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