LibreOffice Module connectivity (master) 1
DTable.cxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 * This file incorporates work covered by the following license notice:
10 *
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 */
19
20#include <dbase/DTable.hxx>
21#include <com/sun/star/container/ElementExistException.hpp>
22#include <com/sun/star/sdbc/ColumnValue.hpp>
23#include <com/sun/star/sdbc/DataType.hpp>
24#include <com/sun/star/ucb/XContentAccess.hpp>
25#include <com/sun/star/sdbc/XRow.hpp>
26#include <o3tl/safeint.hxx>
27#include <svl/converter.hxx>
28#include <dbase/DConnection.hxx>
29#include <dbase/DColumns.hxx>
30#include <tools/config.hxx>
32#include <dbase/DIndex.hxx>
33#include <dbase/DIndexes.hxx>
35#include <rtl/math.hxx>
36#include <ucbhelper/content.hxx>
37#include <com/sun/star/ucb/ContentCreationException.hpp>
39#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
42#include <o3tl/string_view.hxx>
43#include <comphelper/string.hxx>
45#include <unotools/tempfile.hxx>
47#include <comphelper/types.hxx>
54#include <strings.hrc>
55#include <rtl/strbuf.hxx>
56#include <sal/log.hxx>
57#include <tools/date.hxx>
58#include <i18nutil/calendar.hxx>
59
60#include <algorithm>
61#include <cassert>
62#include <memory>
63#include <string_view>
64
65using namespace ::comphelper;
66using namespace connectivity;
67using namespace connectivity::sdbcx;
68using namespace connectivity::dbase;
69using namespace connectivity::file;
70using namespace ::ucbhelper;
71using namespace ::utl;
72using namespace ::cppu;
73using namespace ::dbtools;
74using namespace ::com::sun::star::uno;
75using namespace ::com::sun::star::ucb;
76using namespace ::com::sun::star::beans;
77using namespace ::com::sun::star::sdbcx;
78using namespace ::com::sun::star::sdbc;
79using namespace ::com::sun::star::container;
80using namespace ::com::sun::star::lang;
81using namespace ::com::sun::star::i18n;
82
83// stored as the Field Descriptor terminator
84#define FIELD_DESCRIPTOR_TERMINATOR 0x0D
85#define DBF_EOL 0x1A
86
87namespace
88{
89std::size_t lcl_getFileSize(SvStream& _rStream)
90{
91 std::size_t nFileSize = 0;
92 _rStream.Seek(STREAM_SEEK_TO_END);
93 _rStream.SeekRel(-1);
94 char cEOL;
95 _rStream.ReadChar( cEOL );
96 nFileSize = _rStream.Tell();
97 if ( cEOL == DBF_EOL )
98 nFileSize -= 1;
99 return nFileSize;
100}
104void lcl_CalcJulDate(sal_Int32& _nJulianDate,sal_Int32& _nJulianTime, const css::util::DateTime& rDateTime)
105{
106 css::util::DateTime aDateTime = rDateTime;
107 // weird: months fix
108 if (aDateTime.Month > 12)
109 {
110 aDateTime.Month--;
111 sal_uInt16 delta = rDateTime.Month / 12;
112 aDateTime.Year += delta;
113 aDateTime.Month -= delta * 12;
114 aDateTime.Month++;
115 }
116
117 _nJulianTime = ((aDateTime.Hours*3600000)+(aDateTime.Minutes*60000)+(aDateTime.Seconds*1000)+(aDateTime.NanoSeconds/1000000));
118 /* conversion factors */
119 sal_uInt16 iy0;
120 sal_uInt16 im0;
121 if ( aDateTime.Month <= 2 )
122 {
123 iy0 = aDateTime.Year - 1;
124 im0 = aDateTime.Month + 12;
125 }
126 else
127 {
128 iy0 = aDateTime.Year;
129 im0 = aDateTime.Month;
130 }
131 sal_Int32 ia = iy0 / 100;
132 sal_Int32 ib = 2 - ia + (ia >> 2);
133 /* calculate julian date */
134 if ( aDateTime.Year <= 0 )
135 {
136 _nJulianDate = static_cast<sal_Int32>((365.25 * iy0) - 0.75)
137 + static_cast<sal_Int32>(i18nutil::monthDaysWithoutJanFeb * (im0 + 1) )
138 + aDateTime.Day + 1720994;
139 } // if ( rDateTime.Year <= 0 )
140 else
141 {
142 _nJulianDate = static_cast<sal_Int32>(365.25 * iy0)
143 + static_cast<sal_Int32>(i18nutil::monthDaysWithoutJanFeb * (im0 + 1))
144 + aDateTime.Day + 1720994;
145 }
146 double JD = _nJulianDate + 0.5;
147 _nJulianDate = static_cast<sal_Int32>( JD + 0.5);
148 const double gyr = aDateTime.Year + (0.01 * aDateTime.Month) + (0.0001 * aDateTime.Day);
149 if ( gyr >= 1582.1015 ) /* on or after 15 October 1582 */
150 _nJulianDate += ib;
151}
152
156void lcl_CalDate(sal_Int32 _nJulianDate,sal_Int32 _nJulianTime,css::util::DateTime& _rDateTime)
157{
158 if ( _nJulianDate )
159 {
160 sal_Int64 ka = _nJulianDate;
161 if ( _nJulianDate >= 2299161 )
162 {
163 sal_Int64 ialp = static_cast<sal_Int64>( (static_cast<double>(_nJulianDate) - 1867216.25 ) / 36524.25 );
164 ka = ka + 1 + ialp - ( ialp >> 2 );
165 }
166 sal_Int64 kb = ka + 1524;
167 sal_Int64 kc = static_cast<sal_Int64>((static_cast<double>(kb) - 122.1) / 365.25);
168 sal_Int64 kd = static_cast<sal_Int64>(static_cast<double>(kc) * 365.25);
169 sal_Int64 ke = static_cast<sal_Int64>(static_cast<double>(kb - kd) / i18nutil::monthDaysWithoutJanFeb);
170 _rDateTime.Day = static_cast<sal_uInt16>(kb - kd - static_cast<sal_Int64>( static_cast<double>(ke) * i18nutil::monthDaysWithoutJanFeb ));
171 if ( ke > 13 )
172 _rDateTime.Month = static_cast<sal_uInt16>(ke - 13);
173 else
174 _rDateTime.Month = static_cast<sal_uInt16>(ke - 1);
175 if ( (_rDateTime.Month == 2) && (_rDateTime.Day > 28) )
176 _rDateTime.Day = 29;
177 if ( (_rDateTime.Month == 2) && (_rDateTime.Day == 29) && (ke == 3) )
178 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4716);
179 else if ( _rDateTime.Month > 2 )
180 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4716);
181 else
182 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4715);
183 }
184
185 if ( _nJulianTime )
186 {
187 double d_s = _nJulianTime / 1000.0;
188 double d_m = d_s / 60.0;
189 double d_h = d_m / 60.0;
190 _rDateTime.Hours = static_cast<sal_uInt16>(d_h);
191 _rDateTime.Minutes = static_cast<sal_uInt16>((d_h - static_cast<double>(_rDateTime.Hours)) * 60.0);
192 _rDateTime.Seconds = static_cast<sal_uInt16>(((d_m - static_cast<double>(_rDateTime.Minutes)) * 60.0)
193 - (static_cast<double>(_rDateTime.Hours) * 3600.0));
194 }
195}
196
197}
198
199
200void ODbaseTable::readHeader()
201{
202 OSL_ENSURE(m_pFileStream,"No Stream available!");
203 if(!m_pFileStream)
204 return;
205 m_pFileStream->RefreshBuffer(); // Make sure, that the header information actually is read again
207
209 m_pFileStream->ReadUChar( nType );
210 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
212
213 m_pFileStream->ReadBytes(m_aHeader.dateElems, 3);
214 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
216
217 m_pFileStream->ReadUInt32( m_aHeader.nbRecords);
218 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
220
222 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
224
226 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
228 if (m_aHeader.recordLength == 0)
230
231 m_pFileStream->ReadBytes(m_aHeader.trailer, 20);
232 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
234
235
236 if ( ( ( m_aHeader.headerLength - 1 ) / 32 - 1 ) <= 0 ) // number of fields
237 {
238 // no dBASE file
240 }
241 else
242 {
243 // Consistency check of the header:
244 m_aHeader.type = static_cast<DBFType>(nType);
245 switch (m_aHeader.type)
246 {
247 case dBaseIII:
248 case dBaseIV:
249 case dBaseV:
250 case VisualFoxPro:
251 case VisualFoxProAuto:
252 case dBaseFS:
253 case dBaseFSMemo:
254 case dBaseIVMemoSQL:
255 case dBaseIIIMemo:
256 case FoxProMemo:
257 m_pFileStream->SetEndian(SvStreamEndian::LITTLE);
260 {
261 m_eEncoding = RTL_TEXTENCODING_IBM_850;
262 }
263 break;
264 case dBaseIVMemo:
265 m_pFileStream->SetEndian(SvStreamEndian::LITTLE);
266 break;
267 default:
268 {
270 }
271 }
272 }
273}
274
276{
278 if (!checkSeek(*m_pFileStream, 32))
279 {
280 SAL_WARN("connectivity.drivers", "ODbaseTable::fillColumns: bad offset!");
281 return;
282 }
283
284 if(!m_aColumns.is())
285 m_aColumns = new OSQLColumns();
286 else
287 m_aColumns->clear();
288
289 m_aTypes.clear();
290 m_aPrecisions.clear();
291 m_aScales.clear();
292
293 // Number of fields:
294 sal_Int32 nFieldCount = (m_aHeader.headerLength - 1) / 32 - 1;
295 if (nFieldCount <= 0)
296 {
297 SAL_WARN("connectivity.drivers", "No columns in table!");
298 return;
299 }
300
301 auto nRemainingsize = m_pFileStream->remainingSize();
302 auto nMaxPossibleRecords = nRemainingsize / 32;
303 if (o3tl::make_unsigned(nFieldCount) > nMaxPossibleRecords)
304 {
305 SAL_WARN("connectivity.drivers", "Parsing error: " << nMaxPossibleRecords <<
306 " max possible entries, but " << nFieldCount << " claimed, truncating");
307 nFieldCount = nMaxPossibleRecords;
308 }
309
310 m_aColumns->reserve(nFieldCount);
311 m_aTypes.reserve(nFieldCount);
312 m_aPrecisions.reserve(nFieldCount);
313 m_aScales.reserve(nFieldCount);
314
315 OUString aTypeName;
316 const bool bCase = getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers();
318
319 sal_Int32 i = 0;
320 for (; i < nFieldCount; i++)
321 {
322 DBFColumn aDBFColumn;
323 m_pFileStream->ReadBytes(aDBFColumn.db_fnm, 11);
324 m_pFileStream->ReadUChar(aDBFColumn.db_typ);
325 m_pFileStream->ReadUInt32(aDBFColumn.db_adr);
326 m_pFileStream->ReadUChar(aDBFColumn.db_flng);
327 m_pFileStream->ReadUChar(aDBFColumn.db_dez);
328 m_pFileStream->ReadBytes(aDBFColumn.db_free2, 14);
329 if (!m_pFileStream->good())
330 {
331 SAL_WARN("connectivity.drivers", "ODbaseTable::fillColumns: short read!");
332 break;
333 }
334 if ( FIELD_DESCRIPTOR_TERMINATOR == aDBFColumn.db_fnm[0] ) // 0x0D stored as the Field Descriptor terminator.
335 break;
336
337 aDBFColumn.db_fnm[sizeof(aDBFColumn.db_fnm)-1] = 0; //ensure null termination for broken input
338 const OUString aColumnName(reinterpret_cast<char *>(aDBFColumn.db_fnm), strlen(reinterpret_cast<char *>(aDBFColumn.db_fnm)), m_eEncoding);
339
340 bool bIsRowVersion = bFoxPro && ( aDBFColumn.db_free2[0] & 0x01 ) == 0x01;
341
342 m_aRealFieldLengths.push_back(aDBFColumn.db_flng);
343 sal_Int32 nPrecision = aDBFColumn.db_flng;
344 sal_Int32 eType;
345 bool bIsCurrency = false;
346
347 char cType[2];
348 cType[0] = aDBFColumn.db_typ;
349 cType[1] = 0;
350 aTypeName = OUString(cType, 1, RTL_TEXTENCODING_ASCII_US);
351 SAL_INFO( "connectivity.drivers","column type: " << aDBFColumn.db_typ);
352
353 switch (aDBFColumn.db_typ)
354 {
355 case 'C':
356 eType = DataType::VARCHAR;
357 aTypeName = "VARCHAR";
358 break;
359 case 'F':
360 case 'N':
361 aTypeName = "DECIMAL";
362 if ( aDBFColumn.db_typ == 'N' )
363 aTypeName = "NUMERIC";
364 eType = DataType::DECIMAL;
365
366 // for numeric fields two characters more are written, then the precision of the column description predescribes,
367 // to keep room for the possible sign and the comma. This has to be considered...
368 nPrecision = SvDbaseConverter::ConvertPrecisionToOdbc(nPrecision,aDBFColumn.db_dez);
369 // This is not true for older versions...
370 break;
371 case 'L':
372 eType = DataType::BIT;
373 aTypeName = "BOOLEAN";
374 break;
375 case 'Y':
376 bIsCurrency = true;
377 eType = DataType::DOUBLE;
378 aTypeName = "DOUBLE";
379 break;
380 case 'D':
381 eType = DataType::DATE;
382 aTypeName = "DATE";
383 break;
384 case 'T':
385 eType = DataType::TIMESTAMP;
386 aTypeName = "TIMESTAMP";
387 break;
388 case 'I':
389 eType = DataType::INTEGER;
390 aTypeName = "INTEGER";
391 break;
392 case 'M':
393 if ( bFoxPro && ( aDBFColumn.db_free2[0] & 0x04 ) == 0x04 )
394 {
395 eType = DataType::LONGVARBINARY;
396 aTypeName = "LONGVARBINARY";
397 }
398 else
399 {
400 aTypeName = "LONGVARCHAR";
401 eType = DataType::LONGVARCHAR;
402 }
403 nPrecision = 2147483647;
404 break;
405 case 'P':
406 aTypeName = "LONGVARBINARY";
407 eType = DataType::LONGVARBINARY;
408 nPrecision = 2147483647;
409 break;
410 case '0':
411 case 'B':
413 {
414 aTypeName = "DOUBLE";
415 eType = DataType::DOUBLE;
416 }
417 else
418 {
419 aTypeName = "LONGVARBINARY";
420 eType = DataType::LONGVARBINARY;
421 nPrecision = 2147483647;
422 }
423 break;
424 default:
425 eType = DataType::OTHER;
426 }
427
428 m_aTypes.push_back(eType);
429 m_aPrecisions.push_back(nPrecision);
430 m_aScales.push_back(aDBFColumn.db_dez);
431
432 Reference< XPropertySet> xCol = new sdbcx::OColumn(aColumnName,
433 aTypeName,
434 OUString(),
435 OUString(),
436 ColumnValue::NULLABLE,
437 nPrecision,
438 aDBFColumn.db_dez,
439 eType,
440 false,
441 bIsRowVersion,
442 bIsCurrency,
443 bCase,
445 m_aColumns->push_back(xCol);
446 } // for (; i < nFieldCount; i++)
447 OSL_ENSURE(i,"No columns in table!");
448}
449
451 : ODbaseTable_BASE(_pTables,_pConnection)
452{
453 // initialize the header
456}
457
459 const OUString& Name,
460 const OUString& Type,
461 const OUString& Description ,
462 const OUString& SchemaName,
463 const OUString& CatalogName )
464 : ODbaseTable_BASE(_pTables,_pConnection,Name,
465 Type,
466 Description,
467 SchemaName,
468 CatalogName)
469{
471}
472
474{
475 // initialize the header
481
482 OUString sFileName(getEntry(m_pConnection, m_Name));
483
485 aURL.SetURL(sFileName);
486
487 OSL_ENSURE( m_pConnection->matchesExtension( aURL.getExtension() ),
488 "ODbaseTable::ODbaseTable: invalid extension!");
489 // getEntry is expected to ensure the correct file name
490
491 m_pFileStream = createStream_simpleError( sFileName, StreamMode::READWRITE | StreamMode::NOCREATE | StreamMode::SHARE_DENYWRITE);
492 m_bWriteable = ( m_pFileStream != nullptr );
493
494 if ( !m_pFileStream )
495 {
496 m_bWriteable = false;
497 m_pFileStream = createStream_simpleError( sFileName, StreamMode::READ | StreamMode::NOCREATE | StreamMode::SHARE_DENYNONE);
498 }
499
500 if (!m_pFileStream)
501 return;
502
503 readHeader();
504
505 std::size_t nFileSize = lcl_getFileSize(*m_pFileStream);
506
507 if (m_aHeader.headerLength > nFileSize)
508 {
509 SAL_WARN("connectivity.drivers", "Parsing error: " << nFileSize <<
510 " max possible size, but " << m_aHeader.headerLength << " claimed, abandoning");
511 return;
512 }
513
515 {
516 std::size_t nMaxPossibleRecords = (nFileSize - m_aHeader.headerLength) / m_aHeader.recordLength;
517 // #i83401# seems to be empty or someone wrote nonsense into the dbase
518 // file try and recover if m_aHeader.db_slng is sane
519 if (m_aHeader.nbRecords == 0)
520 {
521 SAL_WARN("connectivity.drivers", "Parsing warning: 0 records claimed, recovering");
522 m_aHeader.nbRecords = nMaxPossibleRecords;
523 }
524 else if (m_aHeader.nbRecords > nMaxPossibleRecords)
525 {
526 SAL_WARN("connectivity.drivers", "Parsing error: " << nMaxPossibleRecords <<
527 " max possible records, but " << m_aHeader.nbRecords << " claimed, truncating");
528 m_aHeader.nbRecords = std::max(nMaxPossibleRecords, static_cast<size_t>(1));
529 }
530 }
531
532 if (HasMemoFields())
533 {
534 // Create Memo-Filename (.DBT):
535 // nyi: Ugly for Unix and Mac!
536
537 if ( m_aHeader.type == FoxProMemo || m_aHeader.type == VisualFoxPro || m_aHeader.type == VisualFoxProAuto) // foxpro uses another extension
538 aURL.SetExtension(u"fpt");
539 else
540 aURL.SetExtension(u"dbt");
541
542 // If the memo file isn't found, the data will be displayed anyhow.
543 // However, updates can't be done
544 // but the operation is executed
545 m_pMemoStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READWRITE | StreamMode::NOCREATE | StreamMode::SHARE_DENYWRITE);
546 if ( !m_pMemoStream )
547 {
548 m_pMemoStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READ | StreamMode::NOCREATE | StreamMode::SHARE_DENYNONE);
549 }
550 if (m_pMemoStream)
552 }
553
554 fillColumns();
556
557
558 // Buffersize dependent on the file size
559 m_pFileStream->SetBufferSize(nFileSize > 1000000 ? 32768 :
560 nFileSize > 100000 ? 16384 :
561 nFileSize > 10000 ? 4096 : 1024);
562
563 if (m_pMemoStream)
564 {
565 // set the buffer exactly to the length of a record
566 nFileSize = m_pMemoStream->TellEnd();
568
569 // Buffersize dependent on the file size
570 m_pMemoStream->SetBufferSize(nFileSize > 1000000 ? 32768 :
571 nFileSize > 100000 ? 16384 :
572 nFileSize > 10000 ? 4096 :
574 }
575
576 AllocBuffer();
577}
578
580{
581 m_pMemoStream->SetEndian(SvStreamEndian::LITTLE);
582 m_pMemoStream->RefreshBuffer(); // make sure that the header information is actually read again
583 m_pMemoStream->Seek(0);
584
585 (*m_pMemoStream).ReadUInt32( m_aMemoHeader.db_next );
586 switch (m_aHeader.type)
587 {
588 case dBaseIIIMemo: // dBase III: fixed block size
589 case dBaseIVMemo:
590 // sometimes dBase3 is attached to dBase4 memo
591 m_pMemoStream->Seek(20);
592 (*m_pMemoStream).ReadUInt16( m_aMemoHeader.db_size );
593 if (m_aMemoHeader.db_size > 1 && m_aMemoHeader.db_size != 512) // 1 is also for dBase 3
595 else if (m_aMemoHeader.db_size == 512)
596 {
597 // There are files using size specification, though they are dBase-files
598 char sHeader[4];
600 m_pMemoStream->ReadBytes(sHeader, 4);
601
602 if ((m_pMemoStream->GetErrorCode() != ERRCODE_NONE) || static_cast<sal_uInt8>(sHeader[0]) != 0xFF || static_cast<sal_uInt8>(sHeader[1]) != 0xFF || static_cast<sal_uInt8>(sHeader[2]) != 0x08)
604 else
606 }
607 else
608 {
611 }
612 break;
613 case VisualFoxPro:
614 case VisualFoxProAuto:
615 case FoxProMemo:
617 m_pMemoStream->Seek(6);
618 m_pMemoStream->SetEndian(SvStreamEndian::BIG);
619 (*m_pMemoStream).ReadUInt16( m_aMemoHeader.db_size );
620 break;
621 default:
622 SAL_WARN( "connectivity.drivers", "ODbaseTable::ReadMemoHeader: unsupported memo type!" );
623 break;
624 }
625}
626
627OUString ODbaseTable::getEntry(file::OConnection const * _pConnection, std::u16string_view _sName )
628{
629 OUString sURL;
630 try
631 {
632 Reference< XResultSet > xDir = _pConnection->getDir()->getStaticResultSet();
633 Reference< XRow> xRow(xDir,UNO_QUERY);
634 OUString sName;
635 OUString sExt;
637 xDir->beforeFirst();
638 while(xDir->next())
639 {
640 sName = xRow->getString(1);
641 aURL.SetSmartProtocol(INetProtocol::File);
642 OUString sUrl = _pConnection->getURL() + "/" + sName;
643 aURL.SetSmartURL( sUrl );
644
645 // cut the extension
646 sExt = aURL.getExtension();
647
648 // name and extension have to coincide
649 if ( _pConnection->matchesExtension( sExt ) )
650 {
651 sName = sName.replaceAt(sName.getLength() - (sExt.getLength() + 1), sExt.getLength() + 1, u"");
652 if ( sName == _sName )
653 {
654 Reference< XContentAccess > xContentAccess( xDir, UNO_QUERY );
655 sURL = xContentAccess->queryContentIdentifierString();
656 break;
657 }
658 }
659 }
660 xDir->beforeFirst(); // move back to before first record
661 }
662 catch(const Exception&)
663 {
664 OSL_ASSERT(false);
665 }
666 return sURL;
667}
668
670{
671 ::osl::MutexGuard aGuard( m_aMutex );
672
673 ::std::vector< OUString> aVector;
674 aVector.reserve(m_aColumns->size());
675
676 for (auto const& column : *m_aColumns)
677 aVector.push_back(Reference< XNamed>(column,UNO_QUERY_THROW)->getName());
678
679 if(m_xColumns)
680 m_xColumns->reFill(aVector);
681 else
682 m_xColumns.reset(new ODbaseColumns(this,m_aMutex,aVector));
683}
684
686{
687 ::std::vector< OUString> aVector;
688 if(m_pFileStream && (!m_xIndexes || m_xIndexes->getCount() == 0))
689 {
692
693 aURL.setExtension(u"inf");
694 Config aInfFile(aURL.getFSysPath(FSysStyle::Detect));
695 aInfFile.SetGroup(dBASE_III_GROUP);
696 sal_uInt16 nKeyCnt = aInfFile.GetKeyCount();
697 OString aKeyName;
698
699 for (sal_uInt16 nKey = 0; nKey < nKeyCnt; nKey++)
700 {
701 // References the key an index-file?
702 aKeyName = aInfFile.GetKeyName( nKey );
703 //...if yes, add the index list of the table
704 if (aKeyName.startsWith("NDX"))
705 {
706 OString aIndexName = aInfFile.ReadKey(aKeyName);
707 aURL.setName(OStringToOUString(aIndexName, m_eEncoding));
708 try
709 {
711 if (aCnt.isDocument())
712 {
713 aVector.push_back(aURL.getBase());
714 }
715 }
716 catch(const Exception&) // an exception is thrown when no file exists
717 {
718 }
719 }
720 }
721 }
722 if(m_xIndexes)
723 m_xIndexes->reFill(aVector);
724 else
725 m_xIndexes.reset(new ODbaseIndexes(this,m_aMutex,aVector));
726}
727
728
730{
731 OFileTable::disposing();
732 ::osl::MutexGuard aGuard(m_aMutex);
733 m_aColumns = nullptr;
734}
735
737{
739 std::vector<Type> aOwnTypes;
740 aOwnTypes.reserve(aTypes.getLength());
741
742 const Type* pBegin = aTypes.getConstArray();
743 const Type* pEnd = pBegin + aTypes.getLength();
744 for(;pBegin != pEnd;++pBegin)
745 {
746 if(*pBegin != cppu::UnoType<XKeysSupplier>::get() &&
748 {
749 aOwnTypes.push_back(*pBegin);
750 }
751 }
752 aOwnTypes.push_back(cppu::UnoType<css::lang::XUnoTunnel>::get());
753 return Sequence< Type >(aOwnTypes.data(), aOwnTypes.size());
754}
755
756
757Any SAL_CALL ODbaseTable::queryInterface( const Type & rType )
758{
759 if( rType == cppu::UnoType<XKeysSupplier>::get()||
761 return Any();
762
764 return aRet;
765}
766
767
768bool ODbaseTable::fetchRow(OValueRefRow& _rRow, const OSQLColumns & _rCols, bool bRetrieveData)
769{
770 if (!m_pBuffer)
771 return false;
772
773 // Read the data
774 bool bIsCurRecordDeleted = m_pBuffer[0] == '*';
775
776 // only read the bookmark
777
778 // Mark record as deleted
779 _rRow->setDeleted(bIsCurRecordDeleted);
780 *(*_rRow)[0] = m_nFilePos;
781
782 if (!bRetrieveData)
783 return true;
784
785 std::size_t nByteOffset = 1;
786 // Fields:
787 OSQLColumns::const_iterator aIter = _rCols.begin();
788 OSQLColumns::const_iterator aEnd = _rCols.end();
789 const std::size_t nCount = _rRow->size();
790 for (std::size_t i = 1; aIter != aEnd && nByteOffset <= m_nBufferSize && i < nCount;++aIter, i++)
791 {
792 // Lengths depending on data type:
793 sal_Int32 nLen = m_aPrecisions[i-1];
794 sal_Int32 nType = m_aTypes[i-1];
795
796 switch(nType)
797 {
798 case DataType::INTEGER:
799 case DataType::DOUBLE:
800 case DataType::TIMESTAMP:
801 case DataType::DATE:
802 case DataType::BIT:
803 case DataType::LONGVARCHAR:
804 case DataType::LONGVARBINARY:
805 nLen = m_aRealFieldLengths[i-1];
806 break;
807 case DataType::DECIMAL:
809 break; // the sign and the comma
810
811 case DataType::BINARY:
812 case DataType::OTHER:
813 nByteOffset += nLen;
814 continue;
815 }
816
817 // Is the variable bound?
818 if ( !(*_rRow)[i]->isBound() )
819 {
820 // No - next field.
821 nByteOffset += nLen;
822 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
823 continue;
824 } // if ( !(_rRow->get())[i]->isBound() )
825 if ( ( nByteOffset + nLen) > m_nBufferSize )
826 break; // length doesn't match buffer size.
827
828 char *pData = reinterpret_cast<char *>(m_pBuffer.get() + nByteOffset);
829
830 if (nType == DataType::CHAR || nType == DataType::VARCHAR)
831 {
832 sal_Int32 nLastPos = -1;
833 for (sal_Int32 k = 0; k < nLen; ++k)
834 {
835 if (pData[k] != ' ')
836 // Record last non-empty position.
837 nLastPos = k;
838 }
839 if (nLastPos < 0)
840 {
841 // Empty string. Skip it.
842 (*_rRow)[i]->setNull();
843 }
844 else
845 {
846 // Commit the string
847 *(*_rRow)[i] = OUString(pData, static_cast<sal_Int32>(nLastPos+1), m_eEncoding);
848 }
849 } // if (nType == DataType::CHAR || nType == DataType::VARCHAR)
850 else if ( DataType::TIMESTAMP == nType )
851 {
852 sal_Int32 nDate = 0,nTime = 0;
853 if (o3tl::make_unsigned(nLen) < 8)
854 {
855 SAL_WARN("connectivity.drivers", "short TIMESTAMP");
856 return false;
857 }
858 memcpy(&nDate, pData, 4);
859 memcpy(&nTime, pData + 4, 4);
860 if ( !nDate && !nTime )
861 {
862 (*_rRow)[i]->setNull();
863 }
864 else
865 {
866 css::util::DateTime aDateTime;
867 lcl_CalDate(nDate,nTime,aDateTime);
868 *(*_rRow)[i] = aDateTime;
869 }
870 }
871 else if ( DataType::INTEGER == nType )
872 {
873 sal_Int32 nValue = 0;
874 if (o3tl::make_unsigned(nLen) > sizeof(nValue))
875 return false;
876 memcpy(&nValue, pData, nLen);
877 *(*_rRow)[i] = nValue;
878 }
879 else if ( DataType::DOUBLE == nType )
880 {
881 double d = 0.0;
882 if (getBOOL((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency is treated separately
883 {
884 sal_Int64 nValue = 0;
885 if (o3tl::make_unsigned(nLen) > sizeof(nValue))
886 return false;
887 memcpy(&nValue, pData, nLen);
888
889 if ( m_aScales[i-1] )
890 d = (nValue / pow(10.0,static_cast<int>(m_aScales[i-1])));
891 else
892 d = static_cast<double>(nValue);
893 }
894 else
895 {
896 if (o3tl::make_unsigned(nLen) > sizeof(d))
897 return false;
898 memcpy(&d, pData, nLen);
899 }
900
901 *(*_rRow)[i] = d;
902 }
903 else
904 {
905 sal_Int32 nPos1 = -1, nPos2 = -1;
906 // If the string contains Nul-characters, then convert them to blanks!
907 for (sal_Int32 k = 0; k < nLen; k++)
908 {
909 if (pData[k] == '\0')
910 pData[k] = ' ';
911
912 if (pData[k] != ' ')
913 {
914 if (nPos1 < 0)
915 // first non-empty char position.
916 nPos1 = k;
917
918 // last non-empty char position.
919 nPos2 = k;
920 }
921 }
922
923 if (nPos1 < 0)
924 {
925 // Empty string. Skip it.
926 nByteOffset += nLen;
927 (*_rRow)[i]->setNull(); // no values -> done
928 continue;
929 }
930
931 OUString aStr(pData+nPos1, nPos2-nPos1+1, m_eEncoding);
932
933 switch (nType)
934 {
935 case DataType::DATE:
936 {
937 if (nLen < 8 || aStr.getLength() != nLen)
938 {
939 (*_rRow)[i]->setNull();
940 break;
941 }
942 const sal_uInt16 nYear = static_cast<sal_uInt16>(o3tl::toInt32(aStr.subView( 0, 4 )));
943 const sal_uInt16 nMonth = static_cast<sal_uInt16>(o3tl::toInt32(aStr.subView( 4, 2 )));
944 const sal_uInt16 nDay = static_cast<sal_uInt16>(o3tl::toInt32(aStr.subView( 6, 2 )));
945
946 const css::util::Date aDate(nDay,nMonth,nYear);
947 *(*_rRow)[i] = aDate;
948 }
949 break;
950 case DataType::DECIMAL:
951 *(*_rRow)[i] = ORowSetValue(aStr);
952 break;
953 case DataType::BIT:
954 {
955 bool b;
956 switch (*pData)
957 {
958 case 'T':
959 case 'Y':
960 case 'J': b = true; break;
961 default: b = false; break;
962 }
963 *(*_rRow)[i] = b;
964 }
965 break;
966 case DataType::LONGVARBINARY:
967 case DataType::BINARY:
968 case DataType::LONGVARCHAR:
969 {
970 const tools::Long nBlockNo = aStr.toInt32(); // read blocknumber
971 if (nBlockNo > 0 && m_pMemoStream) // Read data from memo-file, only if
972 {
973 if ( !ReadMemo(nBlockNo, (*_rRow)[i]->get()) )
974 break;
975 }
976 else
977 (*_rRow)[i]->setNull();
978 } break;
979 default:
980 SAL_WARN( "connectivity.drivers","Wrong type");
981 }
982 (*_rRow)[i]->setTypeKind(nType);
983 }
984
985 nByteOffset += nLen;
986 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
987 }
988 return true;
989}
990
991
992void ODbaseTable::FileClose()
993{
994 ::osl::MutexGuard aGuard(m_aMutex);
995
996 m_pMemoStream.reset();
997
998 ODbaseTable_BASE::FileClose();
999}
1000
1001bool ODbaseTable::CreateImpl()
1002{
1003 OSL_ENSURE(!m_pFileStream, "SequenceError");
1004
1005 if ( m_pConnection->isCheckEnabled() && ::dbtools::convertName2SQLName(m_Name, u"") != m_Name )
1006 {
1007 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1008 STR_SQL_NAME_ERROR,
1009 "$name$", m_Name
1010 ) );
1011 ::dbtools::throwGenericSQLException( sError, *this );
1012 }
1013
1014 INetURLObject aURL;
1015 aURL.SetSmartProtocol(INetProtocol::File);
1016 OUString aName = getEntry(m_pConnection, m_Name);
1017 if(aName.isEmpty())
1018 {
1019 OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
1020 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
1021 aIdent += "/";
1022 aIdent += m_Name;
1023 aName = aIdent;
1024 }
1025 aURL.SetURL(aName);
1026
1027 if ( !m_pConnection->matchesExtension( aURL.getExtension() ) )
1028 aURL.setExtension(m_pConnection->getExtension());
1029
1030 try
1031 {
1032 Content aContent(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
1033 if (aContent.isDocument())
1034 {
1035 // Only if the file exists with length > 0 raise an error
1036 std::unique_ptr<SvStream> pFileStream(createStream_simpleError( aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE), StreamMode::READ));
1037
1038 if (pFileStream && pFileStream->TellEnd())
1039 return false;
1040 }
1041 }
1042 catch(const Exception&) // an exception is thrown when no file exists
1043 {
1044 }
1045
1046 bool bMemoFile = false;
1047
1048 bool bOk = CreateFile(aURL, bMemoFile);
1049
1050 FileClose();
1051
1052 if (!bOk)
1053 {
1054 try
1055 {
1056 Content aContent(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
1057 aContent.executeCommand( "delete", css::uno::Any( true ) );
1058 }
1059 catch(const Exception&) // an exception is thrown when no file exists
1060 {
1061 }
1062 return false;
1063 }
1064
1065 if (bMemoFile)
1066 {
1067 OUString aExt = aURL.getExtension();
1068 aURL.setExtension(u"dbt"); // extension for memo file
1069
1070 bool bMemoAlreadyExists = false;
1071 try
1072 {
1073 Content aMemo1Content(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
1074 bMemoAlreadyExists = aMemo1Content.isDocument();
1075 }
1076 catch(const Exception&) // an exception is thrown when no file exists
1077 {
1078 }
1079 if (bMemoAlreadyExists)
1080 {
1081 aURL.setExtension(aExt); // kill dbf file
1082 try
1083 {
1084 Content aMemoContent(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
1085 aMemoContent.executeCommand( "delete", css::uno::Any( true ) );
1086 }
1087 catch(const Exception&)
1088 {
1089 css::uno::Any anyEx = cppu::getCaughtException();
1090 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1091 STR_COULD_NOT_DELETE_FILE,
1092 "$name$", aName
1093 ) );
1094 ::dbtools::throwGenericSQLException( sError, *this, anyEx );
1095 }
1096 }
1097 if (!CreateMemoFile(aURL))
1098 {
1099 aURL.setExtension(aExt); // kill dbf file
1100 try
1101 {
1102 Content aMemoContent(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
1103 aMemoContent.executeCommand( "delete", css::uno::Any( true ) );
1104 }
1105 catch(const ContentCreationException&)
1106 {
1107 css::uno::Any anyEx = cppu::getCaughtException();
1108 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1109 STR_COULD_NOT_DELETE_FILE,
1110 "$name$", aName
1111 ) );
1112 ::dbtools::throwGenericSQLException( sError, *this, anyEx );
1113 }
1114 return false;
1115 }
1116 m_aHeader.type = dBaseIIIMemo;
1117 }
1118 else
1119 m_aHeader.type = dBaseIII;
1120
1121 return true;
1122}
1123
1124void ODbaseTable::throwInvalidColumnType(TranslateId pErrorId, const OUString& _sColumnName)
1125{
1126 try
1127 {
1128 // we have to drop the file because it is corrupted now
1129 DropImpl();
1130 }
1131 catch(const Exception&)
1132 {
1133 }
1134
1135 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1136 pErrorId,
1137 "$columnname$", _sColumnName
1138 ) );
1139 ::dbtools::throwGenericSQLException( sError, *this );
1140}
1141
1142// creates in principle dBase IV file format
1143bool ODbaseTable::CreateFile(const INetURLObject& aFile, bool& bCreateMemo)
1144{
1145 bCreateMemo = false;
1146 Date aDate( Date::SYSTEM ); // current date
1147
1148 m_pFileStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::DecodeMechanism::NONE),StreamMode::READWRITE | StreamMode::SHARE_DENYWRITE | StreamMode::TRUNC );
1149
1150 if (!m_pFileStream)
1151 return false;
1152
1153 sal_uInt8 nDbaseType = dBaseIII;
1154 Reference<XIndexAccess> xColumns(getColumns(),UNO_QUERY);
1155 Reference<XPropertySet> xCol;
1156 const OUString sPropType = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE);
1157
1158 try
1159 {
1160 const sal_Int32 nCount = xColumns->getCount();
1161 for(sal_Int32 i=0;i<nCount;++i)
1162 {
1163 xColumns->getByIndex(i) >>= xCol;
1164 OSL_ENSURE(xCol.is(),"This should be a column!");
1165
1166 switch (getINT32(xCol->getPropertyValue(sPropType)))
1167 {
1168 case DataType::DOUBLE:
1169 case DataType::INTEGER:
1170 case DataType::TIMESTAMP:
1171 case DataType::LONGVARBINARY:
1172 nDbaseType = VisualFoxPro;
1173 i = nCount; // no more columns need to be checked
1174 break;
1175 } // switch (getINT32(xCol->getPropertyValue(sPropType)))
1176 }
1177 }
1178 catch ( const Exception& )
1179 {
1180 try
1181 {
1182 // we have to drop the file because it is corrupted now
1183 DropImpl();
1184 }
1185 catch(const Exception&) { }
1186 throw;
1187 }
1188
1189 char aBuffer[21] = {}; // write buffer
1190
1191 m_pFileStream->Seek(0);
1192 (*m_pFileStream).WriteUChar( nDbaseType ); // dBase format
1193 (*m_pFileStream).WriteUChar( aDate.GetYearUnsigned() % 100 ); // current date
1194
1195
1196 (*m_pFileStream).WriteUChar( aDate.GetMonth() );
1197 (*m_pFileStream).WriteUChar( aDate.GetDay() );
1198 (*m_pFileStream).WriteUInt32( 0 ); // number of data records
1199 (*m_pFileStream).WriteUInt16( (m_xColumns->getCount()+1) * 32 + 1 ); // header information,
1200 // pColumns contains always an additional column
1201 (*m_pFileStream).WriteUInt16( 0 ); // record length will be determined later
1202 m_pFileStream->WriteBytes(aBuffer, 20);
1203
1204 sal_uInt16 nRecLength = 1; // Length 1 for deleted flag
1205 sal_Int32 nMaxFieldLength = m_pConnection->getMetaData()->getMaxColumnNameLength();
1206 OUString aName;
1207 const OUString sPropName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
1208 const OUString sPropPrec = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION);
1209 const OUString sPropScale = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE);
1210
1211 try
1212 {
1213 const sal_Int32 nCount = xColumns->getCount();
1214 for(sal_Int32 i=0;i<nCount;++i)
1215 {
1216 xColumns->getByIndex(i) >>= xCol;
1217 OSL_ENSURE(xCol.is(),"This should be a column!");
1218
1219 char cTyp( 'C' );
1220
1221 xCol->getPropertyValue(sPropName) >>= aName;
1222
1223 OString aCol;
1224 if ( DBTypeConversion::convertUnicodeString( aName, aCol, m_eEncoding ) > nMaxFieldLength)
1225 {
1226 throwInvalidColumnType( STR_INVALID_COLUMN_NAME_LENGTH, aName );
1227 }
1228
1229 m_pFileStream->WriteOString( aCol );
1230 m_pFileStream->WriteBytes(aBuffer, 11 - aCol.getLength());
1231
1232 sal_Int32 nPrecision = 0;
1233 xCol->getPropertyValue(sPropPrec) >>= nPrecision;
1234 sal_Int32 nScale = 0;
1235 xCol->getPropertyValue(sPropScale) >>= nScale;
1236
1237 bool bBinary = false;
1238
1239 switch (getINT32(xCol->getPropertyValue(sPropType)))
1240 {
1241 case DataType::CHAR:
1242 case DataType::VARCHAR:
1243 cTyp = 'C';
1244 break;
1245 case DataType::DOUBLE:
1246 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency will be treated separately
1247 cTyp = 'Y';
1248 else
1249 cTyp = 'B';
1250 break;
1251 case DataType::INTEGER:
1252 cTyp = 'I';
1253 break;
1254 case DataType::TINYINT:
1255 case DataType::SMALLINT:
1256 case DataType::BIGINT:
1257 case DataType::DECIMAL:
1258 case DataType::NUMERIC:
1259 case DataType::REAL:
1260 cTyp = 'N'; // only dBase 3 format
1261 break;
1262 case DataType::TIMESTAMP:
1263 cTyp = 'T';
1264 break;
1265 case DataType::DATE:
1266 cTyp = 'D';
1267 break;
1268 case DataType::BIT:
1269 cTyp = 'L';
1270 break;
1271 case DataType::LONGVARBINARY:
1272 bBinary = true;
1273 [[fallthrough]];
1274 case DataType::LONGVARCHAR:
1275 cTyp = 'M';
1276 break;
1277 default:
1278 {
1279 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1280 }
1281 }
1282
1283 (*m_pFileStream).WriteChar( cTyp );
1284 if ( nDbaseType == VisualFoxPro )
1285 (*m_pFileStream).WriteUInt32( nRecLength-1 );
1286 else
1287 m_pFileStream->WriteBytes(aBuffer, 4);
1288
1289 switch(cTyp)
1290 {
1291 case 'C':
1292 OSL_ENSURE(nPrecision < 255, "ODbaseTable::Create: Column too long!");
1293 if (nPrecision > 254)
1294 {
1295 throwInvalidColumnType(STR_INVALID_COLUMN_PRECISION, aName);
1296 }
1297 (*m_pFileStream).WriteUChar( std::min(static_cast<unsigned>(nPrecision), 255U) ); // field length
1298 nRecLength = nRecLength + static_cast<sal_uInt16>(std::min(static_cast<sal_uInt16>(nPrecision), sal_uInt16(255UL)));
1299 (*m_pFileStream).WriteUChar( 0 ); // decimals
1300 break;
1301 case 'F':
1302 case 'N':
1303 OSL_ENSURE(nPrecision >= nScale,
1304 "ODbaseTable::Create: Field length must be larger than decimal places!");
1305 if (nPrecision < nScale)
1306 {
1307 throwInvalidColumnType(STR_INVALID_PRECISION_SCALE, aName);
1308 }
1309 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency will be treated separately
1310 {
1311 (*m_pFileStream).WriteUChar( 10 ); // standard length
1312 (*m_pFileStream).WriteUChar( 4 );
1313 nRecLength += 10;
1314 }
1315 else
1316 {
1317 sal_Int32 nPrec = SvDbaseConverter::ConvertPrecisionToDbase(nPrecision,nScale);
1318
1319 (*m_pFileStream).WriteUChar( nPrec );
1320 (*m_pFileStream).WriteUChar( nScale );
1321 nRecLength += static_cast<sal_uInt16>(nPrec);
1322 }
1323 break;
1324 case 'L':
1325 (*m_pFileStream).WriteUChar( 1 );
1326 (*m_pFileStream).WriteUChar( 0 );
1327 ++nRecLength;
1328 break;
1329 case 'I':
1330 (*m_pFileStream).WriteUChar( 4 );
1331 (*m_pFileStream).WriteUChar( 0 );
1332 nRecLength += 4;
1333 break;
1334 case 'Y':
1335 case 'B':
1336 case 'T':
1337 case 'D':
1338 (*m_pFileStream).WriteUChar( 8 );
1339 (*m_pFileStream).WriteUChar( 0 );
1340 nRecLength += 8;
1341 break;
1342 case 'M':
1343 bCreateMemo = true;
1344 (*m_pFileStream).WriteUChar( 10 );
1345 (*m_pFileStream).WriteUChar( 0 );
1346 nRecLength += 10;
1347 if ( bBinary )
1348 aBuffer[0] = 0x06;
1349 break;
1350 default:
1351 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1352 }
1353 m_pFileStream->WriteBytes(aBuffer, 14);
1354 aBuffer[0] = 0x00;
1355 }
1356
1357 (*m_pFileStream).WriteUChar( FIELD_DESCRIPTOR_TERMINATOR ); // end of header
1358 (*m_pFileStream).WriteChar( char(DBF_EOL) );
1359 m_pFileStream->Seek(10);
1360 (*m_pFileStream).WriteUInt16( nRecLength ); // set record length afterwards
1361
1362 if (bCreateMemo)
1363 {
1364 m_pFileStream->Seek(0);
1365 if (nDbaseType == VisualFoxPro)
1366 (*m_pFileStream).WriteUChar( FoxProMemo );
1367 else
1368 (*m_pFileStream).WriteUChar( dBaseIIIMemo );
1369 } // if (bCreateMemo)
1370 }
1371 catch ( const Exception& )
1372 {
1373 try
1374 {
1375 // we have to drop the file because it is corrupted now
1376 DropImpl();
1377 }
1378 catch(const Exception&) { }
1379 throw;
1380 }
1381 return true;
1382}
1383
1384bool ODbaseTable::HasMemoFields() const
1385{
1386 return m_aHeader.type > dBaseIV && !utl::ConfigManager::IsFuzzing();
1387}
1388
1389// creates in principle dBase III file format
1390bool ODbaseTable::CreateMemoFile(const INetURLObject& aFile)
1391{
1392 // filehandling macro for table creation
1393 m_pMemoStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::DecodeMechanism::NONE),StreamMode::READWRITE | StreamMode::SHARE_DENYWRITE);
1394
1395 if (!m_pMemoStream)
1396 return false;
1397
1398 m_pMemoStream->SetStreamSize(512);
1399
1400 m_pMemoStream->Seek(0);
1401 (*m_pMemoStream).WriteUInt32( 1 ); // pointer to the first free block
1402
1403 m_pMemoStream.reset();
1404 return true;
1405}
1406
1407bool ODbaseTable::Drop_Static(std::u16string_view _sUrl, bool _bHasMemoFields, OCollection* _pIndexes )
1408{
1409 INetURLObject aURL;
1410 aURL.SetURL(_sUrl);
1411
1412 bool bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE));
1413
1414 if(bDropped)
1415 {
1416 if (_bHasMemoFields)
1417 { // delete the memo fields
1418 aURL.setExtension(u"dbt");
1419 bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE));
1420 }
1421
1422 if(bDropped)
1423 {
1424 if(_pIndexes)
1425 {
1426 try
1427 {
1428 sal_Int32 i = _pIndexes->getCount();
1429 while (i)
1430 {
1431 _pIndexes->dropByIndex(--i);
1432 }
1433 }
1434 catch(const SQLException&)
1435 {
1436 }
1437 }
1438 aURL.setExtension(u"inf");
1439
1440 // as the inf file does not necessarily exist, we aren't allowed to use UCBContentHelper::Kill
1441 try
1442 {
1443 ::ucbhelper::Content aDeleteContent( aURL.GetMainURL( INetURLObject::DecodeMechanism::NONE ), Reference< XCommandEnvironment >(), comphelper::getProcessComponentContext() );
1444 aDeleteContent.executeCommand( "delete", Any( true ) );
1445 }
1446 catch(const Exception&)
1447 {
1448 // silently ignore this...
1449 }
1450 }
1451 }
1452 return bDropped;
1453}
1454
1455bool ODbaseTable::DropImpl()
1456{
1457 FileClose();
1458
1459 if(!m_xIndexes)
1460 refreshIndexes(); // look for indexes which must be deleted as well
1461
1462 bool bDropped = Drop_Static(getEntry(m_pConnection,m_Name),HasMemoFields(),m_xIndexes.get());
1463 if(!bDropped)
1464 {// we couldn't drop the table so we have to reopen it
1465 construct();
1466 if(m_xColumns)
1467 m_xColumns->refresh();
1468 }
1469 return bDropped;
1470}
1471
1472
1473bool ODbaseTable::InsertRow(OValueRefVector& rRow, const Reference<XIndexAccess>& _xCols)
1474{
1475 // fill buffer with blanks
1476 if (!AllocBuffer())
1477 return false;
1478
1479 memset(m_pBuffer.get(), 0, m_aHeader.recordLength);
1480 m_pBuffer[0] = ' ';
1481
1482 // Copy new row completely:
1483 // ... and add at the end as new Record:
1484 std::size_t nTempPos = m_nFilePos;
1485
1486 m_nFilePos = static_cast<std::size_t>(m_aHeader.nbRecords) + 1;
1487 bool bInsertRow = UpdateBuffer( rRow, nullptr, _xCols, true );
1488 if ( bInsertRow )
1489 {
1490 std::size_t nFileSize = 0, nMemoFileSize = 0;
1491
1492 nFileSize = lcl_getFileSize(*m_pFileStream);
1493
1494 if (HasMemoFields() && m_pMemoStream)
1495 {
1496 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1497 nMemoFileSize = m_pMemoStream->Tell();
1498 }
1499
1500 if (!WriteBuffer())
1501 {
1502 m_pFileStream->SetStreamSize(nFileSize); // restore old size
1503
1504 if (HasMemoFields() && m_pMemoStream)
1505 m_pMemoStream->SetStreamSize(nMemoFileSize); // restore old size
1506 m_nFilePos = nTempPos; // restore file position
1507 }
1508 else
1509 {
1510 (*m_pFileStream).WriteChar( char(DBF_EOL) ); // write EOL
1511 // raise number of datasets in the header:
1512 m_pFileStream->Seek( 4 );
1513 (*m_pFileStream).WriteUInt32( m_aHeader.nbRecords + 1 );
1514
1515 m_pFileStream->Flush();
1516
1517 // raise number if successfully
1518 m_aHeader.nbRecords++;
1519 *rRow[0] = m_nFilePos; // set bookmark
1520 m_nFilePos = nTempPos;
1521 }
1522 }
1523 else
1524 m_nFilePos = nTempPos;
1525
1526 return bInsertRow;
1527}
1528
1529
1530bool ODbaseTable::UpdateRow(OValueRefVector& rRow, OValueRefRow& pOrgRow, const Reference<XIndexAccess>& _xCols)
1531{
1532 // fill buffer with blanks
1533 if (!AllocBuffer())
1534 return false;
1535
1536 // position on desired record:
1537 std::size_t nPos = m_aHeader.headerLength + static_cast<tools::Long>(m_nFilePos-1) * m_aHeader.recordLength;
1538 m_pFileStream->Seek(nPos);
1539 m_pFileStream->ReadBytes(m_pBuffer.get(), m_aHeader.recordLength);
1540
1541 std::size_t nMemoFileSize( 0 );
1542 if (HasMemoFields() && m_pMemoStream)
1543 {
1544 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1545 nMemoFileSize = m_pMemoStream->Tell();
1546 }
1547 if (!UpdateBuffer(rRow, pOrgRow, _xCols, false) || !WriteBuffer())
1548 {
1549 if (HasMemoFields() && m_pMemoStream)
1550 m_pMemoStream->SetStreamSize(nMemoFileSize); // restore old size
1551 }
1552 else
1553 {
1554 m_pFileStream->Flush();
1555 }
1556 return true;
1557}
1558
1559
1560bool ODbaseTable::DeleteRow(const OSQLColumns& _rCols)
1561{
1562 // Set the Delete-Flag (be it set or not):
1563 // Position on desired record:
1564 std::size_t nFilePos = m_aHeader.headerLength + static_cast<tools::Long>(m_nFilePos-1) * m_aHeader.recordLength;
1565 m_pFileStream->Seek(nFilePos);
1566
1567 OValueRefRow aRow = new OValueRefVector(_rCols.size());
1568
1569 if (!fetchRow(aRow,_rCols,true))
1570 return false;
1571
1572 Reference<XPropertySet> xCol;
1573 OUString aColName;
1574 ::comphelper::UStringMixEqual aCase(isCaseSensitive());
1575 for (sal_Int32 i = 0; i < m_xColumns->getCount(); i++)
1576 {
1577 Reference<XPropertySet> xIndex = isUniqueByColumnName(i);
1578 if (xIndex.is())
1579 {
1580 xCol.set(m_xColumns->getByIndex(i), css::uno::UNO_QUERY);
1581 OSL_ENSURE(xCol.is(),"ODbaseTable::DeleteRow column is null!");
1582 if(xCol.is())
1583 {
1584 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1585
1586 ODbaseIndex* pIndex = dynamic_cast<ODbaseIndex*>(xIndex.get());
1587 assert(pIndex && "ODbaseTable::DeleteRow: No Index returned!");
1588
1589 OSQLColumns::const_iterator aIter = std::find_if(_rCols.begin(), _rCols.end(),
1590 [&aCase, &aColName](const OSQLColumns::value_type& rxCol) {
1591 return aCase(getString(rxCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME))), aColName); });
1592 if (aIter == _rCols.end())
1593 continue;
1594
1595 auto nPos = static_cast<sal_Int32>(std::distance(_rCols.begin(), aIter)) + 1;
1596 pIndex->Delete(m_nFilePos,*(*aRow)[nPos]);
1597 }
1598 }
1599 }
1600
1601 m_pFileStream->Seek(nFilePos);
1602 (*m_pFileStream).WriteUChar( '*' ); // mark the row in the table as deleted
1603 m_pFileStream->Flush();
1604 return true;
1605}
1606
1607Reference<XPropertySet> ODbaseTable::isUniqueByColumnName(sal_Int32 _nColumnPos)
1608{
1609 if(!m_xIndexes)
1610 refreshIndexes();
1611 if(m_xIndexes->hasElements())
1612 {
1613 Reference<XPropertySet> xCol;
1614 m_xColumns->getByIndex(_nColumnPos) >>= xCol;
1615 OSL_ENSURE(xCol.is(),"ODbaseTable::isUniqueByColumnName column is null!");
1616 OUString sColName;
1617 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sColName;
1618
1619 Reference<XPropertySet> xIndex;
1620 for(sal_Int32 i=0;i<m_xIndexes->getCount();++i)
1621 {
1622 xIndex.set(m_xIndexes->getByIndex(i), css::uno::UNO_QUERY);
1623 if(xIndex.is() && getBOOL(xIndex->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISUNIQUE))))
1624 {
1625 Reference<XNameAccess> xCols(Reference<XColumnsSupplier>(xIndex,UNO_QUERY_THROW)->getColumns());
1626 if(xCols->hasByName(sColName))
1627 return xIndex;
1628
1629 }
1630 }
1631 }
1632 return Reference<XPropertySet>();
1633}
1634
1635static double toDouble(std::string_view rString)
1636{
1637 return ::rtl::math::stringToDouble( rString, '.', ',' );
1638}
1639
1640
1641bool ODbaseTable::UpdateBuffer(OValueRefVector& rRow, const OValueRefRow& pOrgRow, const Reference<XIndexAccess>& _xCols, const bool bForceAllFields)
1642{
1643 OSL_ENSURE(m_pBuffer,"Buffer is NULL!");
1644 if ( !m_pBuffer )
1645 return false;
1646 sal_Int32 nByteOffset = 1;
1647
1648 // Update fields:
1649 Reference<XPropertySet> xCol;
1650 Reference<XPropertySet> xIndex;
1651 OUString aColName;
1652 const sal_Int32 nColumnCount = m_xColumns->getCount();
1653 std::vector< Reference<XPropertySet> > aIndexedCols(nColumnCount);
1654
1655 ::comphelper::UStringMixEqual aCase(isCaseSensitive());
1656
1657 Reference<XIndexAccess> xColumns(m_xColumns.get());
1658 // first search a key that exist already in the table
1659 for (sal_Int32 i = 0; i < nColumnCount; ++i)
1660 {
1661 sal_Int32 nPos = i;
1662 if(_xCols != xColumns)
1663 {
1664 m_xColumns->getByIndex(i) >>= xCol;
1665 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1666 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1667
1668 for(nPos = 0;nPos<_xCols->getCount();++nPos)
1669 {
1670 Reference<XPropertySet> xFindCol(
1671 _xCols->getByIndex(nPos), css::uno::UNO_QUERY);
1672 OSL_ENSURE(xFindCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1673 if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1674 break;
1675 }
1676 if (nPos >= _xCols->getCount())
1677 continue;
1678 }
1679
1680 ++nPos;
1681 xIndex = isUniqueByColumnName(i);
1682 aIndexedCols[i] = xIndex;
1683 if (xIndex.is())
1684 {
1685 // first check if the value is different to the old one and when if it conform to the index
1686 if(pOrgRow.is() && (rRow[nPos]->getValue().isNull() || rRow[nPos] == (*pOrgRow)[nPos]))
1687 continue;
1688 else
1689 {
1690 ODbaseIndex* pIndex = dynamic_cast<ODbaseIndex*>(xIndex.get());
1691 assert(pIndex && "ODbaseTable::UpdateBuffer: No Index returned!");
1692
1693 if (pIndex->Find(0,*rRow[nPos]))
1694 {
1695 // There is no unique value
1696 if ( aColName.isEmpty() )
1697 {
1698 m_xColumns->getByIndex(i) >>= xCol;
1699 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1700 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1701 xCol.clear();
1702 } // if ( !aColName.getLength() )
1703 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1704 STR_DUPLICATE_VALUE_IN_COLUMN
1705 ,"$columnname$", aColName
1706 ) );
1707 ::dbtools::throwGenericSQLException( sError, *this );
1708 }
1709 }
1710 }
1711 }
1712
1713 // when we are here there is no double key in the table
1714
1715 for (sal_Int32 i = 0; i < nColumnCount && nByteOffset <= m_nBufferSize ; ++i)
1716 {
1717 // Lengths for each data type:
1718 assert(i >= 0);
1719 OSL_ENSURE(o3tl::make_unsigned(i) < m_aPrecisions.size(),"Illegal index!");
1720 sal_Int32 nLen = 0;
1721 sal_Int32 nType = 0;
1722 sal_Int32 nScale = 0;
1723 if ( o3tl::make_unsigned(i) < m_aPrecisions.size() )
1724 {
1725 nLen = m_aPrecisions[i];
1726 nType = m_aTypes[i];
1727 nScale = m_aScales[i];
1728 }
1729 else
1730 {
1731 m_xColumns->getByIndex(i) >>= xCol;
1732 if ( xCol.is() )
1733 {
1734 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)) >>= nLen;
1735 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1736 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1737 }
1738 }
1739
1740 bool bSetZero = false;
1741 switch (nType)
1742 {
1743 case DataType::INTEGER:
1744 case DataType::DOUBLE:
1745 case DataType::TIMESTAMP:
1746 bSetZero = true;
1747 [[fallthrough]];
1748 case DataType::LONGVARBINARY:
1749 case DataType::DATE:
1750 case DataType::BIT:
1751 case DataType::LONGVARCHAR:
1752 nLen = m_aRealFieldLengths[i];
1753 break;
1754 case DataType::DECIMAL:
1755 nLen = SvDbaseConverter::ConvertPrecisionToDbase(nLen,nScale);
1756 break; // The sign and the comma
1757 default:
1758 break;
1759
1760 } // switch (nType)
1761
1762 sal_Int32 nPos = i;
1763 if(_xCols != xColumns)
1764 {
1765 m_xColumns->getByIndex(i) >>= xCol;
1766 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1767 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1768 for(nPos = 0;nPos<_xCols->getCount();++nPos)
1769 {
1770 Reference<XPropertySet> xFindCol(
1771 _xCols->getByIndex(nPos), css::uno::UNO_QUERY);
1772 if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1773 break;
1774 }
1775 if (nPos >= _xCols->getCount())
1776 {
1777 nByteOffset += nLen;
1778 continue;
1779 }
1780 }
1781
1782
1783 ++nPos; // the row values start at 1
1784 const ORowSetValue &thisColVal = rRow[nPos]->get();
1785 const bool thisColIsBound = thisColVal.isBound();
1786 const bool thisColIsNull = !thisColIsBound || thisColVal.isNull();
1787 // don't overwrite non-bound columns
1788 if ( ! (bForceAllFields || thisColIsBound) )
1789 {
1790 // No - don't overwrite this field, it has not changed.
1791 nByteOffset += nLen;
1792 continue;
1793 }
1794 if (aIndexedCols[i].is())
1795 {
1796 ODbaseIndex* pIndex = dynamic_cast<ODbaseIndex*>(aIndexedCols[i].get());
1797 assert(pIndex && "ODbaseTable::UpdateBuffer: No Index returned!");
1798 // Update !!
1799 if (pOrgRow.is() && !thisColIsNull)
1800 pIndex->Update(m_nFilePos, *(*pOrgRow)[nPos], thisColVal);
1801 else
1802 pIndex->Insert(m_nFilePos, thisColVal);
1803 }
1804
1805 char* pData = reinterpret_cast<char *>(m_pBuffer.get() + nByteOffset);
1806 if (thisColIsNull)
1807 {
1808 if ( bSetZero )
1809 memset(pData,0,nLen); // Clear to NULL char ('\0')
1810 else
1811 memset(pData,' ',nLen); // Clear to space/blank ('\0x20')
1812 nByteOffset += nLen;
1813 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1814 continue;
1815 }
1816
1817 try
1818 {
1819 switch (nType)
1820 {
1821 case DataType::TIMESTAMP:
1822 {
1823 sal_Int32 nJulianDate = 0, nJulianTime = 0;
1824 lcl_CalcJulDate(nJulianDate,nJulianTime, thisColVal.getDateTime());
1825 // Exactly 8 bytes to copy:
1826 memcpy(pData,&nJulianDate,4);
1827 memcpy(pData+4,&nJulianTime,4);
1828 }
1829 break;
1830 case DataType::DATE:
1831 {
1832 css::util::Date aDate;
1833 if(thisColVal.getTypeKind() == DataType::DOUBLE)
1834 aDate = ::dbtools::DBTypeConversion::toDate(thisColVal.getDouble());
1835 else
1836 aDate = thisColVal.getDate();
1837 char s[sizeof("-327686553565535")];
1838 // reserve enough space for hypothetical max length
1839 snprintf(s,
1840 sizeof(s),
1841 "%04" SAL_PRIdINT32 "%02" SAL_PRIuUINT32 "%02" SAL_PRIuUINT32,
1842 static_cast<sal_Int32>(aDate.Year),
1843 static_cast<sal_uInt32>(aDate.Month),
1844 static_cast<sal_uInt32>(aDate.Day));
1845
1846 // Exactly 8 bytes to copy (even if s could hypothetically be longer):
1847 memcpy(pData,s,8);
1848 } break;
1849 case DataType::INTEGER:
1850 {
1851 sal_Int32 nValue = thisColVal.getInt32();
1852 if (o3tl::make_unsigned(nLen) > sizeof(nValue))
1853 return false;
1854 memcpy(pData,&nValue,nLen);
1855 }
1856 break;
1857 case DataType::DOUBLE:
1858 {
1859 const double d = thisColVal.getDouble();
1860 m_xColumns->getByIndex(i) >>= xCol;
1861
1862 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency is treated separately
1863 {
1864 sal_Int64 nValue = 0;
1865 if ( m_aScales[i] )
1866 nValue = static_cast<sal_Int64>(d * pow(10.0,static_cast<int>(m_aScales[i])));
1867 else
1868 nValue = static_cast<sal_Int64>(d);
1869 if (o3tl::make_unsigned(nLen) > sizeof(nValue))
1870 return false;
1871 memcpy(pData,&nValue,nLen);
1872 } // if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency is treated separately
1873 else
1874 {
1875 if (o3tl::make_unsigned(nLen) > sizeof(d))
1876 return false;
1877 memcpy(pData,&d,nLen);
1878 }
1879 }
1880 break;
1881 case DataType::DECIMAL:
1882 {
1883 memset(pData,' ',nLen); // Clear to NULL
1884
1885 const double n = thisColVal.getDouble();
1886
1887 // one, because const_cast GetFormatPrecision on SvNumberFormat is not constant,
1888 // even though it really could and should be
1889 const OString aDefaultValue( ::rtl::math::doubleToString( n, rtl_math_StringFormat_F, nScale, '.', nullptr, 0));
1890 const sal_Int32 nValueLen = aDefaultValue.getLength();
1891 if ( nValueLen <= nLen )
1892 {
1893 // Write value right-justified, padded with blanks to the left.
1894 memcpy(pData+nLen-nValueLen,aDefaultValue.getStr(),nValueLen);
1895 // write the resulting double back
1896 *rRow[nPos] = toDouble(aDefaultValue);
1897 }
1898 else
1899 {
1900 m_xColumns->getByIndex(i) >>= xCol;
1901 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1902 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1903 std::vector< std::pair<const char* , OUString > > aStringToSubstitutes
1904 {
1905 { "$columnname$", aColName },
1906 { "$precision$", OUString::number(nLen) },
1907 { "$scale$", OUString::number(nScale) },
1908 { "$value$", OStringToOUString(aDefaultValue,RTL_TEXTENCODING_UTF8) }
1909 };
1910
1911 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1912 STR_INVALID_COLUMN_DECIMAL_VALUE
1913 ,aStringToSubstitutes
1914 ) );
1915 ::dbtools::throwGenericSQLException( sError, *this );
1916 }
1917 } break;
1918 case DataType::BIT:
1919 *pData = thisColVal.getBool() ? 'T' : 'F';
1920 break;
1921 case DataType::LONGVARBINARY:
1922 case DataType::LONGVARCHAR:
1923 {
1924 char cNext = pData[nLen]; // Mark's scratch and replaced by 0
1925 pData[nLen] = '\0'; // This is because the buffer is always a sign of greater ...
1926
1927 std::size_t nBlockNo = strtol(pData,nullptr,10); // Block number read
1928
1929 // Next initial character restore again:
1930 pData[nLen] = cNext;
1931 if (!m_pMemoStream)
1932 break;
1933 WriteMemo(thisColVal, nBlockNo);
1934
1935 OString aBlock(OString::number(nBlockNo));
1936 //align aBlock at the right of a nLen sequence, fill to the left with '0'
1937 OStringBuffer aStr;
1938 comphelper::string::padToLength(aStr, nLen - aBlock.getLength(), '0');
1939 aStr.append(aBlock);
1940
1941 // Copy characters:
1942 memcpy(pData, aStr.getStr(), nLen);
1943 } break;
1944 default:
1945 {
1946 memset(pData,' ',nLen); // Clear to NULL
1947
1948 OUString sStringToWrite( thisColVal.getString() );
1949
1950 // convert the string, using the connection's encoding
1951 OString sEncoded;
1952
1953 DBTypeConversion::convertUnicodeStringToLength( sStringToWrite, sEncoded, nLen, m_eEncoding );
1954 memcpy( pData, sEncoded.getStr(), sEncoded.getLength() );
1955
1956 }
1957 break;
1958 }
1959 }
1960 catch( const SQLException& )
1961 {
1962 throw;
1963 }
1964 catch ( const Exception& )
1965 {
1966 m_xColumns->getByIndex(i) >>= xCol;
1967 OSL_ENSURE( xCol.is(), "ODbaseTable::UpdateBuffer column is null!" );
1968 if ( xCol.is() )
1969 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1970
1971 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1972 STR_INVALID_COLUMN_VALUE,
1973 "$columnname$", aColName
1974 ) );
1975 ::dbtools::throwGenericSQLException( sError, *this );
1976 }
1977 // And more ...
1978 nByteOffset += nLen;
1979 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1980 }
1981 return true;
1982}
1983
1984
1985void ODbaseTable::WriteMemo(const ORowSetValue& aVariable, std::size_t& rBlockNr)
1986{
1987 // if the BlockNo 0 is given, the block will be appended at the end
1988 std::size_t nSize = 0;
1989 OString aStr;
1990 css::uno::Sequence<sal_Int8> aValue;
1991 sal_uInt8 nHeader[4];
1992 const bool bBinary = aVariable.getTypeKind() == DataType::LONGVARBINARY && m_aMemoHeader.db_typ == MemoFoxPro;
1993 if ( bBinary )
1994 {
1995 aValue = aVariable.getSequence();
1996 nSize = aValue.getLength();
1997 }
1998 else
1999 {
2000 nSize = DBTypeConversion::convertUnicodeString( aVariable.getString(), aStr, m_eEncoding );
2001 }
2002
2003 // append or overwrite
2004 bool bAppend = rBlockNr == 0;
2005
2006 if (!bAppend)
2007 {
2008 switch (m_aMemoHeader.db_typ)
2009 {
2010 case MemodBaseIII: // dBase III-Memofield, ends with 2 * Ctrl-Z
2011 bAppend = nSize > (512 - 2);
2012 break;
2013 case MemoFoxPro:
2014 case MemodBaseIV: // dBase IV-Memofield with length
2015 {
2016 char sHeader[4];
2017 m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2018 m_pMemoStream->SeekRel(4);
2019 m_pMemoStream->ReadBytes(sHeader, 4);
2020
2021 std::size_t nOldSize;
2022 if (m_aMemoHeader.db_typ == MemoFoxPro)
2023 nOldSize = ((static_cast<unsigned char>(sHeader[0]) * 256 +
2024 static_cast<unsigned char>(sHeader[1])) * 256 +
2025 static_cast<unsigned char>(sHeader[2])) * 256 +
2026 static_cast<unsigned char>(sHeader[3]);
2027 else
2028 nOldSize = ((static_cast<unsigned char>(sHeader[3]) * 256 +
2029 static_cast<unsigned char>(sHeader[2])) * 256 +
2030 static_cast<unsigned char>(sHeader[1])) * 256 +
2031 static_cast<unsigned char>(sHeader[0]) - 8;
2032
2033 // fits the new length in the used blocks
2034 std::size_t nUsedBlocks = ((nSize + 8) / m_aMemoHeader.db_size) + (((nSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0),
2035 nOldUsedBlocks = ((nOldSize + 8) / m_aMemoHeader.db_size) + (((nOldSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0);
2036 bAppend = nUsedBlocks > nOldUsedBlocks;
2037 }
2038 }
2039 }
2040
2041 if (bAppend)
2042 {
2043 sal_uInt64 const nStreamSize = m_pMemoStream->TellEnd();
2044 // fill last block
2045 rBlockNr = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2046
2047 m_pMemoStream->SetStreamSize(rBlockNr * m_aMemoHeader.db_size);
2048 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2049 }
2050 else
2051 {
2052 m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2053 }
2054
2055 switch (m_aMemoHeader.db_typ)
2056 {
2057 case MemodBaseIII: // dBase III-Memofield, ends with Ctrl-Z
2058 {
2059 const char cEOF = char(DBF_EOL);
2060 nSize++;
2061 m_pMemoStream->WriteBytes(aStr.getStr(), aStr.getLength());
2062 m_pMemoStream->WriteChar( cEOF ).WriteChar( cEOF );
2063 } break;
2064 case MemoFoxPro:
2065 case MemodBaseIV: // dBase IV-Memofield with length
2066 {
2067 if ( MemodBaseIV == m_aMemoHeader.db_typ )
2068 (*m_pMemoStream).WriteUChar( 0xFF )
2069 .WriteUChar( 0xFF )
2070 .WriteUChar( 0x08 );
2071 else
2072 (*m_pMemoStream).WriteUChar( 0x00 )
2073 .WriteUChar( 0x00 )
2074 .WriteUChar( 0x00 );
2075
2076 sal_uInt32 nWriteSize = nSize;
2077 if (m_aMemoHeader.db_typ == MemoFoxPro)
2078 {
2079 if ( bBinary )
2080 (*m_pMemoStream).WriteUChar( 0x00 ); // Picture
2081 else
2082 (*m_pMemoStream).WriteUChar( 0x01 ); // Memo
2083 for (int i = 4; i > 0; nWriteSize >>= 8)
2084 nHeader[--i] = static_cast<sal_uInt8>(nWriteSize % 256);
2085 }
2086 else
2087 {
2088 (*m_pMemoStream).WriteUChar( 0x00 );
2089 nWriteSize += 8;
2090 for (int i = 0; i < 4; nWriteSize >>= 8)
2091 nHeader[i++] = static_cast<sal_uInt8>(nWriteSize % 256);
2092 }
2093
2094 m_pMemoStream->WriteBytes(nHeader, 4);
2095 if ( bBinary )
2096 m_pMemoStream->WriteBytes(aValue.getConstArray(), aValue.getLength());
2097 else
2098 m_pMemoStream->WriteBytes(aStr.getStr(), aStr.getLength());
2099 m_pMemoStream->Flush();
2100 }
2101 }
2102
2103
2104 // Write the new block number
2105 if (bAppend)
2106 {
2107 sal_uInt64 const nStreamSize = m_pMemoStream->TellEnd();
2108 m_aMemoHeader.db_next = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2109
2110 // Write the new block number
2111 m_pMemoStream->Seek(0);
2112 (*m_pMemoStream).WriteUInt32( m_aMemoHeader.db_next );
2113 m_pMemoStream->Flush();
2114 }
2115}
2116
2117
2118// XAlterTable
2119void SAL_CALL ODbaseTable::alterColumnByName( const OUString& colName, const Reference< XPropertySet >& descriptor )
2120{
2121 ::osl::MutexGuard aGuard(m_aMutex);
2122 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2123
2124
2125 Reference<XDataDescriptorFactory> xOldColumn;
2126 m_xColumns->getByName(colName) >>= xOldColumn;
2127
2128 try
2129 {
2130 alterColumn(m_xColumns->findColumn(colName)-1,descriptor,xOldColumn);
2131 }
2132 catch (const css::lang::IndexOutOfBoundsException&)
2133 {
2134 throw NoSuchElementException(colName, *this);
2135 }
2136}
2137
2138void SAL_CALL ODbaseTable::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor )
2139{
2140 ::osl::MutexGuard aGuard(m_aMutex);
2141 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2142
2143 if(index < 0 || index >= m_xColumns->getCount())
2144 throw IndexOutOfBoundsException(OUString::number(index),*this);
2145
2146 Reference<XDataDescriptorFactory> xOldColumn;
2147 m_xColumns->getByIndex(index) >>= xOldColumn;
2148 alterColumn(index,descriptor,xOldColumn);
2149}
2150
2151void ODbaseTable::alterColumn(sal_Int32 index,
2152 const Reference< XPropertySet >& descriptor ,
2153 const Reference< XDataDescriptorFactory >& xOldColumn )
2154{
2155 if(index < 0 || index >= m_xColumns->getCount())
2156 throw IndexOutOfBoundsException(OUString::number(index),*this);
2157
2158 try
2159 {
2160 OSL_ENSURE(descriptor.is(),"ODbaseTable::alterColumn: descriptor can not be null!");
2161 // creates a copy of the original column and copy all properties from descriptor in xCopyColumn
2162 Reference<XPropertySet> xCopyColumn;
2163 if(xOldColumn.is())
2164 xCopyColumn = xOldColumn->createDataDescriptor();
2165 else
2166 xCopyColumn = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2167
2168 ::comphelper::copyProperties(descriptor,xCopyColumn);
2169
2170 // creates a temp file
2171
2172 OUString sTempName = createTempFile();
2173
2174 rtl::Reference<ODbaseTable> pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2175 Reference<XPropertySet> xHoldTable = pNewTable;
2176 pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),Any(sTempName));
2177 Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2178 OSL_ENSURE(xAppend.is(),"ODbaseTable::alterColumn: No XAppend interface!");
2179
2180 // copy the structure
2181 sal_Int32 i=0;
2182 for(;i < index;++i)
2183 {
2184 Reference<XPropertySet> xProp;
2185 m_xColumns->getByIndex(i) >>= xProp;
2186 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2187 Reference<XPropertySet> xCpy;
2188 if(xColumn.is())
2189 xCpy = xColumn->createDataDescriptor();
2190 else
2191 xCpy = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2192 ::comphelper::copyProperties(xProp,xCpy);
2193 xAppend->appendByDescriptor(xCpy);
2194 }
2195 ++i; // now insert our new column
2196 xAppend->appendByDescriptor(xCopyColumn);
2197
2198 for(;i < m_xColumns->getCount();++i)
2199 {
2200 Reference<XPropertySet> xProp;
2201 m_xColumns->getByIndex(i) >>= xProp;
2202 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2203 Reference<XPropertySet> xCpy;
2204 if(xColumn.is())
2205 xCpy = xColumn->createDataDescriptor();
2206 else
2207 xCpy = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2208 ::comphelper::copyProperties(xProp,xCpy);
2209 xAppend->appendByDescriptor(xCpy);
2210 }
2211
2212 // construct the new table
2213 if(!pNewTable->CreateImpl())
2214 {
2215 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2216 STR_COLUMN_NOT_ALTERABLE,
2217 "$columnname$", ::comphelper::getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2218 ) );
2219 ::dbtools::throwGenericSQLException( sError, *this );
2220 }
2221
2222 pNewTable->construct();
2223
2224 // copy the data
2225 copyData(pNewTable.get(),0);
2226
2227 // now drop the old one
2228 if( DropImpl() ) // we don't want to delete the memo columns too
2229 {
2230 try
2231 {
2232 // rename the new one to the old one
2233 pNewTable->renameImpl(m_Name);
2234 }
2235 catch(const css::container::ElementExistException&)
2236 {
2237 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2238 STR_COULD_NOT_DELETE_FILE,
2239 "$filename$", m_Name
2240 ) );
2241 ::dbtools::throwGenericSQLException( sError, *this );
2242 }
2243 // release the temp file
2244 pNewTable = nullptr;
2245 ::comphelper::disposeComponent(xHoldTable);
2246 }
2247 else
2248 {
2249 pNewTable = nullptr;
2250 }
2251 FileClose();
2252 construct();
2253 if(m_xColumns)
2254 m_xColumns->refresh();
2255
2256 }
2257 catch(const SQLException&)
2258 {
2259 throw;
2260 }
2261 catch(const Exception&)
2262 {
2263 TOOLS_WARN_EXCEPTION( "connectivity.drivers","");
2264 throw;
2265 }
2266}
2267
2268Reference< XDatabaseMetaData> ODbaseTable::getMetaData() const
2269{
2270 return getConnection()->getMetaData();
2271}
2272
2273void SAL_CALL ODbaseTable::rename( const OUString& newName )
2274{
2275 ::osl::MutexGuard aGuard(m_aMutex);
2276 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2277 if(m_pTables && m_pTables->hasByName(newName))
2278 throw ElementExistException(newName,*this);
2279
2280
2281 renameImpl(newName);
2282
2283 ODbaseTable_BASE::rename(newName);
2284
2285 construct();
2286 if(m_xColumns)
2287 m_xColumns->refresh();
2288}
2289namespace
2290{
2291 void renameFile(file::OConnection const * _pConnection,std::u16string_view oldName,
2292 const OUString& newName, std::u16string_view _sExtension)
2293 {
2294 OUString aName = ODbaseTable::getEntry(_pConnection,oldName);
2295 if(aName.isEmpty())
2296 {
2297 OUString aIdent = _pConnection->getContent()->getIdentifier()->getContentIdentifier();
2298 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2299 aIdent += "/";
2300 aIdent += oldName;
2301 aName = aIdent;
2302 }
2303 INetURLObject aURL;
2304 aURL.SetURL(aName);
2305
2306 aURL.setExtension( _sExtension );
2307 OUString sNewName(newName + "." + _sExtension);
2308
2309 try
2310 {
2311 Content aContent(aURL.GetMainURL(INetURLObject::DecodeMechanism::NONE),Reference<XCommandEnvironment>(), comphelper::getProcessComponentContext());
2312
2313 Sequence< PropertyValue > aProps{ { "Title",
2314 -1, // n/a
2315 Any(sNewName),
2316 css::beans::PropertyState_DIRECT_VALUE } };
2317 Sequence< Any > aValues;
2318 aContent.executeCommand( "setPropertyValues",Any(aProps) ) >>= aValues;
2319 if(aValues.hasElements() && aValues[0].hasValue())
2320 throw Exception("setPropertyValues returned non-zero", nullptr);
2321 }
2322 catch(const Exception&)
2323 {
2324 throw ElementExistException(newName);
2325 }
2326 }
2327}
2328
2329void ODbaseTable::renameImpl( const OUString& newName )
2330{
2331 ::osl::MutexGuard aGuard(m_aMutex);
2332
2333 FileClose();
2334
2335
2336 renameFile(m_pConnection,m_Name,newName,m_pConnection->getExtension());
2337 if ( HasMemoFields() )
2338 { // delete the memo fields
2339 renameFile(m_pConnection,m_Name,newName,u"dbt");
2340 }
2341}
2342
2343void ODbaseTable::addColumn(const Reference< XPropertySet >& _xNewColumn)
2344{
2345 OUString sTempName = createTempFile();
2346
2347 rtl::Reference xNewTable(new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection)));
2348 xNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),Any(sTempName));
2349 {
2350 Reference<XAppend> xAppend(xNewTable->getColumns(),UNO_QUERY);
2351 bool bCase = getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers();
2352 // copy the structure
2353 for(sal_Int32 i=0;i < m_xColumns->getCount();++i)
2354 {
2355 Reference<XPropertySet> xProp;
2356 m_xColumns->getByIndex(i) >>= xProp;
2357 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2358 Reference<XPropertySet> xCpy;
2359 if(xColumn.is())
2360 xCpy = xColumn->createDataDescriptor();
2361 else
2362 {
2363 xCpy = new OColumn(bCase);
2364 ::comphelper::copyProperties(xProp,xCpy);
2365 }
2366
2367 xAppend->appendByDescriptor(xCpy);
2368 }
2369 Reference<XPropertySet> xCpy = new OColumn(bCase);
2370 ::comphelper::copyProperties(_xNewColumn,xCpy);
2371 xAppend->appendByDescriptor(xCpy);
2372 }
2373
2374 // construct the new table
2375 if(!xNewTable->CreateImpl())
2376 {
2377 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2378 STR_COLUMN_NOT_ADDABLE,
2379 "$columnname$", ::comphelper::getString(_xNewColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2380 ) );
2381 ::dbtools::throwGenericSQLException( sError, *this );
2382 }
2383
2384 xNewTable->construct();
2385 // copy the data
2386 copyData(xNewTable.get(),xNewTable->m_xColumns->getCount());
2387 // drop the old table
2388 if(DropImpl())
2389 {
2390 xNewTable->renameImpl(m_Name);
2391 // release the temp file
2392 }
2393 xNewTable.clear();
2394
2395 FileClose();
2396 construct();
2397 if(m_xColumns)
2398 m_xColumns->refresh();
2399}
2400
2401void ODbaseTable::dropColumn(sal_Int32 _nPos)
2402{
2403 OUString sTempName = createTempFile();
2404
2405 rtl::Reference xNewTable(new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection)));
2406 xNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),Any(sTempName));
2407 {
2408 Reference<XAppend> xAppend(xNewTable->getColumns(),UNO_QUERY);
2409 bool bCase = getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers();
2410 // copy the structure
2411 for(sal_Int32 i=0;i < m_xColumns->getCount();++i)
2412 {
2413 if(_nPos != i)
2414 {
2415 Reference<XPropertySet> xProp;
2416 m_xColumns->getByIndex(i) >>= xProp;
2417 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2418 Reference<XPropertySet> xCpy;
2419 if(xColumn.is())
2420 xCpy = xColumn->createDataDescriptor();
2421 else
2422 {
2423 xCpy = new OColumn(bCase);
2424 ::comphelper::copyProperties(xProp,xCpy);
2425 }
2426 xAppend->appendByDescriptor(xCpy);
2427 }
2428 }
2429 }
2430
2431 // construct the new table
2432 if(!xNewTable->CreateImpl())
2433 {
2434 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2435 STR_COLUMN_NOT_DROP,
2436 "$position$", OUString::number(_nPos)
2437 ) );
2438 ::dbtools::throwGenericSQLException( sError, *this );
2439 }
2440 xNewTable->construct();
2441 // copy the data
2442 copyData(xNewTable.get(),_nPos);
2443 // drop the old table
2444 if(DropImpl())
2445 xNewTable->renameImpl(m_Name);
2446 // release the temp file
2447
2448 xNewTable.clear();
2449
2450 FileClose();
2451 construct();
2452}
2453
2454OUString ODbaseTable::createTempFile()
2455{
2456 OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
2457 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2458 aIdent += "/";
2459
2460 OUString sExt("." + m_pConnection->getExtension());
2461 OUString aTempFileURL = utl::CreateTempURL(m_Name, true, sExt, &aIdent);
2462 if(aTempFileURL.isEmpty())
2463 getConnection()->throwGenericSQLException(STR_COULD_NOT_ALTER_TABLE, *this);
2464
2465 INetURLObject aURL;
2466 aURL.SetSmartProtocol(INetProtocol::File);
2467 aURL.SetURL(aTempFileURL);
2468
2469 OUString sNewName(aURL.getName().copy(0, aURL.getName().getLength() - sExt.getLength()));
2470
2471 return sNewName;
2472}
2473
2474void ODbaseTable::copyData(ODbaseTable* _pNewTable,sal_Int32 _nPos)
2475{
2476 sal_Int32 nPos = _nPos + 1; // +1 because we always have the bookmark column as well
2477 OValueRefRow aRow = new OValueRefVector(m_xColumns->getCount());
2478 OValueRefRow aInsertRow;
2479 if(_nPos)
2480 {
2481 aInsertRow = new OValueRefVector(_pNewTable->m_xColumns->getCount());
2482 std::for_each(aInsertRow->begin(),aInsertRow->end(),TSetRefBound(true));
2483 }
2484 else
2485 aInsertRow = aRow;
2486
2487 // we only have to bind the values which we need to copy into the new table
2488 std::for_each(aRow->begin(),aRow->end(),TSetRefBound(true));
2489 if(_nPos && (_nPos < static_cast<sal_Int32>(aRow->size())))
2490 (*aRow)[nPos]->setBound(false);
2491
2492
2493 sal_Int32 nCurPos;
2494 OValueRefVector::const_iterator aIter;
2495 for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.nbRecords;++nRowPos)
2496 {
2497 bool bOk = seekRow( IResultSetHelper::BOOKMARK, nRowPos+1, nCurPos );
2498 if ( bOk )
2499 {
2500 bOk = fetchRow( aRow, *m_aColumns, true);
2501 if ( bOk && !aRow->isDeleted() ) // copy only not deleted rows
2502 {
2503 // special handling when pos == 0 then we don't have to distinguish between the two rows
2504 if(_nPos)
2505 {
2506 aIter = aRow->begin()+1;
2507 sal_Int32 nCount = 1;
2508 for(OValueRefVector::iterator aInsertIter = aInsertRow->begin()+1; aIter != aRow->end() && aInsertIter != aInsertRow->end();++aIter,++nCount)
2509 {
2510 if(nPos != nCount)
2511 {
2512 (*aInsertIter)->setValue( (*aIter)->getValue() );
2513 ++aInsertIter;
2514 }
2515 }
2516 }
2517 bOk = _pNewTable->InsertRow(*aInsertRow, _pNewTable->m_xColumns.get());
2518 SAL_WARN_IF(!bOk, "connectivity.drivers", "Row could not be inserted!");
2519 }
2520 else
2521 {
2522 SAL_WARN_IF(!bOk, "connectivity.drivers", "Row could not be fetched!");
2523 }
2524 }
2525 else
2526 {
2527 OSL_ASSERT(false);
2528 }
2529 } // for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.db_anz;++nRowPos)
2530}
2531
2532void ODbaseTable::throwInvalidDbaseFormat()
2533{
2534 FileClose();
2535 // no dbase file
2536
2537 const OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2538 STR_INVALID_DBASE_FILE,
2539 "$filename$", getEntry(m_pConnection,m_Name)
2540 ) );
2541 ::dbtools::throwGenericSQLException( sError, *this );
2542}
2543
2544void ODbaseTable::refreshHeader()
2545{
2546 if ( m_aHeader.nbRecords == 0 )
2547 readHeader();
2548}
2549
2550bool ODbaseTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
2551{
2552 // prepare positioning:
2553 OSL_ENSURE(m_pFileStream,"ODbaseTable::seekRow: FileStream is NULL!");
2554
2555 sal_uInt32 nNumberOfRecords = m_aHeader.nbRecords;
2556 sal_uInt32 nTempPos = m_nFilePos;
2557 m_nFilePos = nCurPos;
2558
2559 switch(eCursorPosition)
2560 {
2561 case IResultSetHelper::NEXT:
2562 ++m_nFilePos;
2563 break;
2564 case IResultSetHelper::PRIOR:
2565 if (m_nFilePos > 0)
2566 --m_nFilePos;
2567 break;
2568 case IResultSetHelper::FIRST:
2569 m_nFilePos = 1;
2570 break;
2571 case IResultSetHelper::LAST:
2572 m_nFilePos = nNumberOfRecords;
2573 break;
2574 case IResultSetHelper::RELATIVE1:
2575 m_nFilePos = (m_nFilePos + nOffset < 0) ? 0
2576 : static_cast<sal_uInt32>(m_nFilePos + nOffset);
2577 break;
2578 case IResultSetHelper::ABSOLUTE1:
2579 case IResultSetHelper::BOOKMARK:
2580 m_nFilePos = static_cast<sal_uInt32>(nOffset);
2581 break;
2582 }
2583
2584 if (m_nFilePos > static_cast<sal_Int32>(nNumberOfRecords))
2585 m_nFilePos = static_cast<sal_Int32>(nNumberOfRecords) + 1;
2586
2587 if (m_nFilePos == 0 || m_nFilePos == static_cast<sal_Int32>(nNumberOfRecords) + 1)
2588 goto Error;
2589 else
2590 {
2591 std::size_t nEntryLen = m_aHeader.recordLength;
2592
2593 OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: invalid record position");
2594 std::size_t nPos = m_aHeader.headerLength + static_cast<std::size_t>(m_nFilePos-1) * nEntryLen;
2595
2596 m_pFileStream->Seek(nPos);
2597 if (m_pFileStream->GetError() != ERRCODE_NONE)
2598 goto Error;
2599
2600 std::size_t nRead = m_pFileStream->ReadBytes(m_pBuffer.get(), nEntryLen);
2601 if (nRead != nEntryLen)
2602 {
2603 SAL_WARN("connectivity.drivers", "ODbaseTable::seekRow: short read!");
2604 goto Error;
2605 }
2606 if (m_pFileStream->GetError() != ERRCODE_NONE)
2607 goto Error;
2608 }
2609 goto End;
2610
2611Error:
2612 switch(eCursorPosition)
2613 {
2614 case IResultSetHelper::PRIOR:
2615 case IResultSetHelper::FIRST:
2616 m_nFilePos = 0;
2617 break;
2618 case IResultSetHelper::LAST:
2619 case IResultSetHelper::NEXT:
2620 case IResultSetHelper::ABSOLUTE1:
2621 case IResultSetHelper::RELATIVE1:
2622 if (nOffset > 0)
2623 m_nFilePos = nNumberOfRecords + 1;
2624 else if (nOffset < 0)
2625 m_nFilePos = 0;
2626 break;
2627 case IResultSetHelper::BOOKMARK:
2628 m_nFilePos = nTempPos; // last position
2629 }
2630 return false;
2631
2632End:
2633 nCurPos = m_nFilePos;
2634 return true;
2635}
2636
2637bool ODbaseTable::ReadMemo(std::size_t nBlockNo, ORowSetValue& aVariable)
2638{
2639 m_pMemoStream->Seek(nBlockNo * m_aMemoHeader.db_size);
2640 switch (m_aMemoHeader.db_typ)
2641 {
2642 case MemodBaseIII: // dBase III-Memofield, ends with Ctrl-Z
2643 {
2644 const char cEOF = char(DBF_EOL);
2645 OStringBuffer aBStr;
2646 static char aBuf[514];
2647 aBuf[512] = 0; // avoid random value
2648 bool bReady = false;
2649
2650 do
2651 {
2652 m_pMemoStream->ReadBytes(&aBuf, 512);
2653
2654 sal_uInt16 i = 0;
2655 while (aBuf[i] != cEOF && ++i < 512)
2656 ;
2657 bReady = aBuf[i] == cEOF;
2658
2659 aBuf[i] = 0;
2660 aBStr.append(aBuf);
2661
2662 } while (!bReady && !m_pMemoStream->eof());
2663
2664 aVariable = OStringToOUString(aBStr,
2665 m_eEncoding);
2666
2667 } break;
2668 case MemoFoxPro:
2669 case MemodBaseIV: // dBase IV-Memofield with length
2670 {
2671 bool bIsText = true;
2672 char sHeader[4];
2673 m_pMemoStream->ReadBytes(sHeader, 4);
2674 // Foxpro stores text and binary data
2675 if (m_aMemoHeader.db_typ == MemoFoxPro)
2676 {
2677 bIsText = sHeader[3] != 0;
2678 }
2679 else if (static_cast<sal_uInt8>(sHeader[0]) != 0xFF || static_cast<sal_uInt8>(sHeader[1]) != 0xFF || static_cast<sal_uInt8>(sHeader[2]) != 0x08)
2680 {
2681 return false;
2682 }
2683
2684 sal_uInt32 nLength(0);
2685 (*m_pMemoStream).ReadUInt32( nLength );
2686
2687 if (m_aMemoHeader.db_typ == MemodBaseIV)
2688 nLength -= 8;
2689
2690 if ( nLength )
2691 {
2692 if ( bIsText )
2693 {
2694 OStringBuffer aBuffer(read_uInt8s_ToOString(*m_pMemoStream, nLength));
2695 //pad it out with ' ' to expected length on short read
2696 sal_Int32 nRequested = sal::static_int_cast<sal_Int32>(nLength);
2697 comphelper::string::padToLength(aBuffer, nRequested, ' ');
2698 aVariable = OStringToOUString(aBuffer, m_eEncoding);
2699 } // if ( bIsText )
2700 else
2701 {
2702 css::uno::Sequence< sal_Int8 > aData(nLength);
2703 m_pMemoStream->ReadBytes(aData.getArray(), nLength);
2704 aVariable = aData;
2705 }
2706 } // if ( nLength )
2707 }
2708 }
2709 return true;
2710}
2711
2712bool ODbaseTable::AllocBuffer()
2713{
2714 sal_uInt16 nSize = m_aHeader.recordLength;
2715 SAL_WARN_IF(nSize == 0, "connectivity.drivers", "Size too small");
2716
2717 if (m_nBufferSize != nSize)
2718 {
2719 m_pBuffer.reset();
2720 }
2721
2722 // if there is no buffer available: allocate:
2723 if (!m_pBuffer && nSize > 0)
2724 {
2725 m_nBufferSize = nSize;
2726 m_pBuffer.reset(new sal_uInt8[m_nBufferSize+1]);
2727 }
2728
2729 return m_pBuffer != nullptr;
2730}
2731
2732bool ODbaseTable::WriteBuffer()
2733{
2734 OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: invalid record position");
2735
2736 // position on desired record:
2737 std::size_t nPos = m_aHeader.headerLength + static_cast<tools::Long>(m_nFilePos-1) * m_aHeader.recordLength;
2738 m_pFileStream->Seek(nPos);
2739 return m_pFileStream->WriteBytes(m_pBuffer.get(), m_aHeader.recordLength) > 0;
2740}
2741
2742sal_Int32 ODbaseTable::getCurrentLastPos() const
2743{
2744 return m_aHeader.nbRecords;
2745}
2746
2747/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
struct _ADOColumn Column
Definition: Awrapadox.hxx:40
struct _ADOIndex Index
Definition: Awrapadox.hxx:45
constexpr OStringLiteral dBASE_III_GROUP
Definition: DIndex.hxx:26
#define FIELD_DESCRIPTOR_TERMINATOR
Definition: DTable.cxx:84
#define DBF_EOL
Definition: DTable.cxx:85
css::uno::Sequence< sal_Int8 > Buffer
OString GetKeyName(sal_uInt16 nKey) const
void SetGroup(const OString &rGroup)
sal_uInt16 GetKeyCount() const
OString ReadKey(const OString &rKey) const
static SVL_DLLPUBLIC sal_Int32 ConvertPrecisionToOdbc(sal_Int32 _nLen, sal_Int32 _nScale)
static SVL_DLLPUBLIC sal_Int32 ConvertPrecisionToDbase(sal_Int32 _nLen, sal_Int32 _nScale)
sal_uInt64 Tell() const
SvStream & ReadChar(char &rChar)
sal_uInt64 Seek(sal_uInt64 nPos)
sal_uInt64 SeekRel(sal_Int64 nPos)
rtl_TextEncoding getTextEncoding() const
Definition: TConnection.hxx:61
const OUString & getURL() const
Definition: TConnection.hxx:62
rtl_TextEncoding m_eEncoding
Definition: DTable.hxx:107
virtual bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32 &nCurPos) override
Definition: DTable.cxx:2550
virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type &rType) override
Definition: DTable.cxx:757
virtual void refreshColumns() override
Definition: DTable.cxx:669
std::vector< sal_Int32 > m_aScales
Definition: DTable.hxx:102
virtual void SAL_CALL disposing() override
Definition: DTable.cxx:729
ODbaseTable(sdbcx::OCollection *_pTables, ODbaseConnection *_pConnection)
Definition: DTable.cxx:450
std::vector< sal_Int32 > m_aRealFieldLengths
Definition: DTable.hxx:103
css::uno::Reference< css::beans::XPropertySet > isUniqueByColumnName(sal_Int32 _nColumnPos)
Definition: DTable.cxx:1607
std::vector< sal_Int32 > m_aPrecisions
Definition: DTable.hxx:101
std::vector< sal_Int32 > m_aTypes
Definition: DTable.hxx:100
virtual bool DeleteRow(const OSQLColumns &_rCols) override
Definition: DTable.cxx:1560
static OUString getEntry(file::OConnection const *_pConnection, std::u16string_view _sURL)
Definition: DTable.cxx:627
std::unique_ptr< SvStream > m_pMemoStream
Definition: DTable.hxx:106
void alterColumn(sal_Int32 index, const css::uno::Reference< css::beans::XPropertySet > &descriptor, const css::uno::Reference< css::sdbcx::XDataDescriptorFactory > &xOldColumn)
Definition: DTable.cxx:2151
bool UpdateBuffer(OValueRefVector &rRow, const OValueRefRow &pOrgRow, const css::uno::Reference< css::container::XIndexAccess > &_xCols, bool bForceAllFields)
Definition: DTable.cxx:1641
virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override
Definition: DTable.cxx:736
virtual void refreshIndexes() override
Definition: DTable.cxx:685
virtual bool fetchRow(OValueRefRow &_rRow, const OSQLColumns &_rCols, bool bRetrieveData) override
Definition: DTable.cxx:768
bool matchesExtension(const OUString &_rExt) const
Definition: FConnection.cxx:75
virtual css::uno::Reference< css::sdbc::XDatabaseMetaData > SAL_CALL getMetaData() override
css::uno::Reference< css::ucb::XDynamicResultSet > getDir() const
OConnection * m_pConnection
Definition: FTable.hxx:36
const OUString & getSchema() const
Definition: FTable.hxx:83
OUString SAL_CALL getName() override
Definition: FTable.hxx:81
static std::unique_ptr< SvStream > createStream_simpleError(const OUString &_rFileName, StreamMode _eOpenMode)
Definition: FTable.cxx:155
::rtl::Reference< OSQLColumns > m_aColumns
Definition: FTable.hxx:38
std::unique_ptr< sal_uInt8[]> m_pBuffer
Definition: FTable.hxx:40
std::unique_ptr< SvStream > m_pFileStream
Definition: FTable.hxx:37
OConnection * getConnection() const
Definition: FTable.hxx:66
std::unique_ptr< OCollection > m_xIndexes
Definition: VTable.hxx:78
std::unique_ptr< OCollection > m_xColumns
Definition: VTable.hxx:77
virtual css::uno::Sequence< css::uno::Type > SAL_CALL getTypes() override
Definition: VTable.cxx:124
virtual css::uno::Any SAL_CALL queryInterface(const css::uno::Type &rType) override
Definition: VTable.cxx:109
mutable::osl::Mutex m_aMutex
int nCount
URL aURL
float u
#define ERRCODE_NONE
DocumentType eType
OUString sName
#define SAL_WARN(area, stream)
#define SAL_INFO(area, stream)
if(aStr !=aBuf) UpdateName_Impl(m_xFollowLb.get()
@ Exception
Reference< XComponentContext > getProcessComponentContext()
Type
bool dbfDecodeCharset(rtl_TextEncoding &_out_encoding, sal_uInt8 nType, sal_uInt8 nCodepage)
decode a DBase file's codepage byte to a RTL charset
Definition: dbtools.cxx:1989
ORefVector< css::uno::Reference< css::beans::XPropertySet > > OSQLColumns
Definition: CommonTools.hxx:95
int i
constexpr double monthDaysWithoutJanFeb
constexpr std::enable_if_t< std::is_signed_v< T >, std::make_unsigned_t< T > > make_unsigned(T value)
sal_Int32 type
Definition: pq_statics.cxx:60
QPRO_FUNC_TYPE nType
#define STREAM_SEEK_TO_END
#define STREAM_SEEK_TO_BEGIN
TOOLS_DLLPUBLIC bool checkSeek(SvStream &rSt, sal_uInt64 nOffset)
OUString Name
unsigned char sal_uInt8
const SvXMLTokenMapEntry aTypes[]