Update ooo320-m1
[ooovba.git] / connectivity / source / drivers / dbase / DTable.cxx
blob216dc2d9fc20a5f5b502096696712b4c1f3d8033
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: DTable.cxx,v $
10 * $Revision: 1.107.30.2 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 // MARKER(update_precomp.py): autogen include statement, do not remove
32 #include "precompiled_connectivity.hxx"
33 #include "dbase/DTable.hxx"
34 #include <com/sun/star/sdbc/ColumnValue.hpp>
35 #include <com/sun/star/sdbc/DataType.hpp>
36 #include <com/sun/star/ucb/XContentAccess.hpp>
37 #include <com/sun/star/sdbc/XRow.hpp>
38 #include <svtools/converter.hxx>
39 #include "dbase/DConnection.hxx"
40 #include "dbase/DColumns.hxx"
41 #include <osl/thread.h>
42 #include <tools/config.hxx>
43 #include "dbase/DIndex.hxx"
44 #include "dbase/DIndexes.hxx"
45 //#include "file/FDriver.hxx"
46 #include <comphelper/sequence.hxx>
47 #include <svtools/zforlist.hxx>
48 #include <svtools/syslocale.hxx>
49 #include <rtl/math.hxx>
50 #include <stdio.h> //sprintf
51 #include <ucbhelper/content.hxx>
52 #include <comphelper/extract.hxx>
53 #include <connectivity/dbexception.hxx>
54 #include <connectivity/dbconversion.hxx>
55 #include <com/sun/star/lang/DisposedException.hpp>
56 #include <comphelper/property.hxx>
57 //#include <unotools/calendarwrapper.hxx>
58 #include <unotools/tempfile.hxx>
59 #include <unotools/ucbhelper.hxx>
60 #include <comphelper/types.hxx>
61 #include <cppuhelper/exc_hlp.hxx>
62 #include "connectivity/PColumn.hxx"
63 #include "connectivity/dbtools.hxx"
64 #include "connectivity/FValue.hxx"
65 #include "connectivity/dbconversion.hxx"
66 #include "resource/dbase_res.hrc"
67 #include <rtl/logfile.hxx>
69 #include <algorithm>
71 using namespace ::comphelper;
72 using namespace connectivity;
73 using namespace connectivity::sdbcx;
74 using namespace connectivity::dbase;
75 using namespace connectivity::file;
76 using namespace ::ucbhelper;
77 using namespace ::utl;
78 using namespace ::cppu;
79 using namespace ::dbtools;
80 using namespace ::com::sun::star::uno;
81 using namespace ::com::sun::star::ucb;
82 using namespace ::com::sun::star::beans;
83 using namespace ::com::sun::star::sdbcx;
84 using namespace ::com::sun::star::sdbc;
85 using namespace ::com::sun::star::container;
86 using namespace ::com::sun::star::lang;
87 using namespace ::com::sun::star::i18n;
89 // stored as the Field Descriptor terminator
90 #define FIELD_DESCRIPTOR_TERMINATOR 0x0D
91 #define DBF_EOL 0x1A
93 namespace
95 sal_Int32 lcl_getFileSize(SvStream& _rStream)
97 sal_Int32 nFileSize = 0;
98 _rStream.Seek(STREAM_SEEK_TO_END);
99 _rStream.SeekRel(-1);
100 char cEOL;
101 _rStream >> cEOL;
102 nFileSize = _rStream.Tell();
103 if ( cEOL == DBF_EOL )
104 nFileSize -= 1;
105 return nFileSize;
108 calculates the Julian date
110 void lcl_CalcJulDate(sal_Int32& _nJulianDate,sal_Int32& _nJulianTime,const com::sun::star::util::DateTime _aDateTime)
112 com::sun::star::util::DateTime aDateTime = _aDateTime;
113 // weird: months fix
114 if (aDateTime.Month > 12)
116 aDateTime.Month--;
117 sal_uInt16 delta = _aDateTime.Month / 12;
118 aDateTime.Year += delta;
119 aDateTime.Month -= delta * 12;
120 aDateTime.Month++;
123 _nJulianTime = ((aDateTime.Hours*3600000)+(aDateTime.Minutes*60000)+(aDateTime.Seconds*1000)+(aDateTime.HundredthSeconds*10));
124 /* conversion factors */
125 sal_uInt16 iy0;
126 sal_uInt16 im0;
127 if ( aDateTime.Month <= 2 )
129 iy0 = aDateTime.Year - 1;
130 im0 = aDateTime.Month + 12;
132 else
134 iy0 = aDateTime.Year;
135 im0 = aDateTime.Month;
137 sal_Int32 ia = iy0 / 100;
138 sal_Int32 ib = 2 - ia + (ia >> 2);
139 /* calculate julian date */
140 if ( aDateTime.Year <= 0 )
142 _nJulianDate = (sal_Int32) ((365.25 * iy0) - 0.75)
143 + (sal_Int32) (30.6001 * (im0 + 1) )
144 + aDateTime.Day + 1720994;
145 } // if ( _aDateTime.Year <= 0 )
146 else
148 _nJulianDate = static_cast<sal_Int32>( ((365.25 * iy0)
149 + (sal_Int32) (30.6001 * (im0 + 1))
150 + aDateTime.Day + 1720994));
152 double JD = _nJulianDate + 0.5;
153 _nJulianDate = (sal_Int32)( JD + 0.5);
154 const double gyr = aDateTime.Year + (0.01 * aDateTime.Month) + (0.0001 * aDateTime.Day);
155 if ( gyr >= 1582.1015 ) /* on or after 15 October 1582 */
156 _nJulianDate += ib;
160 calculates date time from the Julian Date
162 void lcl_CalDate(sal_Int32 _nJulianDate,sal_Int32 _nJulianTime,com::sun::star::util::DateTime& _rDateTime)
164 if ( _nJulianDate )
166 sal_Int32 ialp;
167 sal_Int32 ka = _nJulianDate;
168 if ( _nJulianDate >= 2299161 )
170 ialp = (sal_Int32)( ((double) _nJulianDate - 1867216.25 ) / ( 36524.25 ));
171 ka = _nJulianDate + 1 + ialp - ( ialp >> 2 );
173 sal_Int32 kb = ka + 1524;
174 sal_Int32 kc = (sal_Int32) ( ((double) kb - 122.1 ) / 365.25 );
175 sal_Int32 kd = (sal_Int32) ((double) kc * 365.25);
176 sal_Int32 ke = (sal_Int32) ((double) ( kb - kd ) / 30.6001 );
177 _rDateTime.Day = static_cast<sal_uInt16>(kb - kd - ((sal_Int32) ( (double) ke * 30.6001 )));
178 if ( ke > 13 )
179 _rDateTime.Month = static_cast<sal_uInt16>(ke - 13);
180 else
181 _rDateTime.Month = static_cast<sal_uInt16>(ke - 1);
182 if ( (_rDateTime.Month == 2) && (_rDateTime.Day > 28) )
183 _rDateTime.Day = 29;
184 if ( (_rDateTime.Month == 2) && (_rDateTime.Day == 29) && (ke == 3) )
185 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4716);
186 else if ( _rDateTime.Month > 2 )
187 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4716);
188 else
189 _rDateTime.Year = static_cast<sal_uInt16>(kc - 4715);
190 } // if ( _nJulianDate )
192 if ( _nJulianTime )
194 double d_s = _nJulianTime / 1000;
195 double d_m = d_s / 60;
196 double d_h = d_m / 60;
197 _rDateTime.Hours = (sal_uInt16) (d_h);
198 _rDateTime.Minutes = (sal_uInt16) d_m; // integer _aDateTime.Minutes
199 //// weird: time fix
200 // int test = (_rDateTime.Hours % 3) * 100 + _rDateTime.Minutes;
201 //int test_tbl[] = {0, 1, 2, 11, 12, 13, 22, 23, 24, 25, 34, 35, 36,
202 // 45, 46, 47, 56, 57, 58, 107, 108, 109, 110, 119, 120, 121,
203 // 130, 131, 132, 141, 142, 143, 152, 153, 154, 155, 204, 205,
204 // 206, 215, 216, 217, 226, 227, 228, 237, 238, 239, 240, 249,
205 // 250, 251};
206 // for (int i = 0; i < sizeof(test_tbl)/sizeof(test_tbl[0]); i++)
208 // if (test == test_tbl[i])
209 // {
210 // // frac += 0.000012;
211 // //d_hour = frac * 24.0;
212 // _rDateTime.Hours = (sal_uInt16)d_hour;
213 // d_minute = (d_hour - (double)_rDateTime.Hours) * 60.0;
214 // _rDateTime.Minutes = (sal_uInt16)d_minute;
215 // break;
216 // }
217 // }
219 _rDateTime.Seconds = static_cast<sal_uInt16>(( d_m - (double) _rDateTime.Minutes ) * 60.0);
225 // -------------------------------------------------------------------------
226 void ODbaseTable::readHeader()
228 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::readHeader" );
229 OSL_ENSURE(m_pFileStream,"No Stream available!");
230 if(!m_pFileStream)
231 return;
232 m_pFileStream->RefreshBuffer(); // sicherstellen, dass die Kopfinformationen tatsaechlich neu gelesen werden
233 m_pFileStream->Seek(STREAM_SEEK_TO_BEGIN);
235 BYTE nType=0;
236 (*m_pFileStream) >> nType;
237 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
238 throwInvalidDbaseFormat();
240 m_pFileStream->Read((char*)(&m_aHeader.db_aedat), 3*sizeof(BYTE));
241 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
242 throwInvalidDbaseFormat();
243 (*m_pFileStream) >> m_aHeader.db_anz;
244 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
245 throwInvalidDbaseFormat();
246 (*m_pFileStream) >> m_aHeader.db_kopf;
247 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
248 throwInvalidDbaseFormat();
249 (*m_pFileStream) >> m_aHeader.db_slng;
250 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
251 throwInvalidDbaseFormat();
252 m_pFileStream->Read((char*)(&m_aHeader.db_frei), 20*sizeof(BYTE));
253 if(ERRCODE_NONE != m_pFileStream->GetErrorCode())
254 throwInvalidDbaseFormat();
256 if ( ( ( m_aHeader.db_kopf - 1 ) / 32 - 1 ) <= 0 ) // anzahl felder
258 // no dbase file
259 throwInvalidDbaseFormat();
261 else
263 // Konsistenzpruefung des Header:
264 m_aHeader.db_typ = (DBFType)nType;
265 switch (m_aHeader.db_typ)
267 case dBaseIII:
268 case dBaseIV:
269 case dBaseV:
270 case VisualFoxPro:
271 case VisualFoxProAuto:
272 case dBaseFS:
273 case dBaseFSMemo:
274 case dBaseIVMemoSQL:
275 case dBaseIIIMemo:
276 case FoxProMemo:
277 m_pFileStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
278 if ( m_aHeader.db_frei[17] != 0x00
279 && !m_aHeader.db_frei[18] && !m_aHeader.db_frei[19] && getConnection()->isTextEncodingDefaulted() )
281 switch(m_aHeader.db_frei[17])
283 case 0x01: m_eEncoding = RTL_TEXTENCODING_IBM_437; break; // DOS USA code page 437
284 case 0x02: m_eEncoding = RTL_TEXTENCODING_IBM_850; break; // DOS Multilingual code page 850
285 case 0x03: m_eEncoding = RTL_TEXTENCODING_MS_1252; break; // Windows ANSI code page 1252
286 case 0x04: m_eEncoding = RTL_TEXTENCODING_APPLE_ROMAN; break; // Standard Macintosh
287 case 0x64: m_eEncoding = RTL_TEXTENCODING_IBM_852; break; // EE MS-DOS code page 852
288 case 0x65: m_eEncoding = RTL_TEXTENCODING_IBM_865; break; // Nordic MS-DOS code page 865
289 case 0x66: m_eEncoding = RTL_TEXTENCODING_IBM_866; break; // Russian MS-DOS code page 866
290 case 0x67: m_eEncoding = RTL_TEXTENCODING_IBM_861; break; // Icelandic MS-DOS
291 //case 0x68: m_eEncoding = ; break; // Kamenicky (Czech) MS-DOS
292 //case 0x69: m_eEncoding = ; break; // Mazovia (Polish) MS-DOS
293 case 0x6A: m_eEncoding = RTL_TEXTENCODING_IBM_737; break; // Greek MS-DOS (437G)
294 case 0x6B: m_eEncoding = RTL_TEXTENCODING_IBM_857; break; // Turkish MS-DOS
295 case 0x96: m_eEncoding = RTL_TEXTENCODING_APPLE_CYRILLIC; break; // Russian Macintosh
296 case 0x97: m_eEncoding = RTL_TEXTENCODING_APPLE_CENTEURO; break; // Eastern European Macintosh
297 case 0x98: m_eEncoding = RTL_TEXTENCODING_APPLE_GREEK; break; // Greek Macintosh
298 case 0xC8: m_eEncoding = RTL_TEXTENCODING_MS_1250; break; // Windows EE code page 1250
299 case 0xC9: m_eEncoding = RTL_TEXTENCODING_MS_1251; break; // Russian Windows
300 case 0xCA: m_eEncoding = RTL_TEXTENCODING_MS_1254; break; // Turkish Windows
301 case 0xCB: m_eEncoding = RTL_TEXTENCODING_MS_1253; break; // Greek Windows
302 default:
303 break;
306 break;
307 case dBaseIVMemo:
308 m_pFileStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
309 break;
310 default:
312 throwInvalidDbaseFormat();
317 // -------------------------------------------------------------------------
318 void ODbaseTable::fillColumns()
320 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::fillColumns" );
321 m_pFileStream->Seek(STREAM_SEEK_TO_BEGIN);
322 m_pFileStream->Seek(32L);
324 if(!m_aColumns.isValid())
325 m_aColumns = new OSQLColumns();
326 else
327 m_aColumns->get().clear();
329 m_aTypes.clear();
330 m_aPrecisions.clear();
331 m_aScales.clear();
333 // Anzahl Felder:
334 const sal_Int32 nFieldCount = (m_aHeader.db_kopf - 1) / 32 - 1;
335 OSL_ENSURE(nFieldCount,"No columns in table!");
337 m_aColumns->get().reserve(nFieldCount);
338 m_aTypes.reserve(nFieldCount);
339 m_aPrecisions.reserve(nFieldCount);
340 m_aScales.reserve(nFieldCount);
342 String aStrFieldName;
343 aStrFieldName.AssignAscii("Column");
344 ::rtl::OUString aTypeName;
345 static const ::rtl::OUString sVARCHAR(RTL_CONSTASCII_USTRINGPARAM("VARCHAR"));
346 const sal_Bool bCase = getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers();
347 const bool bFoxPro = m_aHeader.db_typ == VisualFoxPro || m_aHeader.db_typ == VisualFoxProAuto || m_aHeader.db_typ == FoxProMemo;
349 sal_Int32 i = 0;
350 for (; i < nFieldCount; i++)
352 DBFColumn aDBFColumn;
353 m_pFileStream->Read((char*)&aDBFColumn, sizeof(aDBFColumn));
354 if ( FIELD_DESCRIPTOR_TERMINATOR == aDBFColumn.db_fnm[0] ) // 0x0D stored as the Field Descriptor terminator.
355 break;
357 sal_Bool bIsRowVersion = bFoxPro && ( aDBFColumn.db_frei2[0] & 0x01 ) == 0x01;
358 //if ( bFoxPro && ( aDBFColumn.db_frei2[0] & 0x01 ) == 0x01 ) // system column not visible to user
359 // continue;
360 const String aColumnName((const char *)aDBFColumn.db_fnm,m_eEncoding);
362 m_aRealFieldLengths.push_back(aDBFColumn.db_flng);
363 sal_Int32 nPrecision = aDBFColumn.db_flng;
364 sal_Int32 eType;
365 sal_Bool bIsCurrency = sal_False;
367 char cType[2];
368 cType[0] = aDBFColumn.db_typ;
369 cType[1] = 0;
370 aTypeName = ::rtl::OUString::createFromAscii(cType);
371 OSL_TRACE("column type: %c",aDBFColumn.db_typ);
373 switch (aDBFColumn.db_typ)
375 case 'C':
376 eType = DataType::VARCHAR;
377 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VARCHAR"));
378 break;
379 case 'F':
380 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DECIMAL"));
381 case 'N':
382 if ( aDBFColumn.db_typ == 'N' )
383 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("NUMERIC"));
384 eType = DataType::DECIMAL;
386 // Bei numerischen Feldern werden zwei Zeichen mehr geschrieben, als die Precision der Spaltenbeschreibung eigentlich
387 // angibt, um Platz fuer das eventuelle Vorzeichen und das Komma zu haben. Das muss ich jetzt aber wieder rausrechnen.
388 nPrecision = SvDbaseConverter::ConvertPrecisionToOdbc(nPrecision,aDBFColumn.db_dez);
389 // leider gilt das eben Gesagte nicht fuer aeltere Versionen ....
390 break;
391 case 'L':
392 eType = DataType::BIT;
393 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BOOLEAN"));
394 break;
395 case 'Y':
396 bIsCurrency = sal_True;
397 eType = DataType::DOUBLE;
398 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DOUBLE"));
399 break;
400 case 'D':
401 eType = DataType::DATE;
402 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DATE"));
403 break;
404 case 'T':
405 eType = DataType::TIMESTAMP;
406 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TIMESTAMP"));
407 break;
408 case 'I':
409 eType = DataType::INTEGER;
410 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("INTEGER"));
411 break;
412 case 'M':
413 if ( bFoxPro && ( aDBFColumn.db_frei2[0] & 0x04 ) == 0x04 )
415 eType = DataType::LONGVARBINARY;
416 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
418 else
420 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARCHAR"));
421 eType = DataType::LONGVARCHAR;
423 nPrecision = 2147483647;
424 break;
425 case 'P':
426 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
427 eType = DataType::LONGVARBINARY;
428 nPrecision = 2147483647;
429 break;
430 case '0':
431 case 'B':
432 if ( m_aHeader.db_typ == VisualFoxPro || m_aHeader.db_typ == VisualFoxProAuto )
434 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DOUBLE"));
435 eType = DataType::DOUBLE;
437 else
439 aTypeName = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
440 eType = DataType::LONGVARBINARY;
441 nPrecision = 2147483647;
443 break;
444 default:
445 eType = DataType::OTHER;
448 m_aTypes.push_back(eType);
449 m_aPrecisions.push_back(nPrecision);
450 m_aScales.push_back(aDBFColumn.db_dez);
452 Reference< XPropertySet> xCol = new sdbcx::OColumn(aColumnName,
453 aTypeName,
454 ::rtl::OUString(),
455 ColumnValue::NULLABLE,
456 nPrecision,
457 aDBFColumn.db_dez,
458 eType,
459 sal_False,
460 bIsRowVersion,
461 bIsCurrency,
462 bCase);
463 m_aColumns->get().push_back(xCol);
464 } // for (; i < nFieldCount; i++)
465 OSL_ENSURE(i,"No columns in table!");
467 // -------------------------------------------------------------------------
468 ODbaseTable::ODbaseTable(sdbcx::OCollection* _pTables,ODbaseConnection* _pConnection)
469 :ODbaseTable_BASE(_pTables,_pConnection)
470 ,m_pMemoStream(NULL)
471 ,m_bWriteableMemo(sal_False)
473 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::ODbaseTable" );
474 // initialize the header
475 m_aHeader.db_typ = dBaseIII;
476 m_aHeader.db_anz = 0;
477 m_aHeader.db_kopf = 0;
478 m_aHeader.db_slng = 0;
479 m_eEncoding = getConnection()->getTextEncoding();
481 // -------------------------------------------------------------------------
482 ODbaseTable::ODbaseTable(sdbcx::OCollection* _pTables,ODbaseConnection* _pConnection,
483 const ::rtl::OUString& _Name,
484 const ::rtl::OUString& _Type,
485 const ::rtl::OUString& _Description ,
486 const ::rtl::OUString& _SchemaName,
487 const ::rtl::OUString& _CatalogName
488 ) : ODbaseTable_BASE(_pTables,_pConnection,_Name,
489 _Type,
490 _Description,
491 _SchemaName,
492 _CatalogName)
493 ,m_pMemoStream(NULL)
494 ,m_bWriteableMemo(sal_False)
496 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::ODbaseTable" );
497 m_eEncoding = getConnection()->getTextEncoding();
500 // -----------------------------------------------------------------------------
501 void ODbaseTable::construct()
503 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::construct" );
504 // initialize the header
505 m_aHeader.db_typ = dBaseIII;
506 m_aHeader.db_anz = 0;
507 m_aHeader.db_kopf = 0;
508 m_aHeader.db_slng = 0;
509 m_aMemoHeader.db_size = 0;
511 String sFileName(getEntry(m_pConnection,m_Name));
513 INetURLObject aURL;
514 aURL.SetURL(sFileName);
516 OSL_ENSURE( m_pConnection->matchesExtension( aURL.getExtension() ),
517 "ODbaseTable::ODbaseTable: invalid extension!");
518 // getEntry is expected to ensure the corect file name
520 m_pFileStream = createStream_simpleError( sFileName, STREAM_READWRITE | STREAM_NOCREATE | STREAM_SHARE_DENYWRITE);
521 m_bWriteable = ( m_pFileStream != NULL );
523 if ( !m_pFileStream )
525 m_bWriteable = sal_False;
526 m_pFileStream = createStream_simpleError( sFileName, STREAM_READ | STREAM_NOCREATE | STREAM_SHARE_DENYNONE);
529 if(m_pFileStream)
531 readHeader();
532 if (HasMemoFields())
534 // Memo-Dateinamen bilden (.DBT):
535 // nyi: Unschoen fuer Unix und Mac!
537 if ( m_aHeader.db_typ == FoxProMemo || VisualFoxPro == m_aHeader.db_typ || VisualFoxProAuto == m_aHeader.db_typ ) // foxpro uses another extension
538 aURL.SetExtension(String::CreateFromAscii("fpt"));
539 else
540 aURL.SetExtension(String::CreateFromAscii("dbt"));
542 // Wenn die Memodatei nicht gefunden wird, werden die Daten trotzdem angezeigt
543 // allerdings koennen keine Updates durchgefuehrt werden
544 // jedoch die Operation wird ausgefuehrt
545 m_pMemoStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::NO_DECODE), STREAM_READWRITE | STREAM_NOCREATE | STREAM_SHARE_DENYWRITE);
546 if ( !m_pMemoStream )
548 m_bWriteableMemo = sal_False;
549 m_pMemoStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::NO_DECODE), STREAM_READ | STREAM_NOCREATE | STREAM_SHARE_DENYNONE);
551 if (m_pMemoStream)
552 ReadMemoHeader();
554 // if(!m_pColumns && (!m_aColumns.isValid() || !m_aColumns->size()))
555 fillColumns();
557 UINT32 nFileSize = lcl_getFileSize(*m_pFileStream);
558 m_pFileStream->Seek(STREAM_SEEK_TO_BEGIN);
559 if ( m_aHeader.db_anz == 0 && ((nFileSize-m_aHeader.db_kopf)/m_aHeader.db_slng) > 0) // seems to be empty or someone wrote bullshit into the dbase file
560 m_aHeader.db_anz = ((nFileSize-m_aHeader.db_kopf)/m_aHeader.db_slng);
562 // Buffersize abhaengig von der Filegroesse
563 m_pFileStream->SetBufferSize(nFileSize > 1000000 ? 32768 :
564 nFileSize > 100000 ? 16384 :
565 nFileSize > 10000 ? 4096 : 1024);
567 if (m_pMemoStream)
569 // Puffer genau auf Laenge eines Satzes stellen
570 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
571 nFileSize = m_pMemoStream->Tell();
572 m_pMemoStream->Seek(STREAM_SEEK_TO_BEGIN);
574 // Buffersize abhaengig von der Filegroesse
575 m_pMemoStream->SetBufferSize(nFileSize > 1000000 ? 32768 :
576 nFileSize > 100000 ? 16384 :
577 nFileSize > 10000 ? 4096 :
578 m_aMemoHeader.db_size);
581 AllocBuffer();
584 //------------------------------------------------------------------
585 BOOL ODbaseTable::ReadMemoHeader()
587 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::ReadMemoHeader" );
588 m_pMemoStream->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN);
589 m_pMemoStream->RefreshBuffer(); // sicherstellen das die Kopfinformationen tatsaechlich neu gelesen werden
590 m_pMemoStream->Seek(0L);
592 (*m_pMemoStream) >> m_aMemoHeader.db_next;
593 switch (m_aHeader.db_typ)
595 case dBaseIIIMemo: // dBase III: feste Blockgroesse
596 case dBaseIVMemo:
597 // manchmal wird aber auch dBase3 dBase4 Memo zugeordnet
598 m_pMemoStream->Seek(20L);
599 (*m_pMemoStream) >> m_aMemoHeader.db_size;
600 if (m_aMemoHeader.db_size > 1 && m_aMemoHeader.db_size != 512) // 1 steht auch fuer dBase 3
601 m_aMemoHeader.db_typ = MemodBaseIV;
602 else if (m_aMemoHeader.db_size > 1 && m_aMemoHeader.db_size == 512)
604 // nun gibt es noch manche Dateien, die verwenden eine Groessenangabe,
605 // sind aber dennoch dBase Dateien
606 char sHeader[4];
607 m_pMemoStream->Seek(m_aMemoHeader.db_size);
608 m_pMemoStream->Read(sHeader,4);
610 if ((m_pMemoStream->GetErrorCode() != ERRCODE_NONE) || ((BYTE)sHeader[0]) != 0xFF || ((BYTE)sHeader[1]) != 0xFF || ((BYTE)sHeader[2]) != 0x08)
611 m_aMemoHeader.db_typ = MemodBaseIII;
612 else
613 m_aMemoHeader.db_typ = MemodBaseIV;
615 else
617 m_aMemoHeader.db_typ = MemodBaseIII;
618 m_aMemoHeader.db_size = 512;
620 break;
621 case VisualFoxPro:
622 case VisualFoxProAuto:
623 case FoxProMemo:
624 m_aMemoHeader.db_typ = MemoFoxPro;
625 m_pMemoStream->Seek(6L);
626 m_pMemoStream->SetNumberFormatInt(NUMBERFORMAT_INT_BIGENDIAN);
627 (*m_pMemoStream) >> m_aMemoHeader.db_size;
628 break;
629 default:
630 OSL_ENSURE( false, "ODbaseTable::ReadMemoHeader: unsupported memo type!" );
631 break;
633 return TRUE;
635 // -------------------------------------------------------------------------
636 String ODbaseTable::getEntry(OConnection* _pConnection,const ::rtl::OUString& _sName )
638 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getEntry" );
639 ::rtl::OUString sURL;
642 Reference< XResultSet > xDir = _pConnection->getDir()->getStaticResultSet();
643 Reference< XRow> xRow(xDir,UNO_QUERY);
644 ::rtl::OUString sName;
645 ::rtl::OUString sExt;
646 INetURLObject aURL;
647 static const ::rtl::OUString s_sSeparator(RTL_CONSTASCII_USTRINGPARAM("/"));
648 xDir->beforeFirst();
649 while(xDir->next())
651 sName = xRow->getString(1);
652 aURL.SetSmartProtocol(INET_PROT_FILE);
653 String sUrl = _pConnection->getURL() + s_sSeparator + sName;
654 aURL.SetSmartURL( sUrl );
656 // cut the extension
657 sExt = aURL.getExtension();
659 // name and extension have to coincide
660 if ( _pConnection->matchesExtension( sExt ) )
662 sName = sName.replaceAt(sName.getLength()-(sExt.getLength()+1),sExt.getLength()+1,::rtl::OUString());
663 if ( sName == _sName )
665 Reference< XContentAccess > xContentAccess( xDir, UNO_QUERY );
666 sURL = xContentAccess->queryContentIdentifierString();
667 break;
671 xDir->beforeFirst(); // move back to before first record
673 catch(Exception&)
675 OSL_ASSERT(0);
677 return sURL;
679 // -------------------------------------------------------------------------
680 void ODbaseTable::refreshColumns()
682 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::refreshColumns" );
683 ::osl::MutexGuard aGuard( m_aMutex );
685 TStringVector aVector;
686 aVector.reserve(m_aColumns->get().size());
688 for(OSQLColumns::Vector::const_iterator aIter = m_aColumns->get().begin();aIter != m_aColumns->get().end();++aIter)
689 aVector.push_back(Reference< XNamed>(*aIter,UNO_QUERY)->getName());
691 if(m_pColumns)
692 m_pColumns->reFill(aVector);
693 else
694 m_pColumns = new ODbaseColumns(this,m_aMutex,aVector);
696 // -------------------------------------------------------------------------
697 void ODbaseTable::refreshIndexes()
699 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::refreshIndexes" );
700 TStringVector aVector;
701 if(m_pFileStream && (!m_pIndexes || m_pIndexes->getCount() == 0))
703 INetURLObject aURL;
704 aURL.SetURL(getEntry(m_pConnection,m_Name));
706 aURL.setExtension(String::CreateFromAscii("inf"));
707 Config aInfFile(aURL.getFSysPath(INetURLObject::FSYS_DETECT));
708 aInfFile.SetGroup(dBASE_III_GROUP);
709 USHORT nKeyCnt = aInfFile.GetKeyCount();
710 ByteString aKeyName;
711 ByteString aIndexName;
713 for (USHORT nKey = 0; nKey < nKeyCnt; nKey++)
715 // Verweist der Key auf ein Indexfile?...
716 aKeyName = aInfFile.GetKeyName( nKey );
717 //...wenn ja, Indexliste der Tabelle hinzufuegen
718 if (aKeyName.Copy(0,3) == ByteString("NDX") )
720 aIndexName = aInfFile.ReadKey(aKeyName);
721 aURL.setName(String(aIndexName,m_eEncoding));
724 Content aCnt(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
725 if (aCnt.isDocument())
727 aVector.push_back(aURL.getBase());
730 catch(Exception&) // a execption is thrown when no file exists
736 if(m_pIndexes)
737 m_pIndexes->reFill(aVector);
738 else
739 m_pIndexes = new ODbaseIndexes(this,m_aMutex,aVector);
742 // -------------------------------------------------------------------------
743 void SAL_CALL ODbaseTable::disposing(void)
745 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::disposing" );
746 OFileTable::disposing();
747 ::osl::MutexGuard aGuard(m_aMutex);
748 m_aColumns = NULL;
750 // -------------------------------------------------------------------------
751 Sequence< Type > SAL_CALL ODbaseTable::getTypes( ) throw(RuntimeException)
753 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getTypes" );
754 Sequence< Type > aTypes = OTable_TYPEDEF::getTypes();
755 ::std::vector<Type> aOwnTypes;
756 aOwnTypes.reserve(aTypes.getLength());
758 const Type* pBegin = aTypes.getConstArray();
759 const Type* pEnd = pBegin + aTypes.getLength();
760 for(;pBegin != pEnd;++pBegin)
762 if(!(*pBegin == ::getCppuType((const Reference<XKeysSupplier>*)0) ||
763 // *pBegin == ::getCppuType((const Reference<XAlterTable>*)0) ||
764 *pBegin == ::getCppuType((const Reference<XDataDescriptorFactory>*)0)))
766 aOwnTypes.push_back(*pBegin);
769 aOwnTypes.push_back(::getCppuType( (const Reference< ::com::sun::star::lang::XUnoTunnel > *)0 ));
770 Type *pTypes = aOwnTypes.empty() ? 0 : &aOwnTypes[0];
771 return Sequence< Type >(pTypes, aOwnTypes.size());
774 // -------------------------------------------------------------------------
775 Any SAL_CALL ODbaseTable::queryInterface( const Type & rType ) throw(RuntimeException)
777 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::queryInterface" );
778 if( rType == ::getCppuType((const Reference<XKeysSupplier>*)0) ||
779 rType == ::getCppuType((const Reference<XDataDescriptorFactory>*)0))
780 return Any();
782 Any aRet = OTable_TYPEDEF::queryInterface(rType);
783 return aRet.hasValue() ? aRet : ::cppu::queryInterface(rType,static_cast< ::com::sun::star::lang::XUnoTunnel*> (this));
786 //--------------------------------------------------------------------------
787 Sequence< sal_Int8 > ODbaseTable::getUnoTunnelImplementationId()
789 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getUnoTunnelImplementationId" );
790 static ::cppu::OImplementationId * pId = 0;
791 if (! pId)
793 ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
794 if (! pId)
796 static ::cppu::OImplementationId aId;
797 pId = &aId;
800 return pId->getImplementationId();
803 // com::sun::star::lang::XUnoTunnel
804 //------------------------------------------------------------------
805 sal_Int64 ODbaseTable::getSomething( const Sequence< sal_Int8 > & rId ) throw (RuntimeException)
807 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getSomething" );
808 return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )
809 ? reinterpret_cast< sal_Int64 >( this )
810 : ODbaseTable_BASE::getSomething(rId);
812 //------------------------------------------------------------------
813 sal_Bool ODbaseTable::fetchRow(OValueRefRow& _rRow,const OSQLColumns & _rCols, sal_Bool _bUseTableDefs,sal_Bool bRetrieveData)
815 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::fetchRow" );
816 // Einlesen der Daten
817 BOOL bIsCurRecordDeleted = ((char)m_pBuffer[0] == '*') ? TRUE : sal_False;
819 // only read the bookmark
821 // Satz als geloescht markieren
822 // rRow.setState(bIsCurRecordDeleted ? ROW_DELETED : ROW_CLEAN );
823 _rRow->setDeleted(bIsCurRecordDeleted);
824 *(_rRow->get())[0] = m_nFilePos;
826 if (!bRetrieveData)
827 return TRUE;
829 sal_Size nByteOffset = 1;
830 // Felder:
831 OSQLColumns::Vector::const_iterator aIter = _rCols.get().begin();
832 OSQLColumns::Vector::const_iterator aEnd = _rCols.get().end();
833 const sal_Size nCount = _rRow->get().size();
834 for (sal_Size i = 1; aIter != aEnd && nByteOffset <= m_nBufferSize && i < nCount;++aIter, i++)
836 // Laengen je nach Datentyp:
837 sal_Int32 nLen = 0;
838 sal_Int32 nType = 0;
839 if(_bUseTableDefs)
841 nLen = m_aPrecisions[i-1];
842 nType = m_aTypes[i-1];
844 else
846 (*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)) >>= nLen;
847 (*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
849 switch(nType)
851 case DataType::INTEGER:
852 case DataType::DOUBLE:
853 case DataType::TIMESTAMP:
854 case DataType::DATE:
855 case DataType::BIT:
856 case DataType::LONGVARCHAR:
857 case DataType::LONGVARBINARY:
858 nLen = m_aRealFieldLengths[i-1];
859 break;
860 case DataType::DECIMAL:
861 if(_bUseTableDefs)
862 nLen = SvDbaseConverter::ConvertPrecisionToDbase(nLen,m_aScales[i-1]);
863 else
864 nLen = SvDbaseConverter::ConvertPrecisionToDbase(nLen,getINT32((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE))));
865 break; // das Vorzeichen und das Komma
867 case DataType::BINARY:
868 case DataType::OTHER:
869 nByteOffset += nLen;
870 continue;
873 // Ist die Variable ueberhaupt gebunden?
874 if ( !(_rRow->get())[i]->isBound() )
876 // Nein - naechstes Feld.
877 nByteOffset += nLen;
878 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
879 continue;
880 } // if ( !(_rRow->get())[i]->isBound() )
881 if ( ( nByteOffset + nLen) > m_nBufferSize )
882 break; // length doesn't match buffer size.
884 char *pData = (char *) (m_pBuffer + nByteOffset);
886 // (*_rRow)[i].setType(nType);
888 if (nType == DataType::CHAR || nType == DataType::VARCHAR)
890 char cLast = pData[nLen];
891 pData[nLen] = 0;
892 String aStr(pData,(xub_StrLen)nLen,m_eEncoding);
893 aStr.EraseTrailingChars();
895 if ( aStr.Len() )
896 *(_rRow->get())[i] = ::rtl::OUString(aStr);
897 else// keine StringLaenge, dann NULL
898 (_rRow->get())[i]->setNull();
900 pData[nLen] = cLast;
901 } // if (nType == DataType::CHAR || nType == DataType::VARCHAR)
902 else if ( DataType::TIMESTAMP == nType )
904 sal_Int32 nDate = 0,nTime = 0;
905 memcpy(&nDate, pData, 4);
906 memcpy(&nTime, pData+ 4, 4);
907 if ( !nDate && !nTime )
909 (_rRow->get())[i]->setNull();
911 else
913 ::com::sun::star::util::DateTime aDateTime;
914 lcl_CalDate(nDate,nTime,aDateTime);
915 *(_rRow->get())[i] = aDateTime;
918 else if ( DataType::INTEGER == nType )
920 sal_Int32 nValue = 0;
921 memcpy(&nValue, pData, nLen);
922 *(_rRow->get())[i] = nValue;
924 else if ( DataType::DOUBLE == nType )
926 double d = 0.0;
927 if (getBOOL((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
929 sal_Int64 nValue = 0;
930 memcpy(&nValue, pData, nLen);
932 if ( m_aScales[i-1] )
933 d = (double)(nValue / pow(10.0,(int)m_aScales[i-1]));
934 else
935 d = (double)(nValue);
937 else
939 memcpy(&d, pData, nLen);
942 *(_rRow->get())[i] = d;
944 else
946 // Falls Nul-Zeichen im String enthalten sind, in Blanks umwandeln!
947 for (sal_Int32 k = 0; k < nLen; k++)
949 if (pData[k] == '\0')
950 pData[k] = ' ';
953 String aStr(pData, (xub_StrLen)nLen,m_eEncoding); // Spaces am Anfang und am Ende entfernen:
954 aStr.EraseLeadingChars();
955 aStr.EraseTrailingChars();
957 if (!aStr.Len())
959 nByteOffset += nLen;
960 (_rRow->get())[i]->setNull(); // keine Werte -> fertig
961 continue;
964 switch (nType)
966 case DataType::DATE:
968 if (aStr.Len() != nLen)
970 (_rRow->get())[i]->setNull();
971 break;
973 const sal_uInt16 nYear = (sal_uInt16)aStr.Copy( 0, 4 ).ToInt32();
974 const sal_uInt16 nMonth = (sal_uInt16)aStr.Copy( 4, 2 ).ToInt32();
975 const sal_uInt16 nDay = (sal_uInt16)aStr.Copy( 6, 2 ).ToInt32();
977 const ::com::sun::star::util::Date aDate(nDay,nMonth,nYear);
978 *(_rRow->get())[i] = aDate;
980 break;
981 case DataType::DECIMAL:
982 *(_rRow->get())[i] = ORowSetValue(aStr);
983 // pVal->setDouble(SdbTools::ToDouble(aStr));
984 break;
985 case DataType::BIT:
987 BOOL b;
988 switch (* ((const char *)pData))
990 case 'T':
991 case 'Y':
992 case 'J': b = TRUE; break;
993 default: b = FALSE; break;
995 *(_rRow->get())[i] = b;
996 // pVal->setDouble(b);
998 break;
999 case DataType::LONGVARBINARY:
1000 case DataType::BINARY:
1001 case DataType::LONGVARCHAR:
1003 const long nBlockNo = aStr.ToInt32(); // Blocknummer lesen
1004 if (nBlockNo > 0 && m_pMemoStream) // Daten aus Memo-Datei lesen, nur wenn
1006 if ( !ReadMemo(nBlockNo, (_rRow->get())[i]->get()) )
1007 break;
1009 else
1010 (_rRow->get())[i]->setNull();
1011 } break;
1012 default:
1013 OSL_ASSERT("Falscher Type");
1015 (_rRow->get())[i]->setTypeKind(nType);
1018 nByteOffset += nLen;
1019 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1021 return sal_True;
1023 //------------------------------------------------------------------
1024 // -------------------------------------------------------------------------
1025 void ODbaseTable::FileClose()
1027 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::FileClose" );
1028 ::osl::MutexGuard aGuard(m_aMutex);
1029 // falls noch nicht alles geschrieben wurde
1030 if (m_pMemoStream && m_pMemoStream->IsWritable())
1031 m_pMemoStream->Flush();
1033 delete m_pMemoStream;
1034 m_pMemoStream = NULL;
1036 ODbaseTable_BASE::FileClose();
1038 // -------------------------------------------------------------------------
1039 BOOL ODbaseTable::CreateImpl()
1041 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateImpl" );
1042 OSL_ENSURE(!m_pFileStream, "SequenceError");
1044 if ( m_pConnection->isCheckEnabled() && ::dbtools::convertName2SQLName(m_Name,::rtl::OUString()) != m_Name )
1046 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1047 STR_SQL_NAME_ERROR,
1048 "$name$", m_Name
1049 ) );
1050 ::dbtools::throwGenericSQLException( sError, *this );
1053 INetURLObject aURL;
1054 aURL.SetSmartProtocol(INET_PROT_FILE);
1055 String aName = getEntry(m_pConnection,m_Name);
1056 if(!aName.Len())
1058 ::rtl::OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
1059 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
1060 aIdent += ::rtl::OUString::createFromAscii("/");
1061 aIdent += m_Name;
1062 aName = aIdent.getStr();
1064 aURL.SetURL(aName);
1066 if ( !m_pConnection->matchesExtension( aURL.getExtension() ) )
1067 aURL.setExtension(m_pConnection->getExtension());
1071 Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1072 if (aContent.isDocument())
1074 // Hack fuer Bug #30609 , nur wenn das File existiert und die Laenge > 0 gibt es einen Fehler
1075 SvStream* pFileStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::NO_DECODE),STREAM_READ);
1077 if (pFileStream && pFileStream->Seek(STREAM_SEEK_TO_END))
1079 // aStatus.SetError(ERRCODE_IO_ALREADYEXISTS,TABLE,aFile.GetFull());
1080 return sal_False;
1082 delete pFileStream;
1085 catch(Exception&) // a execption is thrown when no file exists
1089 BOOL bMemoFile = sal_False;
1091 sal_Bool bOk = CreateFile(aURL, bMemoFile);
1093 FileClose();
1095 if (!bOk)
1099 Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1100 aContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1102 catch(Exception&) // a execption is thrown when no file exists
1105 return sal_False;
1108 if (bMemoFile)
1110 String aExt = aURL.getExtension();
1111 aURL.setExtension(String::CreateFromAscii("dbt")); // extension for memo file
1112 Content aMemo1Content(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1114 sal_Bool bMemoAlreadyExists = sal_False;
1117 bMemoAlreadyExists = aMemo1Content.isDocument();
1119 catch(Exception&) // a execption is thrown when no file exists
1122 if (bMemoAlreadyExists)
1124 // aStatus.SetError(ERRCODE_IO_ALREADYEXISTS,MEMO,aFile.GetFull());
1125 aURL.setExtension(aExt); // kill dbf file
1128 Content aMemoContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1129 aMemoContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1131 catch(const Exception&)
1134 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1135 STR_COULD_NOT_DELETE_FILE,
1136 "$name$", aName
1137 ) );
1138 ::dbtools::throwGenericSQLException( sError, *this );
1141 if (!CreateMemoFile(aURL))
1143 aURL.setExtension(aExt); // kill dbf file
1144 Content aMemoContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1145 aMemoContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1146 return sal_False;
1148 m_aHeader.db_typ = dBaseIIIMemo;
1150 else
1151 m_aHeader.db_typ = dBaseIII;
1153 return TRUE;
1155 // -----------------------------------------------------------------------------
1156 void ODbaseTable::throwInvalidColumnType(const sal_uInt16 _nErrorId,const ::rtl::OUString& _sColumnName)
1158 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::throwInvalidColumnType" );
1161 // we have to drop the file because it is corrupted now
1162 DropImpl();
1164 catch(const Exception&)
1168 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1169 _nErrorId,
1170 "$columnname$", _sColumnName
1171 ) );
1172 ::dbtools::throwGenericSQLException( sError, *this );
1174 //------------------------------------------------------------------
1175 // erzeugt grundsaetzlich dBase IV Datei Format
1176 BOOL ODbaseTable::CreateFile(const INetURLObject& aFile, BOOL& bCreateMemo)
1178 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateFile" );
1179 bCreateMemo = sal_False;
1180 Date aDate; // aktuelles Datum
1182 m_pFileStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::NO_DECODE),STREAM_READWRITE | STREAM_SHARE_DENYWRITE | STREAM_TRUNC );
1184 if (!m_pFileStream)
1185 return sal_False;
1187 BYTE nDbaseType = dBaseIII;
1188 Reference<XIndexAccess> xColumns(getColumns(),UNO_QUERY);
1189 Reference<XPropertySet> xCol;
1190 const ::rtl::OUString sPropType = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE);
1194 const sal_Int32 nCount = xColumns->getCount();
1195 for(sal_Int32 i=0;i<nCount;++i)
1197 xColumns->getByIndex(i) >>= xCol;
1198 OSL_ENSURE(xCol.is(),"This should be a column!");
1200 switch (getINT32(xCol->getPropertyValue(sPropType)))
1202 case DataType::DOUBLE:
1203 case DataType::INTEGER:
1204 case DataType::TIMESTAMP:
1205 case DataType::LONGVARBINARY:
1206 nDbaseType = VisualFoxPro;
1207 i = nCount; // no more columns need to be checked
1208 break;
1209 } // switch (getINT32(xCol->getPropertyValue(sPropType)))
1212 catch ( const Exception& e )
1214 (void)e;
1218 // we have to drop the file because it is corrupted now
1219 DropImpl();
1221 catch(const Exception&) { }
1222 throw;
1225 char aBuffer[21]; // write buffer
1226 memset(aBuffer,0,sizeof(aBuffer));
1228 m_pFileStream->Seek(0L);
1229 (*m_pFileStream) << (BYTE) nDbaseType; // dBase format
1230 (*m_pFileStream) << (BYTE) (aDate.GetYear() % 100); // aktuelles Datum
1233 (*m_pFileStream) << (BYTE) aDate.GetMonth();
1234 (*m_pFileStream) << (BYTE) aDate.GetDay();
1235 (*m_pFileStream) << 0L; // Anzahl der Datensaetze
1236 (*m_pFileStream) << (USHORT)((m_pColumns->getCount()+1) * 32 + 1); // Kopfinformationen,
1237 // pColumns erhaelt immer eine Spalte mehr
1238 (*m_pFileStream) << (USHORT) 0; // Satzlaenge wird spaeter bestimmt
1239 m_pFileStream->Write(aBuffer, 20);
1241 USHORT nRecLength = 1; // Laenge 1 fuer deleted flag
1242 sal_Int32 nMaxFieldLength = m_pConnection->getMetaData()->getMaxColumnNameLength();
1243 ::rtl::OUString aName;
1244 const ::rtl::OUString sPropName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
1245 const ::rtl::OUString sPropPrec = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION);
1246 const ::rtl::OUString sPropScale = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE);
1250 const sal_Int32 nCount = xColumns->getCount();
1251 for(sal_Int32 i=0;i<nCount;++i)
1253 xColumns->getByIndex(i) >>= xCol;
1254 OSL_ENSURE(xCol.is(),"This should be a column!");
1256 char cTyp( 'C' );
1258 xCol->getPropertyValue(sPropName) >>= aName;
1260 ::rtl::OString aCol;
1261 if ( DBTypeConversion::convertUnicodeString( aName, aCol, m_eEncoding ) > nMaxFieldLength)
1263 throwInvalidColumnType( STR_INVALID_COLUMN_NAME_LENGTH, aName );
1266 (*m_pFileStream) << aCol.getStr();
1267 m_pFileStream->Write(aBuffer, 11 - aCol.getLength());
1269 sal_Int32 nPrecision = 0;
1270 xCol->getPropertyValue(sPropPrec) >>= nPrecision;
1271 sal_Int32 nScale = 0;
1272 xCol->getPropertyValue(sPropScale) >>= nScale;
1274 bool bBinary = false;
1276 switch (getINT32(xCol->getPropertyValue(sPropType)))
1278 case DataType::CHAR:
1279 case DataType::VARCHAR:
1280 cTyp = 'C';
1281 break;
1282 case DataType::DOUBLE:
1283 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1284 cTyp = 'Y';
1285 else
1286 cTyp = 'B';
1287 break;
1288 case DataType::INTEGER:
1289 cTyp = 'I';
1290 break;
1291 case DataType::TINYINT:
1292 case DataType::SMALLINT:
1293 case DataType::BIGINT:
1294 case DataType::DECIMAL:
1295 case DataType::NUMERIC:
1296 case DataType::REAL:
1297 cTyp = 'N'; // nur dBase 3 format
1298 break;
1299 case DataType::TIMESTAMP:
1300 cTyp = 'T';
1301 break;
1302 case DataType::DATE:
1303 cTyp = 'D';
1304 break;
1305 case DataType::BIT:
1306 cTyp = 'L';
1307 break;
1308 case DataType::LONGVARBINARY:
1309 bBinary = true;
1310 // run through
1311 case DataType::LONGVARCHAR:
1312 cTyp = 'M';
1313 break;
1314 default:
1316 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1320 (*m_pFileStream) << cTyp;
1321 if ( nDbaseType == VisualFoxPro )
1322 (*m_pFileStream) << (nRecLength-1);
1323 else
1324 m_pFileStream->Write(aBuffer, 4);
1326 switch(cTyp)
1328 case 'C':
1329 OSL_ENSURE(nPrecision < 255, "ODbaseTable::Create: Column zu lang!");
1330 if (nPrecision > 254)
1332 throwInvalidColumnType(STR_INVALID_COLUMN_PRECISION, aName);
1334 (*m_pFileStream) << (BYTE) Min((ULONG)nPrecision, 255UL); //Feldlaenge
1335 nRecLength = nRecLength + (USHORT)::std::min((USHORT)nPrecision, (USHORT)255UL);
1336 (*m_pFileStream) << (BYTE)0; //Nachkommastellen
1337 break;
1338 case 'F':
1339 case 'N':
1340 OSL_ENSURE(nPrecision >= nScale,
1341 "ODbaseTable::Create: Feldlaenge muss groesser Nachkommastellen sein!");
1342 if (nPrecision < nScale)
1344 throwInvalidColumnType(STR_INVALID_PRECISION_SCALE, aName);
1346 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1348 (*m_pFileStream) << (BYTE)10; // Standard Laenge
1349 (*m_pFileStream) << (BYTE)4;
1350 nRecLength += 10;
1352 else
1354 sal_Int32 nPrec = SvDbaseConverter::ConvertPrecisionToDbase(nPrecision,nScale);
1356 (*m_pFileStream) << (BYTE)( nPrec);
1357 (*m_pFileStream) << (BYTE)nScale;
1358 nRecLength += (USHORT)nPrec;
1360 break;
1361 case 'L':
1362 (*m_pFileStream) << (BYTE)1;
1363 (*m_pFileStream) << (BYTE)0;
1364 ++nRecLength;
1365 break;
1366 case 'I':
1367 (*m_pFileStream) << (BYTE)4;
1368 (*m_pFileStream) << (BYTE)0;
1369 nRecLength += 4;
1370 break;
1371 case 'Y':
1372 case 'B':
1373 case 'T':
1374 case 'D':
1375 (*m_pFileStream) << (BYTE)8;
1376 (*m_pFileStream) << (BYTE)0;
1377 nRecLength += 8;
1378 break;
1379 case 'M':
1380 bCreateMemo = TRUE;
1381 (*m_pFileStream) << (BYTE)10;
1382 (*m_pFileStream) << (BYTE)0;
1383 nRecLength += 10;
1384 if ( bBinary )
1385 aBuffer[0] = 0x06;
1386 break;
1387 default:
1388 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1390 m_pFileStream->Write(aBuffer, 14);
1391 aBuffer[0] = 0x00;
1394 (*m_pFileStream) << (BYTE)FIELD_DESCRIPTOR_TERMINATOR; // kopf ende
1395 (*m_pFileStream) << (char)DBF_EOL;
1396 m_pFileStream->Seek(10L);
1397 (*m_pFileStream) << nRecLength; // Satzlaenge nachtraeglich eintragen
1399 if (bCreateMemo)
1401 m_pFileStream->Seek(0L);
1402 if (nDbaseType == VisualFoxPro)
1403 (*m_pFileStream) << (BYTE) FoxProMemo;
1404 else
1405 (*m_pFileStream) << (BYTE) dBaseIIIMemo;
1406 } // if (bCreateMemo)
1408 catch ( const Exception& e )
1410 (void)e;
1414 // we have to drop the file because it is corrupted now
1415 DropImpl();
1417 catch(const Exception&) { }
1418 throw;
1420 return TRUE;
1423 //------------------------------------------------------------------
1424 // erzeugt grundsaetzlich dBase III Datei Format
1425 BOOL ODbaseTable::CreateMemoFile(const INetURLObject& aFile)
1427 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateMemoFile" );
1428 // Makro zum Filehandling fuers Erzeugen von Tabellen
1429 m_pMemoStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::NO_DECODE),STREAM_READWRITE | STREAM_SHARE_DENYWRITE);
1431 if (!m_pMemoStream)
1432 return sal_False;
1434 char aBuffer[512]; // write buffer
1435 memset(aBuffer,0,sizeof(aBuffer));
1437 #ifdef WIN
1438 m_pMemoStream->Seek(0L);
1439 for (UINT16 i = 0; i < 512; i++)
1441 (*m_pMemoStream) << BYTE(0);
1443 #else
1444 m_pMemoStream->SetFiller('\0');
1445 m_pMemoStream->SetStreamSize(512);
1446 #endif
1448 m_pMemoStream->Seek(0L);
1449 (*m_pMemoStream) << long(1); // Zeiger auf ersten freien Block
1451 m_pMemoStream->Flush();
1452 delete m_pMemoStream;
1453 m_pMemoStream = NULL;
1454 return TRUE;
1456 //------------------------------------------------------------------
1457 BOOL ODbaseTable::Drop_Static(const ::rtl::OUString& _sUrl,sal_Bool _bHasMemoFields,OCollection* _pIndexes )
1459 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::Drop_Static" );
1460 INetURLObject aURL;
1461 aURL.SetURL(_sUrl);
1463 BOOL bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
1465 if(bDropped)
1467 if (_bHasMemoFields)
1468 { // delete the memo fields
1469 aURL.setExtension(String::CreateFromAscii("dbt"));
1470 bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
1473 if(bDropped)
1475 if(_pIndexes)
1479 sal_Int32 i = _pIndexes->getCount();
1480 while (i)
1482 _pIndexes->dropByIndex(--i);
1485 catch(SQLException)
1489 // aFile.SetBase(m_Name);
1490 aURL.setExtension(String::CreateFromAscii("inf"));
1492 // as the inf file does not necessarily exist, we aren't allowed to use UCBContentHelper::Kill
1493 // 89711 - 16.07.2001 - frank.schoenheit@sun.com
1496 ::ucbhelper::Content aDeleteContent( aURL.GetMainURL( INetURLObject::NO_DECODE ), Reference< XCommandEnvironment > () );
1497 aDeleteContent.executeCommand( ::rtl::OUString::createFromAscii( "delete" ), makeAny( sal_Bool( sal_True ) ) );
1499 catch(Exception&)
1501 // silently ignore this ....
1505 return bDropped;
1507 // -----------------------------------------------------------------------------
1508 BOOL ODbaseTable::DropImpl()
1510 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::DropImpl" );
1511 FileClose();
1513 if(!m_pIndexes)
1514 refreshIndexes(); // look for indexes which must be deleted as well
1516 BOOL bDropped = Drop_Static(getEntry(m_pConnection,m_Name),HasMemoFields(),m_pIndexes);
1517 if(!bDropped)
1518 {// we couldn't drop the table so we have to reopen it
1519 construct();
1520 if(m_pColumns)
1521 m_pColumns->refresh();
1523 return bDropped;
1526 //------------------------------------------------------------------
1527 BOOL ODbaseTable::InsertRow(OValueRefVector& rRow, BOOL bFlush,const Reference<XIndexAccess>& _xCols)
1529 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::InsertRow" );
1530 // Buffer mit Leerzeichen fuellen
1531 AllocBuffer();
1532 memset(m_pBuffer, 0, m_aHeader.db_slng);
1534 // Gesamte neue Row uebernehmen:
1535 // ... und am Ende als neuen Record hinzufuegen:
1536 UINT32 nTempPos = m_nFilePos,
1537 nFileSize = 0,
1538 nMemoFileSize = 0;
1540 m_nFilePos = (ULONG)m_aHeader.db_anz + 1;
1541 BOOL bInsertRow = UpdateBuffer( rRow, NULL, _xCols );
1542 if ( bInsertRow )
1544 nFileSize = lcl_getFileSize(*m_pFileStream);
1546 if (HasMemoFields() && m_pMemoStream)
1548 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1549 nMemoFileSize = m_pMemoStream->Tell();
1552 if (!WriteBuffer())
1554 m_pFileStream->SetStreamSize(nFileSize); // alte Groesse restaurieren
1556 if (HasMemoFields() && m_pMemoStream)
1557 m_pMemoStream->SetStreamSize(nMemoFileSize); // alte Groesse restaurieren
1558 m_nFilePos = nTempPos; // Fileposition restaurieren
1560 else
1562 (*m_pFileStream) << (char)DBF_EOL; // write EOL
1563 // Anzahl Datensaetze im Header erhoehen:
1564 m_pFileStream->Seek( 4L );
1565 (*m_pFileStream) << (m_aHeader.db_anz + 1);
1567 // beim AppendOnly kein Flush!
1568 if (bFlush)
1569 m_pFileStream->Flush();
1571 // bei Erfolg # erhoehen
1572 m_aHeader.db_anz++;
1573 *rRow.get()[0] = m_nFilePos; // BOOKmark setzen
1574 m_nFilePos = nTempPos;
1577 else
1578 m_nFilePos = nTempPos;
1580 return bInsertRow;
1583 //------------------------------------------------------------------
1584 BOOL ODbaseTable::UpdateRow(OValueRefVector& rRow, OValueRefRow& pOrgRow,const Reference<XIndexAccess>& _xCols)
1586 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::UpdateRow" );
1587 // Buffer mit Leerzeichen fuellen
1588 AllocBuffer();
1590 // Auf gewuenschten Record positionieren:
1591 long nPos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
1592 m_pFileStream->Seek(nPos);
1593 m_pFileStream->Read((char*)m_pBuffer, m_aHeader.db_slng);
1595 UINT32 nMemoFileSize( 0 );
1596 if (HasMemoFields() && m_pMemoStream)
1598 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1599 nMemoFileSize = m_pMemoStream->Tell();
1601 if (!UpdateBuffer(rRow, pOrgRow,_xCols) || !WriteBuffer())
1603 if (HasMemoFields() && m_pMemoStream)
1604 m_pMemoStream->SetStreamSize(nMemoFileSize); // alte Groesse restaurieren
1606 else
1608 m_pFileStream->Flush();
1610 return sal_True;
1613 //------------------------------------------------------------------
1614 BOOL ODbaseTable::DeleteRow(const OSQLColumns& _rCols)
1616 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::DeleteRow" );
1617 // Einfach das Loesch-Flag setzen (egal, ob es schon gesetzt war
1618 // oder nicht):
1619 // Auf gewuenschten Record positionieren:
1620 long nFilePos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
1621 m_pFileStream->Seek(nFilePos);
1623 OValueRefRow aRow = new OValueRefVector(_rCols.get().size());
1625 if (!fetchRow(aRow,_rCols,TRUE,TRUE))
1626 return sal_False;
1628 Reference<XPropertySet> xCol;
1629 ::rtl::OUString aColName;
1630 ::comphelper::UStringMixEqual aCase(isCaseSensitive());
1631 for (USHORT i = 0; i < m_pColumns->getCount(); i++)
1633 Reference<XPropertySet> xIndex = isUniqueByColumnName(i);
1634 if (xIndex.is())
1636 ::cppu::extractInterface(xCol,m_pColumns->getByIndex(i));
1637 OSL_ENSURE(xCol.is(),"ODbaseTable::DeleteRow column is null!");
1638 if(xCol.is())
1640 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1642 Reference<XUnoTunnel> xTunnel(xIndex,UNO_QUERY);
1643 OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1644 ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1645 OSL_ENSURE(pIndex,"ODbaseTable::DeleteRow: No Index returned!");
1647 OSQLColumns::Vector::const_iterator aIter = _rCols.get().begin();
1648 sal_Int32 nPos = 1;
1649 for(;aIter != _rCols.get().end();++aIter,++nPos)
1651 if(aCase(getString((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME))),aColName))
1652 break;
1654 if (aIter == _rCols.get().end())
1655 continue;
1657 pIndex->Delete(m_nFilePos,*(aRow->get())[nPos]);
1662 m_pFileStream->Seek(nFilePos);
1663 (*m_pFileStream) << (BYTE)'*'; // mark the row in the table as deleted
1664 m_pFileStream->Flush();
1665 return sal_True;
1667 // -------------------------------------------------------------------------
1668 Reference<XPropertySet> ODbaseTable::isUniqueByColumnName(sal_Int32 _nColumnPos)
1670 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::isUniqueByColumnName" );
1671 if(!m_pIndexes)
1672 refreshIndexes();
1673 if(m_pIndexes->hasElements())
1675 Reference<XPropertySet> xCol;
1676 m_pColumns->getByIndex(_nColumnPos) >>= xCol;
1677 OSL_ENSURE(xCol.is(),"ODbaseTable::isUniqueByColumnName column is null!");
1678 ::rtl::OUString sColName;
1679 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sColName;
1681 Reference<XPropertySet> xIndex;
1682 for(sal_Int32 i=0;i<m_pIndexes->getCount();++i)
1684 ::cppu::extractInterface(xIndex,m_pIndexes->getByIndex(i));
1685 if(xIndex.is() && getBOOL(xIndex->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISUNIQUE))))
1687 Reference<XNameAccess> xCols(Reference<XColumnsSupplier>(xIndex,UNO_QUERY)->getColumns());
1688 if(xCols->hasByName(sColName))
1689 return xIndex;
1694 return Reference<XPropertySet>();
1696 //------------------------------------------------------------------
1697 double toDouble(const ByteString& rString)
1699 return ::rtl::math::stringToDouble( rString, '.', ',', NULL, NULL );
1702 //------------------------------------------------------------------
1703 BOOL ODbaseTable::UpdateBuffer(OValueRefVector& rRow, OValueRefRow pOrgRow,const Reference<XIndexAccess>& _xCols)
1705 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::UpdateBuffer" );
1706 OSL_ENSURE(m_pBuffer,"Buffer is NULL!");
1707 if ( !m_pBuffer )
1708 return FALSE;
1709 sal_Int32 nByteOffset = 1;
1711 // Felder aktualisieren:
1712 Reference<XPropertySet> xCol;
1713 Reference<XPropertySet> xIndex;
1714 USHORT i;
1715 ::rtl::OUString aColName;
1716 const sal_Int32 nColumnCount = m_pColumns->getCount();
1717 ::std::vector< Reference<XPropertySet> > aIndexedCols(nColumnCount);
1719 ::comphelper::UStringMixEqual aCase(isCaseSensitive());
1721 Reference<XIndexAccess> xColumns = m_pColumns;
1722 // first search a key that exist already in the table
1723 for (i = 0; i < nColumnCount; ++i)
1725 sal_Int32 nPos = i;
1726 if(_xCols != xColumns)
1728 m_pColumns->getByIndex(i) >>= xCol;
1729 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1730 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1732 for(nPos = 0;nPos<_xCols->getCount();++nPos)
1734 Reference<XPropertySet> xFindCol;
1735 ::cppu::extractInterface(xFindCol,_xCols->getByIndex(nPos));
1736 OSL_ENSURE(xFindCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1737 if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1738 break;
1740 if (nPos >= _xCols->getCount())
1741 continue;
1744 ++nPos;
1745 xIndex = isUniqueByColumnName(i);
1746 aIndexedCols[i] = xIndex;
1747 if (xIndex.is())
1749 // first check if the value is different to the old one and when if it conform to the index
1750 if(pOrgRow.isValid() && (rRow.get()[nPos]->getValue().isNull() || rRow.get()[nPos] == (pOrgRow->get())[nPos]))
1751 continue;
1752 else
1754 // ODbVariantRef xVar = (pVal == NULL) ? new ODbVariant() : pVal;
1755 Reference<XUnoTunnel> xTunnel(xIndex,UNO_QUERY);
1756 OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1757 ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1758 OSL_ENSURE(pIndex,"ODbaseTable::UpdateBuffer: No Index returned!");
1760 if (pIndex->Find(0,*rRow.get()[nPos]))
1762 // es existiert kein eindeutiger Wert
1763 if ( !aColName.getLength() )
1765 m_pColumns->getByIndex(i) >>= xCol;
1766 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1767 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1768 xCol.clear();
1769 } // if ( !aColName.getLength() )
1770 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1771 STR_DUPLICATE_VALUE_IN_COLUMN
1772 ,"$columnname$", aColName
1773 ) );
1774 ::dbtools::throwGenericSQLException( sError, *this );
1780 // when we are here there is no double key in the table
1782 for (i = 0; i < nColumnCount && nByteOffset <= m_nBufferSize ; ++i)
1784 // Laengen je nach Datentyp:
1785 OSL_ENSURE(i < m_aPrecisions.size(),"Illegal index!");
1786 sal_Int32 nLen = 0;
1787 sal_Int32 nType = 0;
1788 sal_Int32 nScale = 0;
1789 if ( i < m_aPrecisions.size() )
1791 nLen = m_aPrecisions[i];
1792 nType = m_aTypes[i];
1793 nScale = m_aScales[i];
1795 else
1797 m_pColumns->getByIndex(i) >>= xCol;
1798 if ( xCol.is() )
1800 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION)) >>= nLen;
1801 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE)) >>= nType;
1802 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE)) >>= nScale;
1806 bool bSetZero = false;
1807 switch (nType)
1809 case DataType::INTEGER:
1810 case DataType::DOUBLE:
1811 case DataType::TIMESTAMP:
1812 bSetZero = true;
1813 case DataType::LONGVARBINARY:
1814 case DataType::DATE:
1815 case DataType::BIT:
1816 case DataType::LONGVARCHAR:
1817 nLen = m_aRealFieldLengths[i];
1818 break;
1819 case DataType::DECIMAL:
1820 nLen = SvDbaseConverter::ConvertPrecisionToDbase(nLen,nScale);
1821 break; // das Vorzeichen und das Komma
1822 default:
1823 break;
1825 } // switch (nType)
1827 sal_Int32 nPos = i;
1828 if(_xCols != xColumns)
1830 m_pColumns->getByIndex(i) >>= xCol;
1831 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1832 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1833 for(nPos = 0;nPos<_xCols->getCount();++nPos)
1835 Reference<XPropertySet> xFindCol;
1836 ::cppu::extractInterface(xFindCol,_xCols->getByIndex(nPos));
1837 if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1838 break;
1840 if (nPos >= _xCols->getCount())
1842 nByteOffset += nLen;
1843 continue;
1849 ++nPos; // the row values start at 1
1850 // Ist die Variable ueberhaupt gebunden?
1851 if ( !rRow.get()[nPos]->isBound() )
1853 // Nein - naechstes Feld.
1854 nByteOffset += nLen;
1855 continue;
1857 if (aIndexedCols[i].is())
1859 Reference<XUnoTunnel> xTunnel(aIndexedCols[i],UNO_QUERY);
1860 OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1861 ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1862 OSL_ENSURE(pIndex,"ODbaseTable::UpdateBuffer: No Index returned!");
1863 // Update !!
1864 if (pOrgRow.isValid() && !rRow.get()[nPos]->getValue().isNull() )//&& pVal->isModified())
1865 pIndex->Update(m_nFilePos,*(pOrgRow->get())[nPos],*rRow.get()[nPos]);
1866 else
1867 pIndex->Insert(m_nFilePos,*rRow.get()[nPos]);
1870 char* pData = (char *)(m_pBuffer + nByteOffset);
1871 if (rRow.get()[nPos]->getValue().isNull())
1873 if ( bSetZero )
1874 memset(pData,0,nLen); // Zuruecksetzen auf NULL
1875 else
1876 memset(pData,' ',nLen); // Zuruecksetzen auf NULL
1877 nByteOffset += nLen;
1878 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1879 continue;
1882 sal_Bool bHadError = sal_False;
1885 switch (nType)
1887 case DataType::TIMESTAMP:
1889 sal_Int32 nJulianDate = 0, nJulianTime = 0;
1890 lcl_CalcJulDate(nJulianDate,nJulianTime,rRow.get()[nPos]->getValue());
1891 // Genau 8 Byte kopieren:
1892 memcpy(pData,&nJulianDate,4);
1893 memcpy(pData+4,&nJulianTime,4);
1895 break;
1896 case DataType::DATE:
1898 ::com::sun::star::util::Date aDate;
1899 if(rRow.get()[nPos]->getValue().getTypeKind() == DataType::DOUBLE)
1900 aDate = ::dbtools::DBTypeConversion::toDate(rRow.get()[nPos]->getValue().getDouble());
1901 else
1902 aDate = rRow.get()[nPos]->getValue();
1903 char s[9];
1904 snprintf(s,
1905 sizeof(s),
1906 "%04d%02d%02d",
1907 (int)aDate.Year,
1908 (int)aDate.Month,
1909 (int)aDate.Day);
1911 // Genau 8 Byte kopieren:
1912 strncpy(pData,s,sizeof s - 1);
1913 } break;
1914 case DataType::INTEGER:
1916 sal_Int32 nValue = rRow.get()[nPos]->getValue();
1917 memcpy(pData,&nValue,nLen);
1919 break;
1920 case DataType::DOUBLE:
1922 const double d = rRow.get()[nPos]->getValue();
1923 m_pColumns->getByIndex(i) >>= xCol;
1925 if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1927 sal_Int64 nValue = 0;
1928 if ( m_aScales[i] )
1929 nValue = (sal_Int64)(d * pow(10.0,(int)m_aScales[i]));
1930 else
1931 nValue = (sal_Int64)(d);
1932 memcpy(pData,&nValue,nLen);
1933 } // if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1934 else
1935 memcpy(pData,&d,nLen);
1937 break;
1938 case DataType::DECIMAL:
1940 memset(pData,' ',nLen); // Zuruecksetzen auf NULL
1942 const double n = rRow.get()[nPos]->getValue();
1944 // ein const_cast, da GetFormatPrecision am SvNumberFormat nicht const ist, obwohl es das eigentlich
1945 // sein koennte und muesste
1947 const ByteString aDefaultValue( ::rtl::math::doubleToString( n, rtl_math_StringFormat_F, nScale, '.', NULL, 0));
1948 BOOL bValidLength = aDefaultValue.Len() <= nLen;
1949 if ( bValidLength )
1951 strncpy(pData,aDefaultValue.GetBuffer(),nLen);
1952 // write the resulting double back
1953 *rRow.get()[nPos] = toDouble(aDefaultValue);
1955 else
1957 m_pColumns->getByIndex(i) >>= xCol;
1958 OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1959 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1960 ::std::list< ::std::pair<const sal_Char* , ::rtl::OUString > > aStringToSubstitutes;
1961 aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$columnname$", aColName));
1962 aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$precision$", String::CreateFromInt32(nLen)));
1963 aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$scale$", String::CreateFromInt32(nScale)));
1964 aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$value$", ::rtl::OStringToOUString(aDefaultValue,RTL_TEXTENCODING_UTF8)));
1966 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1967 STR_INVALID_COLUMN_DECIMAL_VALUE
1968 ,aStringToSubstitutes
1969 ) );
1970 ::dbtools::throwGenericSQLException( sError, *this );
1972 } break;
1973 case DataType::BIT:
1974 *pData = rRow.get()[nPos]->getValue().getBool() ? 'T' : 'F';
1975 break;
1976 case DataType::LONGVARBINARY:
1977 case DataType::LONGVARCHAR:
1979 char cNext = pData[nLen]; // merken und temporaer durch 0 ersetzen
1980 pData[nLen] = '\0'; // das geht, da der Puffer immer ein Zeichen groesser ist ...
1982 ULONG nBlockNo = strtol((const char *)pData,NULL,10); // Blocknummer lesen
1984 // Naechstes Anfangszeichen wieder restaurieren:
1985 pData[nLen] = cNext;
1986 if (!m_pMemoStream || !WriteMemo(rRow.get()[nPos]->get(), nBlockNo))
1987 break;
1989 ByteString aStr;
1990 ByteString aBlock(ByteString::CreateFromInt32(nBlockNo));
1991 aStr.Expand(static_cast<sal_uInt16>(nLen - aBlock.Len()), '0' );
1992 aStr += aBlock;
1993 // Zeichen kopieren:
1994 memset(pData,' ',nLen); // Zuruecksetzen auf NULL
1995 memcpy(pData, aStr.GetBuffer(), nLen);
1996 } break;
1997 default:
1999 memset(pData,' ',nLen); // Zuruecksetzen auf NULL
2001 ::rtl::OUString sStringToWrite( rRow.get()[nPos]->getValue().getString() );
2003 // convert the string, using the connection's encoding
2004 ::rtl::OString sEncoded;
2006 DBTypeConversion::convertUnicodeStringToLength( sStringToWrite, sEncoded, nLen, m_eEncoding );
2007 memcpy( pData, sEncoded.getStr(), sEncoded.getLength() );
2010 break;
2013 catch( SQLException& )
2015 throw;
2017 catch ( Exception& ) { bHadError = sal_True; }
2019 if ( bHadError )
2021 m_pColumns->getByIndex(i) >>= xCol;
2022 OSL_ENSURE( xCol.is(), "ODbaseTable::UpdateBuffer column is null!" );
2023 if ( xCol.is() )
2024 xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
2026 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2027 STR_INVALID_COLUMN_VALUE,
2028 "$columnname$", aColName
2029 ) );
2030 ::dbtools::throwGenericSQLException( sError, *this );
2032 // Und weiter ...
2033 nByteOffset += nLen;
2034 OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
2036 return sal_True;
2039 // -----------------------------------------------------------------------------
2040 BOOL ODbaseTable::WriteMemo(ORowSetValue& aVariable, ULONG& rBlockNr)
2042 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::WriteMemo" );
2043 // wird die BlockNr 0 vorgegeben, wird der block ans Ende gehaengt
2044 ULONG nSize = 0;
2045 ::rtl::OString aStr;
2046 ::com::sun::star::uno::Sequence<sal_Int8> aValue;
2047 BYTE nHeader[4];
2048 const bool bBinary = aVariable.getTypeKind() == DataType::LONGVARBINARY && m_aMemoHeader.db_typ == MemoFoxPro;
2049 if ( bBinary )
2051 aValue = aVariable.getSequence();
2052 nSize = aValue.getLength();
2054 else
2056 nSize = DBTypeConversion::convertUnicodeString( aVariable.getString(), aStr, m_eEncoding );
2059 // Anhaengen oder ueberschreiben
2060 BOOL bAppend = rBlockNr == 0;
2062 if (!bAppend)
2064 switch (m_aMemoHeader.db_typ)
2066 case MemodBaseIII: // dBase III-Memofeld, endet mit 2 * Ctrl-Z
2067 bAppend = nSize > (512 - 2);
2068 break;
2069 case MemoFoxPro:
2070 case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2072 char sHeader[4];
2073 m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2074 m_pMemoStream->SeekRel(4L);
2075 m_pMemoStream->Read(sHeader,4);
2077 ULONG nOldSize;
2078 if (m_aMemoHeader.db_typ == MemoFoxPro)
2079 nOldSize = ((((unsigned char)sHeader[0]) * 256 +
2080 (unsigned char)sHeader[1]) * 256 +
2081 (unsigned char)sHeader[2]) * 256 +
2082 (unsigned char)sHeader[3];
2083 else
2084 nOldSize = ((((unsigned char)sHeader[3]) * 256 +
2085 (unsigned char)sHeader[2]) * 256 +
2086 (unsigned char)sHeader[1]) * 256 +
2087 (unsigned char)sHeader[0] - 8;
2089 // passt die neue Laenge in die belegten Bloecke
2090 ULONG nUsedBlocks = ((nSize + 8) / m_aMemoHeader.db_size) + (((nSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0),
2091 nOldUsedBlocks = ((nOldSize + 8) / m_aMemoHeader.db_size) + (((nOldSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0);
2092 bAppend = nUsedBlocks > nOldUsedBlocks;
2097 if (bAppend)
2099 ULONG nStreamSize = m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2100 // letzten block auffuellen
2101 rBlockNr = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2103 m_pMemoStream->SetStreamSize(rBlockNr * m_aMemoHeader.db_size);
2104 m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2106 else
2108 m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2111 switch (m_aMemoHeader.db_typ)
2113 case MemodBaseIII: // dBase III-Memofeld, endet mit Ctrl-Z
2115 const char cEOF = (char) DBF_EOL;
2116 nSize++;
2117 m_pMemoStream->Write( aStr.getStr(), aStr.getLength() );
2118 (*m_pMemoStream) << cEOF << cEOF;
2119 } break;
2120 case MemoFoxPro:
2121 case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2123 if ( MemodBaseIV == m_aMemoHeader.db_typ )
2124 (*m_pMemoStream) << (BYTE)0xFF
2125 << (BYTE)0xFF
2126 << (BYTE)0x08;
2127 else
2128 (*m_pMemoStream) << (BYTE)0x00
2129 << (BYTE)0x00
2130 << (BYTE)0x00;
2132 UINT32 nWriteSize = nSize;
2133 if (m_aMemoHeader.db_typ == MemoFoxPro)
2135 if ( bBinary )
2136 (*m_pMemoStream) << (BYTE) 0x00; // Picture
2137 else
2138 (*m_pMemoStream) << (BYTE) 0x01; // Memo
2139 for (int i = 4; i > 0; nWriteSize >>= 8)
2140 nHeader[--i] = (BYTE) (nWriteSize % 256);
2142 else
2144 (*m_pMemoStream) << (BYTE) 0x00;
2145 nWriteSize += 8;
2146 for (int i = 0; i < 4; nWriteSize >>= 8)
2147 nHeader[i++] = (BYTE) (nWriteSize % 256);
2150 m_pMemoStream->Write(nHeader,4);
2151 if ( bBinary )
2152 m_pMemoStream->Write( aValue.getConstArray(), aValue.getLength() );
2153 else
2154 m_pMemoStream->Write( aStr.getStr(), aStr.getLength() );
2155 m_pMemoStream->Flush();
2160 // Schreiben der neuen Blocknummer
2161 if (bAppend)
2163 ULONG nStreamSize = m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2164 m_aMemoHeader.db_next = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2166 // Schreiben der neuen Blocknummer
2167 m_pMemoStream->Seek(0L);
2168 (*m_pMemoStream) << m_aMemoHeader.db_next;
2169 m_pMemoStream->Flush();
2171 return sal_True;
2174 // -----------------------------------------------------------------------------
2175 // XAlterTable
2176 void SAL_CALL ODbaseTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException)
2178 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumnByName" );
2179 ::osl::MutexGuard aGuard(m_aMutex);
2180 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2183 Reference<XDataDescriptorFactory> xOldColumn;
2184 m_pColumns->getByName(colName) >>= xOldColumn;
2186 alterColumn(m_pColumns->findColumn(colName)-1,descriptor,xOldColumn);
2188 // -------------------------------------------------------------------------
2189 void SAL_CALL ODbaseTable::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
2191 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumnByIndex" );
2192 ::osl::MutexGuard aGuard(m_aMutex);
2193 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2195 if(index < 0 || index >= m_pColumns->getCount())
2196 throw IndexOutOfBoundsException(::rtl::OUString::valueOf(index),*this);
2198 Reference<XDataDescriptorFactory> xOldColumn;
2199 m_pColumns->getByIndex(index) >>= xOldColumn;
2200 alterColumn(index,descriptor,xOldColumn);
2202 // -----------------------------------------------------------------------------
2203 void ODbaseTable::alterColumn(sal_Int32 index,
2204 const Reference< XPropertySet >& descriptor ,
2205 const Reference< XDataDescriptorFactory >& xOldColumn )
2207 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumn" );
2208 if(index < 0 || index >= m_pColumns->getCount())
2209 throw IndexOutOfBoundsException(::rtl::OUString::valueOf(index),*this);
2211 ODbaseTable* pNewTable = NULL;
2214 OSL_ENSURE(descriptor.is(),"ODbaseTable::alterColumn: descriptor can not be null!");
2215 // creates a copy of the the original column and copy all properties from descriptor in xCopyColumn
2216 Reference<XPropertySet> xCopyColumn;
2217 if(xOldColumn.is())
2218 xCopyColumn = xOldColumn->createDataDescriptor();
2219 else
2220 xCopyColumn = new OColumn(getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
2222 ::comphelper::copyProperties(descriptor,xCopyColumn);
2224 // creates a temp file
2226 String sTempName = createTempFile();
2228 pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2229 Reference<XPropertySet> xHoldTable = pNewTable;
2230 pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2231 Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2232 OSL_ENSURE(xAppend.is(),"ODbaseTable::alterColumn: No XAppend interface!");
2234 // copy the structure
2235 sal_Int32 i=0;
2236 for(;i < index;++i)
2238 Reference<XPropertySet> xProp;
2239 m_pColumns->getByIndex(i) >>= xProp;
2240 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2241 Reference<XPropertySet> xCpy;
2242 if(xColumn.is())
2243 xCpy = xColumn->createDataDescriptor();
2244 else
2245 xCpy = new OColumn(getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
2246 ::comphelper::copyProperties(xProp,xCpy);
2247 xAppend->appendByDescriptor(xCpy);
2249 ++i; // now insert our new column
2250 xAppend->appendByDescriptor(xCopyColumn);
2252 for(;i < m_pColumns->getCount();++i)
2254 Reference<XPropertySet> xProp;
2255 m_pColumns->getByIndex(i) >>= xProp;
2256 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2257 Reference<XPropertySet> xCpy;
2258 if(xColumn.is())
2259 xCpy = xColumn->createDataDescriptor();
2260 else
2261 xCpy = new OColumn(getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers());
2262 ::comphelper::copyProperties(xProp,xCpy);
2263 xAppend->appendByDescriptor(xCpy);
2266 // construct the new table
2267 if(!pNewTable->CreateImpl())
2269 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2270 STR_COLUMN_NOT_ALTERABLE,
2271 "$columnname$", ::comphelper::getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2272 ) );
2273 ::dbtools::throwGenericSQLException( sError, *this );
2276 pNewTable->construct();
2278 // copy the data
2279 copyData(pNewTable,0);
2281 // now drop the old one
2282 if( DropImpl() ) // we don't want to delete the memo columns too
2284 // rename the new one to the old one
2285 pNewTable->renameImpl(m_Name);
2286 // release the temp file
2287 pNewTable = NULL;
2288 ::comphelper::disposeComponent(xHoldTable);
2290 else
2292 pNewTable = NULL;
2294 FileClose();
2295 construct();
2296 if(m_pColumns)
2297 m_pColumns->refresh();
2300 catch(const SQLException&)
2302 throw;
2304 catch(const Exception&)
2306 OSL_ENSURE(0,"ODbaseTable::alterColumn: Exception occured!");
2307 throw;
2310 // -----------------------------------------------------------------------------
2311 Reference< XDatabaseMetaData> ODbaseTable::getMetaData() const
2313 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getMetaData" );
2314 return getConnection()->getMetaData();
2316 // -------------------------------------------------------------------------
2317 void SAL_CALL ODbaseTable::rename( const ::rtl::OUString& newName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException)
2319 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::rename" );
2320 ::osl::MutexGuard aGuard(m_aMutex);
2321 checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2322 if(m_pTables && m_pTables->hasByName(newName))
2323 throw ElementExistException(newName,*this);
2326 renameImpl(newName);
2328 ODbaseTable_BASE::rename(newName);
2330 construct();
2331 if(m_pColumns)
2332 m_pColumns->refresh();
2334 namespace
2336 void renameFile(OConnection* _pConenction,const ::rtl::OUString& oldName,
2337 const ::rtl::OUString& newName,const String& _sExtension)
2339 String aName = ODbaseTable::getEntry(_pConenction,oldName);
2340 if(!aName.Len())
2342 ::rtl::OUString aIdent = _pConenction->getContent()->getIdentifier()->getContentIdentifier();
2343 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2344 aIdent += ::rtl::OUString::createFromAscii("/");
2345 aIdent += oldName;
2346 aName = aIdent;
2348 INetURLObject aURL;
2349 aURL.SetURL(aName);
2351 aURL.setExtension( _sExtension );
2352 String sNewName(newName);
2353 sNewName.AppendAscii(".");
2354 sNewName += _sExtension;
2358 Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
2360 Sequence< PropertyValue > aProps( 1 );
2361 aProps[0].Name = ::rtl::OUString::createFromAscii("Title");
2362 aProps[0].Handle = -1; // n/a
2363 aProps[0].Value = makeAny( ::rtl::OUString(sNewName) );
2364 Sequence< Any > aValues;
2365 aContent.executeCommand( rtl::OUString::createFromAscii( "setPropertyValues" ),makeAny(aProps) ) >>= aValues;
2366 if(aValues.getLength() && aValues[0].hasValue())
2367 throw Exception();
2369 catch(Exception&)
2371 throw ElementExistException(newName,NULL);
2375 // -------------------------------------------------------------------------
2376 void SAL_CALL ODbaseTable::renameImpl( const ::rtl::OUString& newName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException)
2378 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getEntry" );
2379 ::osl::MutexGuard aGuard(m_aMutex);
2381 FileClose();
2384 renameFile(m_pConnection,m_Name,newName,m_pConnection->getExtension());
2385 if ( HasMemoFields() )
2386 { // delete the memo fields
2387 String sExt = String::CreateFromAscii("dbt");
2388 renameFile(m_pConnection,m_Name,newName,sExt);
2391 // -----------------------------------------------------------------------------
2392 void ODbaseTable::addColumn(const Reference< XPropertySet >& _xNewColumn)
2394 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::addColumn" );
2395 String sTempName = createTempFile();
2397 ODbaseTable* pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2398 Reference< XPropertySet > xHold = pNewTable;
2399 pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2401 Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2402 sal_Bool bCase = getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers();
2403 // copy the structure
2404 for(sal_Int32 i=0;i < m_pColumns->getCount();++i)
2406 Reference<XPropertySet> xProp;
2407 m_pColumns->getByIndex(i) >>= xProp;
2408 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2409 Reference<XPropertySet> xCpy;
2410 if(xColumn.is())
2411 xCpy = xColumn->createDataDescriptor();
2412 else
2414 xCpy = new OColumn(bCase);
2415 ::comphelper::copyProperties(xProp,xCpy);
2418 xAppend->appendByDescriptor(xCpy);
2420 Reference<XPropertySet> xCpy = new OColumn(bCase);
2421 ::comphelper::copyProperties(_xNewColumn,xCpy);
2422 xAppend->appendByDescriptor(xCpy);
2425 // construct the new table
2426 if(!pNewTable->CreateImpl())
2428 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2429 STR_COLUMN_NOT_ADDABLE,
2430 "$columnname$", ::comphelper::getString(_xNewColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2431 ) );
2432 ::dbtools::throwGenericSQLException( sError, *this );
2435 BOOL bAlreadyDroped = FALSE;
2438 pNewTable->construct();
2439 // copy the data
2440 copyData(pNewTable,pNewTable->m_pColumns->getCount());
2441 // drop the old table
2442 if(DropImpl())
2444 bAlreadyDroped = TRUE;
2445 pNewTable->renameImpl(m_Name);
2446 // release the temp file
2448 xHold = pNewTable = NULL;
2450 FileClose();
2451 construct();
2452 if(m_pColumns)
2453 m_pColumns->refresh();
2455 catch(const SQLException&)
2457 // here we know that the old table wasn't droped before
2458 if(!bAlreadyDroped)
2459 xHold = pNewTable = NULL;
2461 throw;
2464 // -----------------------------------------------------------------------------
2465 void ODbaseTable::dropColumn(sal_Int32 _nPos)
2467 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::dropColumn" );
2468 String sTempName = createTempFile();
2470 ODbaseTable* pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2471 Reference< XPropertySet > xHold = pNewTable;
2472 pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2474 Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2475 sal_Bool bCase = getConnection()->getMetaData()->storesMixedCaseQuotedIdentifiers();
2476 // copy the structure
2477 for(sal_Int32 i=0;i < m_pColumns->getCount();++i)
2479 if(_nPos != i)
2481 Reference<XPropertySet> xProp;
2482 m_pColumns->getByIndex(i) >>= xProp;
2483 Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2484 Reference<XPropertySet> xCpy;
2485 if(xColumn.is())
2486 xCpy = xColumn->createDataDescriptor();
2487 else
2489 xCpy = new OColumn(bCase);
2490 ::comphelper::copyProperties(xProp,xCpy);
2492 xAppend->appendByDescriptor(xCpy);
2497 // construct the new table
2498 if(!pNewTable->CreateImpl())
2500 xHold = pNewTable = NULL;
2501 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2502 STR_COLUMN_NOT_DROP,
2503 "$position$", ::rtl::OUString::valueOf(_nPos)
2504 ) );
2505 ::dbtools::throwGenericSQLException( sError, *this );
2507 pNewTable->construct();
2508 // copy the data
2509 copyData(pNewTable,_nPos);
2510 // drop the old table
2511 if(DropImpl())
2512 pNewTable->renameImpl(m_Name);
2513 // release the temp file
2515 xHold = pNewTable = NULL;
2517 FileClose();
2518 construct();
2520 // -----------------------------------------------------------------------------
2521 String ODbaseTable::createTempFile()
2523 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::createTempFile" );
2524 ::rtl::OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
2525 if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2526 aIdent += ::rtl::OUString::createFromAscii("/");
2527 String sTempName(aIdent);
2528 String sExt;
2529 sExt.AssignAscii(".");
2530 sExt += m_pConnection->getExtension();
2532 String sName(m_Name);
2533 TempFile aTempFile(sName,&sExt,&sTempName);
2534 if(!aTempFile.IsValid())
2535 getConnection()->throwGenericSQLException(STR_COULD_NOT_ALTER_TABLE,*this);
2537 INetURLObject aURL;
2538 aURL.SetSmartProtocol(INET_PROT_FILE);
2539 aURL.SetURL(aTempFile.GetURL());
2541 String sNewName(aURL.getName());
2542 sNewName.Erase(sNewName.Len() - sExt.Len());
2543 return sNewName;
2545 // -----------------------------------------------------------------------------
2546 void ODbaseTable::copyData(ODbaseTable* _pNewTable,sal_Int32 _nPos)
2548 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::copyData" );
2549 sal_Int32 nPos = _nPos + 1; // +1 because we always have the bookmark clumn as well
2550 OValueRefRow aRow = new OValueRefVector(m_pColumns->getCount());
2551 OValueRefRow aInsertRow;
2552 if(_nPos)
2554 aInsertRow = new OValueRefVector(_pNewTable->m_pColumns->getCount());
2555 ::std::for_each(aInsertRow->get().begin(),aInsertRow->get().end(),TSetRefBound(sal_True));
2557 else
2558 aInsertRow = aRow;
2560 // we only have to bind the values which we need to copy into the new table
2561 ::std::for_each(aRow->get().begin(),aRow->get().end(),TSetRefBound(sal_True));
2562 if(_nPos && (_nPos < (sal_Int32)aRow->get().size()))
2563 (aRow->get())[nPos]->setBound(sal_False);
2566 sal_Bool bOk = sal_True;
2567 sal_Int32 nCurPos;
2568 OValueRefVector::Vector::iterator aIter;
2569 for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.db_anz;++nRowPos)
2571 bOk = seekRow( IResultSetHelper::BOOKMARK, nRowPos+1, nCurPos );
2572 if ( bOk )
2574 bOk = fetchRow( aRow, m_aColumns.getBody(), sal_True, sal_True);
2575 if ( bOk && !aRow->isDeleted() ) // copy only not deleted rows
2577 // special handling when pos == 0 then we don't have to distinguish between the two rows
2578 if(_nPos)
2580 aIter = aRow->get().begin()+1;
2581 sal_Int32 nCount = 1;
2582 for(OValueRefVector::Vector::iterator aInsertIter = aInsertRow->get().begin()+1; aIter != aRow->get().end() && aInsertIter != aInsertRow->get().end();++aIter,++nCount)
2584 if(nPos != nCount)
2586 (*aInsertIter)->setValue( (*aIter)->getValue() );
2587 ++aInsertIter;
2591 bOk = _pNewTable->InsertRow(*aInsertRow,sal_True,_pNewTable->m_pColumns);
2592 OSL_ENSURE(bOk,"Row could not be inserted!");
2594 else
2595 OSL_ENSURE(bOk,"Row could not be fetched!");
2597 else
2599 OSL_ASSERT(0);
2601 } // for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.db_anz;++nRowPos)
2603 // -----------------------------------------------------------------------------
2604 void ODbaseTable::throwInvalidDbaseFormat()
2606 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::throwInvalidDbaseFormat" );
2607 FileClose();
2608 // no dbase file
2610 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2611 STR_SQL_NAME_ERROR,
2612 "$filename$", getEntry(m_pConnection,m_Name)
2613 ) );
2614 ::dbtools::throwGenericSQLException( sError, *this );
2616 // -----------------------------------------------------------------------------
2617 void ODbaseTable::refreshHeader()
2619 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::refreshHeader" );
2620 if ( m_aHeader.db_anz == 0 )
2621 readHeader();
2623 //------------------------------------------------------------------
2624 sal_Bool ODbaseTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
2626 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::seekRow" );
2627 // ----------------------------------------------------------
2628 // Positionierung vorbereiten:
2629 OSL_ENSURE(m_pFileStream,"ODbaseTable::seekRow: FileStream is NULL!");
2631 sal_uInt32 nNumberOfRecords = (sal_uInt32)m_aHeader.db_anz;
2632 sal_uInt32 nTempPos = m_nFilePos;
2633 m_nFilePos = nCurPos;
2635 switch(eCursorPosition)
2637 case IResultSetHelper::NEXT:
2638 ++m_nFilePos;
2639 break;
2640 case IResultSetHelper::PRIOR:
2641 if (m_nFilePos > 0)
2642 --m_nFilePos;
2643 break;
2644 case IResultSetHelper::FIRST:
2645 m_nFilePos = 1;
2646 break;
2647 case IResultSetHelper::LAST:
2648 m_nFilePos = nNumberOfRecords;
2649 break;
2650 case IResultSetHelper::RELATIVE:
2651 m_nFilePos = (((sal_Int32)m_nFilePos) + nOffset < 0) ? 0L
2652 : (sal_uInt32)(((sal_Int32)m_nFilePos) + nOffset);
2653 break;
2654 case IResultSetHelper::ABSOLUTE:
2655 case IResultSetHelper::BOOKMARK:
2656 m_nFilePos = (sal_uInt32)nOffset;
2657 break;
2660 if (m_nFilePos > (sal_Int32)nNumberOfRecords)
2661 m_nFilePos = (sal_Int32)nNumberOfRecords + 1;
2663 if (m_nFilePos == 0 || m_nFilePos == (sal_Int32)nNumberOfRecords + 1)
2664 goto Error;
2665 else
2667 sal_uInt16 nEntryLen = m_aHeader.db_slng;
2669 OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: ungueltige Record-Position");
2670 sal_Int32 nPos = m_aHeader.db_kopf + (sal_Int32)(m_nFilePos-1) * nEntryLen;
2672 ULONG nLen = m_pFileStream->Seek(nPos);
2673 if (m_pFileStream->GetError() != ERRCODE_NONE)
2674 goto Error;
2676 nLen = m_pFileStream->Read((char*)m_pBuffer, nEntryLen);
2677 if (m_pFileStream->GetError() != ERRCODE_NONE)
2678 goto Error;
2680 goto End;
2682 Error:
2683 switch(eCursorPosition)
2685 case IResultSetHelper::PRIOR:
2686 case IResultSetHelper::FIRST:
2687 m_nFilePos = 0;
2688 break;
2689 case IResultSetHelper::LAST:
2690 case IResultSetHelper::NEXT:
2691 case IResultSetHelper::ABSOLUTE:
2692 case IResultSetHelper::RELATIVE:
2693 if (nOffset > 0)
2694 m_nFilePos = nNumberOfRecords + 1;
2695 else if (nOffset < 0)
2696 m_nFilePos = 0;
2697 break;
2698 case IResultSetHelper::BOOKMARK:
2699 m_nFilePos = nTempPos; // vorherige Position
2701 // aStatus.Set(SDB_STAT_NO_DATA_FOUND);
2702 return sal_False;
2704 End:
2705 nCurPos = m_nFilePos;
2706 return sal_True;
2708 // -----------------------------------------------------------------------------
2709 BOOL ODbaseTable::ReadMemo(ULONG nBlockNo, ORowSetValue& aVariable)
2711 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::ReadMemo" );
2712 BOOL bIsText = TRUE;
2713 // SdbConnection* pConnection = GetConnection();
2715 m_pMemoStream->Seek(nBlockNo * m_aMemoHeader.db_size);
2716 switch (m_aMemoHeader.db_typ)
2718 case MemodBaseIII: // dBase III-Memofeld, endet mit Ctrl-Z
2720 const char cEOF = (char) DBF_EOL;
2721 ByteString aBStr;
2722 static char aBuf[514];
2723 aBuf[512] = 0; // sonst kann der Zufall uebel mitspielen
2724 BOOL bReady = sal_False;
2728 m_pMemoStream->Read(&aBuf,512);
2730 USHORT i = 0;
2731 while (aBuf[i] != cEOF && ++i < 512)
2733 bReady = aBuf[i] == cEOF;
2735 aBuf[i] = 0;
2736 aBStr += aBuf;
2738 } while (!bReady && !m_pMemoStream->IsEof() && aBStr.Len() < STRING_MAXLEN);
2740 ::rtl::OUString aStr(aBStr.GetBuffer(), aBStr.Len(),m_eEncoding);
2741 aVariable = aStr;
2743 } break;
2744 case MemoFoxPro:
2745 case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2747 char sHeader[4];
2748 m_pMemoStream->Read(sHeader,4);
2749 // Foxpro stores text and binary data
2750 if (m_aMemoHeader.db_typ == MemoFoxPro)
2752 // if (((BYTE)sHeader[0]) != 0 || ((BYTE)sHeader[1]) != 0 || ((BYTE)sHeader[2]) != 0)
2753 // {
2754 //// String aText = String(SdbResId(STR_STAT_IResultSetHelper::INVALID));
2755 //// aText.SearchAndReplace(String::CreateFromAscii("%%d"),m_pMemoStream->GetFileName());
2756 //// aText.SearchAndReplace(String::CreateFromAscii("%%t"),aStatus.TypeToString(MEMO));
2757 //// aStatus.Set(SDB_STAT_ERROR,
2758 //// String::CreateFromAscii("01000"),
2759 //// aStatus.CreateErrorMessage(aText),
2760 //// 0, String() );
2761 // return sal_False;
2762 // }
2764 bIsText = sHeader[3] != 0;
2766 else if (((BYTE)sHeader[0]) != 0xFF || ((BYTE)sHeader[1]) != 0xFF || ((BYTE)sHeader[2]) != 0x08)
2768 // String aText = String(SdbResId(STR_STAT_IResultSetHelper::INVALID));
2769 // aText.SearchAndReplace(String::CreateFromAscii("%%d"),m_pMemoStream->GetFileName());
2770 // aText.SearchAndReplace(String::CreateFromAscii("%%t"),aStatus.TypeToString(MEMO));
2771 // aStatus.Set(SDB_STAT_ERROR,
2772 // String::CreateFromAscii("01000"),
2773 // aStatus.CreateErrorMessage(aText),
2774 // 0, String() );
2775 return sal_False;
2778 sal_uInt32 nLength(0);
2779 (*m_pMemoStream) >> nLength;
2781 if (m_aMemoHeader.db_typ == MemodBaseIV)
2782 nLength -= 8;
2784 if ( nLength )
2786 if ( bIsText )
2788 // char cChar;
2789 ::rtl::OUStringBuffer aStr;
2790 while ( nLength > STRING_MAXLEN )
2792 ByteString aBStr;
2793 aBStr.Expand(STRING_MAXLEN);
2794 m_pMemoStream->Read(aBStr.AllocBuffer(STRING_MAXLEN),STRING_MAXLEN);
2795 aStr.append(::rtl::OUString(aBStr.GetBuffer(),aBStr.Len(), m_eEncoding));
2796 nLength -= STRING_MAXLEN;
2798 if ( nLength > 0 )
2800 ByteString aBStr;
2801 aBStr.Expand(static_cast<xub_StrLen>(nLength));
2802 m_pMemoStream->Read(aBStr.AllocBuffer(static_cast<xub_StrLen>(nLength)),nLength);
2803 // aBStr.ReleaseBufferAccess();
2804 aStr.append(::rtl::OUString(aBStr.GetBuffer(),aBStr.Len(), m_eEncoding));
2806 if ( aStr.getLength() )
2807 aVariable = aStr.makeStringAndClear();
2808 } // if ( bIsText )
2809 else
2811 ::com::sun::star::uno::Sequence< sal_Int8 > aData(nLength);
2812 m_pMemoStream->Read(aData.getArray(),nLength);
2813 aVariable = aData;
2815 } // if ( nLength )
2818 return sal_True;
2820 // -----------------------------------------------------------------------------
2821 void ODbaseTable::AllocBuffer()
2823 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::AllocBuffer" );
2824 UINT16 nSize = m_aHeader.db_slng;
2825 OSL_ENSURE(nSize > 0, "Size too small");
2827 if (m_nBufferSize != nSize)
2829 delete m_pBuffer;
2830 m_pBuffer = NULL;
2833 // Falls noch kein Puffer vorhanden: allozieren:
2834 if (m_pBuffer == NULL && nSize)
2836 m_nBufferSize = nSize;
2837 m_pBuffer = new BYTE[m_nBufferSize+1];
2840 // -----------------------------------------------------------------------------
2841 BOOL ODbaseTable::WriteBuffer()
2843 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::WriteBuffer" );
2844 OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: ungueltige Record-Position");
2846 // Auf gewuenschten Record positionieren:
2847 long nPos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
2848 m_pFileStream->Seek(nPos);
2849 return m_pFileStream->Write((char*) m_pBuffer, m_aHeader.db_slng) > 0;
2851 // -----------------------------------------------------------------------------
2852 sal_Int32 ODbaseTable::getCurrentLastPos() const
2854 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getCurrentLastPos" );
2855 return m_aHeader.db_anz;