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