1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
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>
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
95 sal_Int32
lcl_getFileSize(SvStream
& _rStream
)
97 sal_Int32 nFileSize
= 0;
98 _rStream
.Seek(STREAM_SEEK_TO_END
);
102 nFileSize
= _rStream
.Tell();
103 if ( cEOL
== DBF_EOL
)
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
;
114 if (aDateTime
.Month
> 12)
117 sal_uInt16 delta
= _aDateTime
.Month
/ 12;
118 aDateTime
.Year
+= delta
;
119 aDateTime
.Month
-= delta
* 12;
123 _nJulianTime
= ((aDateTime
.Hours
*3600000)+(aDateTime
.Minutes
*60000)+(aDateTime
.Seconds
*1000)+(aDateTime
.HundredthSeconds
*10));
124 /* conversion factors */
127 if ( aDateTime
.Month
<= 2 )
129 iy0
= aDateTime
.Year
- 1;
130 im0
= aDateTime
.Month
+ 12;
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 )
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 */
160 calculates date time from the Julian Date
162 void lcl_CalDate(sal_Int32 _nJulianDate
,sal_Int32 _nJulianTime
,com::sun::star::util::DateTime
& _rDateTime
)
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 )));
179 _rDateTime
.Month
= static_cast<sal_uInt16
>(ke
- 13);
181 _rDateTime
.Month
= static_cast<sal_uInt16
>(ke
- 1);
182 if ( (_rDateTime
.Month
== 2) && (_rDateTime
.Day
> 28) )
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);
189 _rDateTime
.Year
= static_cast<sal_uInt16
>(kc
- 4715);
190 } // if ( _nJulianDate )
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
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,
206 // for (int i = 0; i < sizeof(test_tbl)/sizeof(test_tbl[0]); i++)
208 // if (test == test_tbl[i])
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;
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!");
232 m_pFileStream
->RefreshBuffer(); // sicherstellen, dass die Kopfinformationen tatsaechlich neu gelesen werden
233 m_pFileStream
->Seek(STREAM_SEEK_TO_BEGIN
);
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
259 throwInvalidDbaseFormat();
263 // Konsistenzpruefung des Header:
264 m_aHeader
.db_typ
= (DBFType
)nType
;
265 switch (m_aHeader
.db_typ
)
271 case VisualFoxProAuto
:
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
308 m_pFileStream
->SetNumberFormatInt(NUMBERFORMAT_INT_LITTLEENDIAN
);
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();
327 m_aColumns
->get().clear();
330 m_aPrecisions
.clear();
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
;
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.
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
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
;
365 sal_Bool bIsCurrency
= sal_False
;
368 cType
[0] = aDBFColumn
.db_typ
;
370 aTypeName
= ::rtl::OUString::createFromAscii(cType
);
371 OSL_TRACE("column type: %c",aDBFColumn
.db_typ
);
373 switch (aDBFColumn
.db_typ
)
376 eType
= DataType::VARCHAR
;
377 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VARCHAR"));
380 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DECIMAL"));
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 ....
392 eType
= DataType::BIT
;
393 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("BOOLEAN"));
396 bIsCurrency
= sal_True
;
397 eType
= DataType::DOUBLE
;
398 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DOUBLE"));
401 eType
= DataType::DATE
;
402 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DATE"));
405 eType
= DataType::TIMESTAMP
;
406 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("TIMESTAMP"));
409 eType
= DataType::INTEGER
;
410 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("INTEGER"));
413 if ( bFoxPro
&& ( aDBFColumn
.db_frei2
[0] & 0x04 ) == 0x04 )
415 eType
= DataType::LONGVARBINARY
;
416 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
420 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARCHAR"));
421 eType
= DataType::LONGVARCHAR
;
423 nPrecision
= 2147483647;
426 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
427 eType
= DataType::LONGVARBINARY
;
428 nPrecision
= 2147483647;
432 if ( m_aHeader
.db_typ
== VisualFoxPro
|| m_aHeader
.db_typ
== VisualFoxProAuto
)
434 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("DOUBLE"));
435 eType
= DataType::DOUBLE
;
439 aTypeName
= ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("LONGVARBINARY"));
440 eType
= DataType::LONGVARBINARY
;
441 nPrecision
= 2147483647;
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
,
455 ColumnValue::NULLABLE
,
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
)
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
,
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
));
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
);
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"));
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
);
554 // if(!m_pColumns && (!m_aColumns.isValid() || !m_aColumns->size()))
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);
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
);
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
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
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
;
613 m_aMemoHeader
.db_typ
= MemodBaseIV
;
617 m_aMemoHeader
.db_typ
= MemodBaseIII
;
618 m_aMemoHeader
.db_size
= 512;
622 case VisualFoxProAuto
:
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
;
630 OSL_ENSURE( false, "ODbaseTable::ReadMemoHeader: unsupported memo type!" );
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
;
647 static const ::rtl::OUString
s_sSeparator(RTL_CONSTASCII_USTRINGPARAM("/"));
651 sName
= xRow
->getString(1);
652 aURL
.SetSmartProtocol(INET_PROT_FILE
);
653 String sUrl
= _pConnection
->getURL() + s_sSeparator
+ sName
;
654 aURL
.SetSmartURL( sUrl
);
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();
671 xDir
->beforeFirst(); // move back to before first record
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());
692 m_pColumns
->reFill(aVector
);
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))
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();
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
737 m_pIndexes
->reFill(aVector
);
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
);
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))
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;
793 ::osl::MutexGuard
aGuard( ::osl::Mutex::getGlobalMutex() );
796 static ::cppu::OImplementationId 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
;
829 sal_Size nByteOffset
= 1;
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:
841 nLen
= m_aPrecisions
[i
-1];
842 nType
= m_aTypes
[i
-1];
846 (*aIter
)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION
)) >>= nLen
;
847 (*aIter
)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE
)) >>= nType
;
851 case DataType::INTEGER
:
852 case DataType::DOUBLE
:
853 case DataType::TIMESTAMP
:
856 case DataType::LONGVARCHAR
:
857 case DataType::LONGVARBINARY
:
858 nLen
= m_aRealFieldLengths
[i
-1];
860 case DataType::DECIMAL
:
862 nLen
= SvDbaseConverter::ConvertPrecisionToDbase(nLen
,m_aScales
[i
-1]);
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
:
873 // Ist die Variable ueberhaupt gebunden?
874 if ( !(_rRow
->get())[i
]->isBound() )
876 // Nein - naechstes Feld.
878 OSL_ENSURE( nByteOffset
<= m_nBufferSize
,"ByteOffset > m_nBufferSize!");
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
];
892 String
aStr(pData
,(xub_StrLen
)nLen
,m_eEncoding
);
893 aStr
.EraseTrailingChars();
896 *(_rRow
->get())[i
] = ::rtl::OUString(aStr
);
897 else// keine StringLaenge, dann NULL
898 (_rRow
->get())[i
]->setNull();
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();
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
)
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]));
935 d
= (double)(nValue
);
939 memcpy(&d
, pData
, nLen
);
942 *(_rRow
->get())[i
] = d
;
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')
953 String
aStr(pData
, (xub_StrLen
)nLen
,m_eEncoding
); // Spaces am Anfang und am Ende entfernen:
954 aStr
.EraseLeadingChars();
955 aStr
.EraseTrailingChars();
960 (_rRow
->get())[i
]->setNull(); // keine Werte -> fertig
968 if (aStr
.Len() != nLen
)
970 (_rRow
->get())[i
]->setNull();
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
;
981 case DataType::DECIMAL
:
982 *(_rRow
->get())[i
] = ORowSetValue(aStr
);
983 // pVal->setDouble(SdbTools::ToDouble(aStr));
988 switch (* ((const char *)pData
))
992 case 'J': b
= TRUE
; break;
993 default: b
= FALSE
; break;
995 *(_rRow
->get())[i
] = b
;
996 // pVal->setDouble(b);
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()) )
1010 (_rRow
->get())[i
]->setNull();
1013 OSL_ASSERT("Falscher Type");
1015 (_rRow
->get())[i
]->setTypeKind(nType
);
1018 nByteOffset
+= nLen
;
1019 OSL_ENSURE( nByteOffset
<= m_nBufferSize
,"ByteOffset > m_nBufferSize!");
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(
1050 ::dbtools::throwGenericSQLException( sError
, *this );
1054 aURL
.SetSmartProtocol(INET_PROT_FILE
);
1055 String aName
= getEntry(m_pConnection
,m_Name
);
1058 ::rtl::OUString aIdent
= m_pConnection
->getContent()->getIdentifier()->getContentIdentifier();
1059 if ( aIdent
.lastIndexOf('/') != (aIdent
.getLength()-1) )
1060 aIdent
+= ::rtl::OUString::createFromAscii("/");
1062 aName
= aIdent
.getStr();
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());
1085 catch(Exception
&) // a execption is thrown when no file exists
1089 BOOL bMemoFile
= sal_False
;
1091 sal_Bool bOk
= CreateFile(aURL
, bMemoFile
);
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
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
,
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
) );
1148 m_aHeader
.db_typ
= dBaseIIIMemo
;
1151 m_aHeader
.db_typ
= dBaseIII
;
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
1164 catch(const Exception
&)
1168 const ::rtl::OUString
sError( getConnection()->getResources().getResourceStringWithSubstitution(
1170 "$columnname$", _sColumnName
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
);
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
1209 } // switch (getINT32(xCol->getPropertyValue(sPropType)))
1212 catch ( const Exception
& e
)
1218 // we have to drop the file because it is corrupted now
1221 catch(const Exception
&) { }
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!");
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
:
1282 case DataType::DOUBLE
:
1283 if (getBOOL(xCol
->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY
)))) // Currency wird gesondert behandelt
1288 case DataType::INTEGER
:
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
1299 case DataType::TIMESTAMP
:
1302 case DataType::DATE
:
1308 case DataType::LONGVARBINARY
:
1311 case DataType::LONGVARCHAR
:
1316 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE
, aName
);
1320 (*m_pFileStream
) << cTyp
;
1321 if ( nDbaseType
== VisualFoxPro
)
1322 (*m_pFileStream
) << (nRecLength
-1);
1324 m_pFileStream
->Write(aBuffer
, 4);
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
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;
1354 sal_Int32 nPrec
= SvDbaseConverter::ConvertPrecisionToDbase(nPrecision
,nScale
);
1356 (*m_pFileStream
) << (BYTE
)( nPrec
);
1357 (*m_pFileStream
) << (BYTE
)nScale
;
1358 nRecLength
+= (USHORT
)nPrec
;
1362 (*m_pFileStream
) << (BYTE
)1;
1363 (*m_pFileStream
) << (BYTE
)0;
1367 (*m_pFileStream
) << (BYTE
)4;
1368 (*m_pFileStream
) << (BYTE
)0;
1375 (*m_pFileStream
) << (BYTE
)8;
1376 (*m_pFileStream
) << (BYTE
)0;
1381 (*m_pFileStream
) << (BYTE
)10;
1382 (*m_pFileStream
) << (BYTE
)0;
1388 throwInvalidColumnType(STR_INVALID_COLUMN_TYPE
, aName
);
1390 m_pFileStream
->Write(aBuffer
, 14);
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
1401 m_pFileStream
->Seek(0L);
1402 if (nDbaseType
== VisualFoxPro
)
1403 (*m_pFileStream
) << (BYTE
) FoxProMemo
;
1405 (*m_pFileStream
) << (BYTE
) dBaseIIIMemo
;
1406 } // if (bCreateMemo)
1408 catch ( const Exception
& e
)
1414 // we have to drop the file because it is corrupted now
1417 catch(const Exception
&) { }
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
);
1434 char aBuffer
[512]; // write buffer
1435 memset(aBuffer
,0,sizeof(aBuffer
));
1438 m_pMemoStream
->Seek(0L);
1439 for (UINT16 i
= 0; i
< 512; i
++)
1441 (*m_pMemoStream
) << BYTE(0);
1444 m_pMemoStream
->SetFiller('\0');
1445 m_pMemoStream
->SetStreamSize(512);
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
;
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" );
1463 BOOL bDropped
= ::utl::UCBContentHelper::Kill(aURL
.GetMainURL(INetURLObject::NO_DECODE
));
1467 if (_bHasMemoFields
)
1468 { // delete the memo fields
1469 aURL
.setExtension(String::CreateFromAscii("dbt"));
1470 bDropped
= ::utl::UCBContentHelper::Kill(aURL
.GetMainURL(INetURLObject::NO_DECODE
));
1479 sal_Int32 i
= _pIndexes
->getCount();
1482 _pIndexes
->dropByIndex(--i
);
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
) ) );
1501 // silently ignore this ....
1507 // -----------------------------------------------------------------------------
1508 BOOL
ODbaseTable::DropImpl()
1510 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger
, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::DropImpl" );
1514 refreshIndexes(); // look for indexes which must be deleted as well
1516 BOOL bDropped
= Drop_Static(getEntry(m_pConnection
,m_Name
),HasMemoFields(),m_pIndexes
);
1518 {// we couldn't drop the table so we have to reopen it
1521 m_pColumns
->refresh();
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
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
,
1540 m_nFilePos
= (ULONG
)m_aHeader
.db_anz
+ 1;
1541 BOOL bInsertRow
= UpdateBuffer( rRow
, NULL
, _xCols
);
1544 nFileSize
= lcl_getFileSize(*m_pFileStream
);
1546 if (HasMemoFields() && m_pMemoStream
)
1548 m_pMemoStream
->Seek(STREAM_SEEK_TO_END
);
1549 nMemoFileSize
= m_pMemoStream
->Tell();
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
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!
1569 m_pFileStream
->Flush();
1571 // bei Erfolg # erhoehen
1573 *rRow
.get()[0] = m_nFilePos
; // BOOKmark setzen
1574 m_nFilePos
= nTempPos
;
1578 m_nFilePos
= nTempPos
;
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
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
1608 m_pFileStream
->Flush();
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
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
))
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
);
1636 ::cppu::extractInterface(xCol
,m_pColumns
->getByIndex(i
));
1637 OSL_ENSURE(xCol
.is(),"ODbaseTable::DeleteRow column is null!");
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();
1649 for(;aIter
!= _rCols
.get().end();++aIter
,++nPos
)
1651 if(aCase(getString((*aIter
)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME
))),aColName
))
1654 if (aIter
== _rCols
.get().end())
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();
1667 // -------------------------------------------------------------------------
1668 Reference
<XPropertySet
> ODbaseTable::isUniqueByColumnName(sal_Int32 _nColumnPos
)
1670 RTL_LOGFILE_CONTEXT_AUTHOR( aLogger
, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::isUniqueByColumnName" );
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
))
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!");
1709 sal_Int32 nByteOffset
= 1;
1711 // Felder aktualisieren:
1712 Reference
<XPropertySet
> xCol
;
1713 Reference
<XPropertySet
> xIndex
;
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
)
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
))
1740 if (nPos
>= _xCols
->getCount())
1745 xIndex
= isUniqueByColumnName(i
);
1746 aIndexedCols
[i
] = xIndex
;
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
]))
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
;
1769 } // if ( !aColName.getLength() )
1770 const ::rtl::OUString
sError( getConnection()->getResources().getResourceStringWithSubstitution(
1771 STR_DUPLICATE_VALUE_IN_COLUMN
1772 ,"$columnname$", aColName
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!");
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
];
1797 m_pColumns
->getByIndex(i
) >>= xCol
;
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;
1809 case DataType::INTEGER
:
1810 case DataType::DOUBLE
:
1811 case DataType::TIMESTAMP
:
1813 case DataType::LONGVARBINARY
:
1814 case DataType::DATE
:
1816 case DataType::LONGVARCHAR
:
1817 nLen
= m_aRealFieldLengths
[i
];
1819 case DataType::DECIMAL
:
1820 nLen
= SvDbaseConverter::ConvertPrecisionToDbase(nLen
,nScale
);
1821 break; // das Vorzeichen und das Komma
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
))
1840 if (nPos
>= _xCols
->getCount())
1842 nByteOffset
+= nLen
;
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
;
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!");
1864 if (pOrgRow
.isValid() && !rRow
.get()[nPos
]->getValue().isNull() )//&& pVal->isModified())
1865 pIndex
->Update(m_nFilePos
,*(pOrgRow
->get())[nPos
],*rRow
.get()[nPos
]);
1867 pIndex
->Insert(m_nFilePos
,*rRow
.get()[nPos
]);
1870 char* pData
= (char *)(m_pBuffer
+ nByteOffset
);
1871 if (rRow
.get()[nPos
]->getValue().isNull())
1874 memset(pData
,0,nLen
); // Zuruecksetzen auf NULL
1876 memset(pData
,' ',nLen
); // Zuruecksetzen auf NULL
1877 nByteOffset
+= nLen
;
1878 OSL_ENSURE( nByteOffset
<= m_nBufferSize
,"ByteOffset > m_nBufferSize!");
1882 sal_Bool bHadError
= sal_False
;
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);
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());
1902 aDate
= rRow
.get()[nPos
]->getValue();
1911 // Genau 8 Byte kopieren:
1912 strncpy(pData
,s
,sizeof s
- 1);
1914 case DataType::INTEGER
:
1916 sal_Int32 nValue
= rRow
.get()[nPos
]->getValue();
1917 memcpy(pData
,&nValue
,nLen
);
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;
1929 nValue
= (sal_Int64
)(d
* pow(10.0,(int)m_aScales
[i
]));
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
1935 memcpy(pData
,&d
,nLen
);
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
;
1951 strncpy(pData
,aDefaultValue
.GetBuffer(),nLen
);
1952 // write the resulting double back
1953 *rRow
.get()[nPos
] = toDouble(aDefaultValue
);
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
1970 ::dbtools::throwGenericSQLException( sError
, *this );
1974 *pData
= rRow
.get()[nPos
]->getValue().getBool() ? 'T' : 'F';
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
))
1990 ByteString
aBlock(ByteString::CreateFromInt32(nBlockNo
));
1991 aStr
.Expand(static_cast<sal_uInt16
>(nLen
- aBlock
.Len()), '0' );
1993 // Zeichen kopieren:
1994 memset(pData
,' ',nLen
); // Zuruecksetzen auf NULL
1995 memcpy(pData
, aStr
.GetBuffer(), nLen
);
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() );
2013 catch( SQLException
& )
2017 catch ( Exception
& ) { bHadError
= sal_True
; }
2021 m_pColumns
->getByIndex(i
) >>= xCol
;
2022 OSL_ENSURE( xCol
.is(), "ODbaseTable::UpdateBuffer column is null!" );
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
2030 ::dbtools::throwGenericSQLException( sError
, *this );
2033 nByteOffset
+= nLen
;
2034 OSL_ENSURE( nByteOffset
<= m_nBufferSize
,"ByteOffset > m_nBufferSize!");
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
2045 ::rtl::OString aStr
;
2046 ::com::sun::star::uno::Sequence
<sal_Int8
> aValue
;
2048 const bool bBinary
= aVariable
.getTypeKind() == DataType::LONGVARBINARY
&& m_aMemoHeader
.db_typ
== MemoFoxPro
;
2051 aValue
= aVariable
.getSequence();
2052 nSize
= aValue
.getLength();
2056 nSize
= DBTypeConversion::convertUnicodeString( aVariable
.getString(), aStr
, m_eEncoding
);
2059 // Anhaengen oder ueberschreiben
2060 BOOL bAppend
= rBlockNr
== 0;
2064 switch (m_aMemoHeader
.db_typ
)
2066 case MemodBaseIII
: // dBase III-Memofeld, endet mit 2 * Ctrl-Z
2067 bAppend
= nSize
> (512 - 2);
2070 case MemodBaseIV
: // dBase IV-Memofeld mit Laengenangabe
2073 m_pMemoStream
->Seek(rBlockNr
* m_aMemoHeader
.db_size
);
2074 m_pMemoStream
->SeekRel(4L);
2075 m_pMemoStream
->Read(sHeader
,4);
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];
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
;
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
);
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
;
2117 m_pMemoStream
->Write( aStr
.getStr(), aStr
.getLength() );
2118 (*m_pMemoStream
) << cEOF
<< cEOF
;
2121 case MemodBaseIV
: // dBase IV-Memofeld mit Laengenangabe
2123 if ( MemodBaseIV
== m_aMemoHeader
.db_typ
)
2124 (*m_pMemoStream
) << (BYTE
)0xFF
2128 (*m_pMemoStream
) << (BYTE
)0x00
2132 UINT32 nWriteSize
= nSize
;
2133 if (m_aMemoHeader
.db_typ
== MemoFoxPro
)
2136 (*m_pMemoStream
) << (BYTE
) 0x00; // Picture
2138 (*m_pMemoStream
) << (BYTE
) 0x01; // Memo
2139 for (int i
= 4; i
> 0; nWriteSize
>>= 8)
2140 nHeader
[--i
] = (BYTE
) (nWriteSize
% 256);
2144 (*m_pMemoStream
) << (BYTE
) 0x00;
2146 for (int i
= 0; i
< 4; nWriteSize
>>= 8)
2147 nHeader
[i
++] = (BYTE
) (nWriteSize
% 256);
2150 m_pMemoStream
->Write(nHeader
,4);
2152 m_pMemoStream
->Write( aValue
.getConstArray(), aValue
.getLength() );
2154 m_pMemoStream
->Write( aStr
.getStr(), aStr
.getLength() );
2155 m_pMemoStream
->Flush();
2160 // Schreiben der neuen Blocknummer
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();
2174 // -----------------------------------------------------------------------------
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
;
2218 xCopyColumn
= xOldColumn
->createDataDescriptor();
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
2238 Reference
<XPropertySet
> xProp
;
2239 m_pColumns
->getByIndex(i
) >>= xProp
;
2240 Reference
<XDataDescriptorFactory
> xColumn(xProp
,UNO_QUERY
);
2241 Reference
<XPropertySet
> xCpy
;
2243 xCpy
= xColumn
->createDataDescriptor();
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
;
2259 xCpy
= xColumn
->createDataDescriptor();
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
)))
2273 ::dbtools::throwGenericSQLException( sError
, *this );
2276 pNewTable
->construct();
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
2288 ::comphelper::disposeComponent(xHoldTable
);
2297 m_pColumns
->refresh();
2300 catch(const SQLException
&)
2304 catch(const Exception
&)
2306 OSL_ENSURE(0,"ODbaseTable::alterColumn: Exception occured!");
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
);
2332 m_pColumns
->refresh();
2336 void renameFile(OConnection
* _pConenction
,const ::rtl::OUString
& oldName
,
2337 const ::rtl::OUString
& newName
,const String
& _sExtension
)
2339 String aName
= ODbaseTable::getEntry(_pConenction
,oldName
);
2342 ::rtl::OUString aIdent
= _pConenction
->getContent()->getIdentifier()->getContentIdentifier();
2343 if ( aIdent
.lastIndexOf('/') != (aIdent
.getLength()-1) )
2344 aIdent
+= ::rtl::OUString::createFromAscii("/");
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())
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
);
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
;
2411 xCpy
= xColumn
->createDataDescriptor();
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
)))
2432 ::dbtools::throwGenericSQLException( sError
, *this );
2435 BOOL bAlreadyDroped
= FALSE
;
2438 pNewTable
->construct();
2440 copyData(pNewTable
,pNewTable
->m_pColumns
->getCount());
2441 // drop the old table
2444 bAlreadyDroped
= TRUE
;
2445 pNewTable
->renameImpl(m_Name
);
2446 // release the temp file
2448 xHold
= pNewTable
= NULL
;
2453 m_pColumns
->refresh();
2455 catch(const SQLException
&)
2457 // here we know that the old table wasn't droped before
2459 xHold
= pNewTable
= NULL
;
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
)
2481 Reference
<XPropertySet
> xProp
;
2482 m_pColumns
->getByIndex(i
) >>= xProp
;
2483 Reference
<XDataDescriptorFactory
> xColumn(xProp
,UNO_QUERY
);
2484 Reference
<XPropertySet
> xCpy
;
2486 xCpy
= xColumn
->createDataDescriptor();
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
)
2505 ::dbtools::throwGenericSQLException( sError
, *this );
2507 pNewTable
->construct();
2509 copyData(pNewTable
,_nPos
);
2510 // drop the old table
2512 pNewTable
->renameImpl(m_Name
);
2513 // release the temp file
2515 xHold
= pNewTable
= NULL
;
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
);
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);
2538 aURL
.SetSmartProtocol(INET_PROT_FILE
);
2539 aURL
.SetURL(aTempFile
.GetURL());
2541 String
sNewName(aURL
.getName());
2542 sNewName
.Erase(sNewName
.Len() - sExt
.Len());
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
;
2554 aInsertRow
= new OValueRefVector(_pNewTable
->m_pColumns
->getCount());
2555 ::std::for_each(aInsertRow
->get().begin(),aInsertRow
->get().end(),TSetRefBound(sal_True
));
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
;
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
);
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
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
)
2586 (*aInsertIter
)->setValue( (*aIter
)->getValue() );
2591 bOk
= _pNewTable
->InsertRow(*aInsertRow
,sal_True
,_pNewTable
->m_pColumns
);
2592 OSL_ENSURE(bOk
,"Row could not be inserted!");
2595 OSL_ENSURE(bOk
,"Row could not be fetched!");
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" );
2610 const ::rtl::OUString
sError( getConnection()->getResources().getResourceStringWithSubstitution(
2612 "$filename$", getEntry(m_pConnection
,m_Name
)
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 )
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
:
2640 case IResultSetHelper::PRIOR
:
2644 case IResultSetHelper::FIRST
:
2647 case IResultSetHelper::LAST
:
2648 m_nFilePos
= nNumberOfRecords
;
2650 case IResultSetHelper::RELATIVE
:
2651 m_nFilePos
= (((sal_Int32
)m_nFilePos
) + nOffset
< 0) ? 0L
2652 : (sal_uInt32
)(((sal_Int32
)m_nFilePos
) + nOffset
);
2654 case IResultSetHelper::ABSOLUTE
:
2655 case IResultSetHelper::BOOKMARK
:
2656 m_nFilePos
= (sal_uInt32
)nOffset
;
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)
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
)
2676 nLen
= m_pFileStream
->Read((char*)m_pBuffer
, nEntryLen
);
2677 if (m_pFileStream
->GetError() != ERRCODE_NONE
)
2683 switch(eCursorPosition
)
2685 case IResultSetHelper::PRIOR
:
2686 case IResultSetHelper::FIRST
:
2689 case IResultSetHelper::LAST
:
2690 case IResultSetHelper::NEXT
:
2691 case IResultSetHelper::ABSOLUTE
:
2692 case IResultSetHelper::RELATIVE
:
2694 m_nFilePos
= nNumberOfRecords
+ 1;
2695 else if (nOffset
< 0)
2698 case IResultSetHelper::BOOKMARK
:
2699 m_nFilePos
= nTempPos
; // vorherige Position
2701 // aStatus.Set(SDB_STAT_NO_DATA_FOUND);
2705 nCurPos
= m_nFilePos
;
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
;
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);
2731 while (aBuf
[i
] != cEOF
&& ++i
< 512)
2733 bReady
= aBuf
[i
] == cEOF
;
2738 } while (!bReady
&& !m_pMemoStream
->IsEof() && aBStr
.Len() < STRING_MAXLEN
);
2740 ::rtl::OUString
aStr(aBStr
.GetBuffer(), aBStr
.Len(),m_eEncoding
);
2745 case MemodBaseIV
: // dBase IV-Memofeld mit Laengenangabe
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)
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),
2761 // return sal_False;
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),
2778 sal_uInt32
nLength(0);
2779 (*m_pMemoStream
) >> nLength
;
2781 if (m_aMemoHeader
.db_typ
== MemodBaseIV
)
2789 ::rtl::OUStringBuffer aStr
;
2790 while ( nLength
> STRING_MAXLEN
)
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
;
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();
2811 ::com::sun::star::uno::Sequence
< sal_Int8
> aData(nLength
);
2812 m_pMemoStream
->Read(aData
.getArray(),nLength
);
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
)
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
;