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 {
lcl_getFileSize(SvStream & _rStream)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 */
lcl_CalcJulDate(sal_Int32 & _nJulianDate,sal_Int32 & _nJulianTime,const com::sun::star::util::DateTime _aDateTime)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 */
lcl_CalDate(sal_Int32 _nJulianDate,sal_Int32 _nJulianTime,com::sun::star::util::DateTime & _rDateTime)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 // -------------------------------------------------------------------------
readHeader()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 // -------------------------------------------------------------------------
fillColumns()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 // -------------------------------------------------------------------------
ODbaseTable(sdbcx::OCollection * _pTables,ODbaseConnection * _pConnection)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 // -------------------------------------------------------------------------
ODbaseTable(sdbcx::OCollection * _pTables,ODbaseConnection * _pConnection,const::rtl::OUString & _Name,const::rtl::OUString & _Type,const::rtl::OUString & _Description,const::rtl::OUString & _SchemaName,const::rtl::OUString & _CatalogName)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 // -----------------------------------------------------------------------------
construct()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 //------------------------------------------------------------------
ReadMemoHeader()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 // -------------------------------------------------------------------------
getEntry(OConnection * _pConnection,const::rtl::OUString & _sName)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 // -------------------------------------------------------------------------
refreshColumns()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 // -------------------------------------------------------------------------
refreshIndexes()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 // -------------------------------------------------------------------------
disposing(void)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 // -------------------------------------------------------------------------
getTypes()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 // -------------------------------------------------------------------------
queryInterface(const Type & rType)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 //--------------------------------------------------------------------------
getUnoTunnelImplementationId()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 //------------------------------------------------------------------
getSomething(const Sequence<sal_Int8> & rId)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 //------------------------------------------------------------------
fetchRow(OValueRefRow & _rRow,const OSQLColumns & _rCols,sal_Bool _bUseTableDefs,sal_Bool bRetrieveData)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                 memcpy(&nDate, pData, 4);
902                 memcpy(&nTime, pData+ 4, 4);
903             }
904             if ( !nDate && !nTime )
905             {
906                 (_rRow->get())[i]->setNull();
907             }
908             else
909             {
910                 ::com::sun::star::util::DateTime aDateTime;
911                 lcl_CalDate(nDate,nTime,aDateTime);
912                 *(_rRow->get())[i] = aDateTime;
913             }
914         }
915         else if ( DataType::INTEGER == nType )
916         {
917             OSL_ENSURE(nLen == 4, "Invalid length for integer field");
918             if (nLen >= 4) {
919                 sal_Int32 nValue = 0;
920                 memcpy(&nValue, pData, 4);
921                 *(_rRow->get())[i] = nValue;
922             } else {
923                 (_rRow->get())[i]->setNull();
924             }
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                 if (getBOOL((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency needs special treatment
932                     {
933                         sal_Int64 nValue = 0;
934                         memcpy(&nValue, pData, nLen);
935 
936                         if ( m_aScales[i-1] )
937                             d = (double)(nValue / pow(10.0,(int)m_aScales[i-1]));
938                         else
939                             d = (double)(nValue);
940                     }
941                 else
942                     {
943                         memcpy(&d, pData, nLen);
944                     }
945 
946                 *(_rRow->get())[i] = d;
947             } else {
948                 (_rRow->get())[i]->setNull();
949             }
950         }
951 		else
952 		{
953 			// Change any nulls into spaces
954 			for (sal_Int32 k = 0; k < nLen; k++)
955 			{
956 				if (pData[k] == '\0')
957 					pData[k] = ' ';
958 			}
959 
960 			String aStr(pData, (xub_StrLen)nLen,m_eEncoding);		// Strip spaces from beginning and end
961 			aStr.EraseLeadingChars();
962 			aStr.EraseTrailingChars();
963 
964 			if (!aStr.Len())
965 			{
966 				nByteOffset += nLen;
967 				(_rRow->get())[i]->setNull();	// no value -> we are done
968 				continue;
969 			}
970 
971 			switch (nType)
972 			{
973 				case DataType::DATE:
974 				{
975                     OSL_ENSURE(nLen == 8, "Invalid length for date field");
976 					if ((nLen < 8) || (aStr.Len() != nLen)) {
977 						(_rRow->get())[i]->setNull();
978 						break;
979 					}
980 					const sal_uInt16  nYear   = (sal_uInt16)aStr.Copy( 0, 4 ).ToInt32();
981 					const sal_uInt16  nMonth  = (sal_uInt16)aStr.Copy( 4, 2 ).ToInt32();
982 					const sal_uInt16  nDay    = (sal_uInt16)aStr.Copy( 6, 2 ).ToInt32();
983 
984 					const ::com::sun::star::util::Date aDate(nDay,nMonth,nYear);
985 					*(_rRow->get())[i] = aDate;
986 				}
987 				break;
988 				case DataType::DECIMAL:
989 					*(_rRow->get())[i] = ORowSetValue(aStr);
990 					//	pVal->setDouble(SdbTools::ToDouble(aStr));
991 				break;
992 				case DataType::BIT:
993 				{
994                     OSL_ENSURE(nLen == 1, "Invalid length for bit field");
995                     if (nLen < 1) {
996 						(_rRow->get())[i]->setNull();
997 						break;
998                     }
999 					sal_Bool b;
1000 					switch (* ((const char *)pData))
1001 					{
1002 						case 'T':
1003 						case 'Y':
1004 						case 'J':	b = sal_True; break;
1005 						default: 	b = sal_False; break;
1006 					}
1007 					*(_rRow->get())[i] = b;
1008 					//	pVal->setDouble(b);
1009 				}
1010 				break;
1011                 case DataType::LONGVARBINARY:
1012                 case DataType::BINARY:
1013 				case DataType::LONGVARCHAR:
1014 				{
1015 					const long nBlockNo = aStr.ToInt32();	// Blocknummer lesen
1016 					if (nBlockNo > 0 && m_pMemoStream) // Daten aus Memo-Datei lesen, nur wenn
1017 					{
1018 						if ( !ReadMemo(nBlockNo, (_rRow->get())[i]->get()) )
1019 							break;
1020 					}
1021 					else
1022 						(_rRow->get())[i]->setNull();
1023 				}	break;
1024 				default:
1025 					OSL_ASSERT("Wrong type");
1026 			}
1027 			(_rRow->get())[i]->setTypeKind(nType);
1028 		}
1029 
1030 		nByteOffset += nLen;
1031 		OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1032 	}
1033 	return sal_True;
1034 }
1035 //------------------------------------------------------------------
1036 // -------------------------------------------------------------------------
FileClose()1037 void ODbaseTable::FileClose()
1038 {
1039     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::FileClose" );
1040 	::osl::MutexGuard aGuard(m_aMutex);
1041 	// falls noch nicht alles geschrieben wurde
1042 	if (m_pMemoStream && m_pMemoStream->IsWritable())
1043 		m_pMemoStream->Flush();
1044 
1045 	delete m_pMemoStream;
1046 	m_pMemoStream = NULL;
1047 
1048 	ODbaseTable_BASE::FileClose();
1049 }
1050 // -------------------------------------------------------------------------
CreateImpl()1051 sal_Bool ODbaseTable::CreateImpl()
1052 {
1053     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateImpl" );
1054 	OSL_ENSURE(!m_pFileStream, "SequenceError");
1055 
1056 	if ( m_pConnection->isCheckEnabled() && ::dbtools::convertName2SQLName(m_Name,::rtl::OUString()) != m_Name )
1057 	{
1058         const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1059                 STR_SQL_NAME_ERROR,
1060                 "$name$", m_Name
1061              ) );
1062         ::dbtools::throwGenericSQLException( sError, *this );
1063 	}
1064 
1065 	INetURLObject aURL;
1066 	aURL.SetSmartProtocol(INET_PROT_FILE);
1067 	String aName = getEntry(m_pConnection,m_Name);
1068 	if(!aName.Len())
1069 	{
1070 		::rtl::OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
1071 		if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
1072 			aIdent += ::rtl::OUString::createFromAscii("/");
1073 		aIdent += m_Name;
1074 		aName = aIdent.getStr();
1075 	}
1076 	aURL.SetURL(aName);
1077 
1078 	if ( !m_pConnection->matchesExtension( aURL.getExtension() ) )
1079 		aURL.setExtension(m_pConnection->getExtension());
1080 
1081 	try
1082 	{
1083 		Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1084 		if (aContent.isDocument())
1085 		{
1086 			// Hack fuer Bug #30609 , nur wenn das File existiert und die Laenge > 0 gibt es einen Fehler
1087 			SvStream* pFileStream = createStream_simpleError( aURL.GetMainURL(INetURLObject::NO_DECODE),STREAM_READ);
1088 
1089 			if (pFileStream && pFileStream->Seek(STREAM_SEEK_TO_END))
1090 			{
1091 				//	aStatus.SetError(ERRCODE_IO_ALREADYEXISTS,TABLE,aFile.GetFull());
1092 				return sal_False;
1093 			}
1094 			delete pFileStream;
1095 		}
1096 	}
1097 	catch(Exception&) // a execption is thrown when no file exists
1098 	{
1099 	}
1100 
1101 	sal_Bool bMemoFile = sal_False;
1102 
1103 	sal_Bool bOk = CreateFile(aURL, bMemoFile);
1104 
1105 	FileClose();
1106 
1107 	if (!bOk)
1108 	{
1109 		try
1110 		{
1111 			Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1112 			aContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1113 		}
1114 		catch(Exception&) // a execption is thrown when no file exists
1115 		{
1116 		}
1117 		return sal_False;
1118 	}
1119 
1120 	if (bMemoFile)
1121 	{
1122 		String aExt = aURL.getExtension();
1123 		aURL.setExtension(String::CreateFromAscii("dbt"));                      // extension for memo file
1124 		Content aMemo1Content(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1125 
1126 		sal_Bool bMemoAlreadyExists = sal_False;
1127 		try
1128 		{
1129 			bMemoAlreadyExists = aMemo1Content.isDocument();
1130 		}
1131 		catch(Exception&) // a execption is thrown when no file exists
1132 		{
1133 		}
1134 		if (bMemoAlreadyExists)
1135 		{
1136 			//	aStatus.SetError(ERRCODE_IO_ALREADYEXISTS,MEMO,aFile.GetFull());
1137 			aURL.setExtension(aExt);      // kill dbf file
1138 			try
1139 			{
1140 				Content aMemoContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1141 				aMemoContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1142 			}
1143 			catch(const Exception&)
1144 			{
1145 
1146                 const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1147                         STR_COULD_NOT_DELETE_FILE,
1148                         "$name$", aName
1149                      ) );
1150                 ::dbtools::throwGenericSQLException( sError, *this );
1151 			}
1152 		}
1153 		if (!CreateMemoFile(aURL))
1154 		{
1155 			aURL.setExtension(aExt);      // kill dbf file
1156 			Content aMemoContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
1157 			aMemoContent.executeCommand( rtl::OUString::createFromAscii( "delete" ),bool2any( sal_True ) );
1158 			return sal_False;
1159 		}
1160 		m_aHeader.db_typ = dBaseIIIMemo;
1161 	}
1162 	else
1163 		m_aHeader.db_typ = dBaseIII;
1164 
1165 	return sal_True;
1166 }
1167 // -----------------------------------------------------------------------------
throwInvalidColumnType(const sal_uInt16 _nErrorId,const::rtl::OUString & _sColumnName)1168 void ODbaseTable::throwInvalidColumnType(const sal_uInt16 _nErrorId,const ::rtl::OUString& _sColumnName)
1169 {
1170     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::throwInvalidColumnType" );
1171 	try
1172 	{
1173 		// we have to drop the file because it is corrupted now
1174 		DropImpl();
1175 	}
1176 	catch(const Exception&)
1177 	{
1178 	}
1179 
1180     const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1181             _nErrorId,
1182             "$columnname$", _sColumnName
1183          ) );
1184     ::dbtools::throwGenericSQLException( sError, *this );
1185 }
1186 //------------------------------------------------------------------
1187 // erzeugt grundsaetzlich dBase IV Datei Format
CreateFile(const INetURLObject & aFile,sal_Bool & bCreateMemo)1188 sal_Bool ODbaseTable::CreateFile(const INetURLObject& aFile, sal_Bool& bCreateMemo)
1189 {
1190     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateFile" );
1191 	bCreateMemo = sal_False;
1192 	Date aDate;                                     // aktuelles Datum
1193 
1194 	m_pFileStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::NO_DECODE),STREAM_READWRITE | STREAM_SHARE_DENYWRITE | STREAM_TRUNC );
1195 
1196 	if (!m_pFileStream)
1197 		return sal_False;
1198 
1199     sal_uInt8 nDbaseType = dBaseIII;
1200     Reference<XIndexAccess> xColumns(getColumns(),UNO_QUERY);
1201 	Reference<XPropertySet> xCol;
1202     const ::rtl::OUString sPropType = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE);
1203 
1204     try
1205 	{
1206         const sal_Int32 nCount = xColumns->getCount();
1207 		for(sal_Int32 i=0;i<nCount;++i)
1208 		{
1209 			xColumns->getByIndex(i) >>= xCol;
1210 			OSL_ENSURE(xCol.is(),"This should be a column!");
1211 
1212 			switch (getINT32(xCol->getPropertyValue(sPropType)))
1213 			{
1214                 case DataType::DOUBLE:
1215                 case DataType::INTEGER:
1216                 case DataType::TIMESTAMP:
1217                 case DataType::LONGVARBINARY:
1218                     nDbaseType = VisualFoxPro;
1219                     i = nCount; // no more columns need to be checked
1220                     break;
1221             } // switch (getINT32(xCol->getPropertyValue(sPropType)))
1222         }
1223     }
1224     catch ( const Exception& e )
1225 	{
1226         (void)e;
1227 
1228 		try
1229 		{
1230 			// we have to drop the file because it is corrupted now
1231 			DropImpl();
1232 		}
1233 		catch(const Exception&) { }
1234 		throw;
1235 	}
1236 
1237 	char aBuffer[21];               // write buffer
1238 	memset(aBuffer,0,sizeof(aBuffer));
1239 
1240 	m_pFileStream->Seek(0L);
1241 	(*m_pFileStream) << (sal_uInt8) nDbaseType;                              // dBase format
1242 	(*m_pFileStream) << (sal_uInt8) (aDate.GetYear() % 100);                 // aktuelles Datum
1243 
1244 
1245 	(*m_pFileStream) << (sal_uInt8) aDate.GetMonth();
1246 	(*m_pFileStream) << (sal_uInt8) aDate.GetDay();
1247     (*m_pFileStream) << 0L;                                             // Anzahl der Datensaetze
1248 	(*m_pFileStream) << (sal_uInt16)((m_pColumns->getCount()+1) * 32 + 1);  // Kopfinformationen,
1249                                                                         // pColumns erhaelt immer eine Spalte mehr
1250     (*m_pFileStream) << (sal_uInt16) 0;                                     // Satzlaenge wird spaeter bestimmt
1251 	m_pFileStream->Write(aBuffer, 20);
1252 
1253     sal_uInt16 nRecLength = 1;                                              // Laenge 1 fuer deleted flag
1254 	sal_Int32  nMaxFieldLength = m_pConnection->getMetaData()->getMaxColumnNameLength();
1255 	::rtl::OUString aName;
1256     const ::rtl::OUString sPropName = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME);
1257     const ::rtl::OUString sPropPrec = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION);
1258     const ::rtl::OUString sPropScale = OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE);
1259 
1260 	try
1261 	{
1262 		const sal_Int32 nCount = xColumns->getCount();
1263 		for(sal_Int32 i=0;i<nCount;++i)
1264 		{
1265 			xColumns->getByIndex(i) >>= xCol;
1266 			OSL_ENSURE(xCol.is(),"This should be a column!");
1267 
1268             char cTyp( 'C' );
1269 
1270 			xCol->getPropertyValue(sPropName) >>= aName;
1271 
1272 			::rtl::OString aCol;
1273 			if ( DBTypeConversion::convertUnicodeString( aName, aCol, m_eEncoding ) > nMaxFieldLength)
1274 			{
1275                 throwInvalidColumnType( STR_INVALID_COLUMN_NAME_LENGTH, aName );
1276 			}
1277 
1278 			(*m_pFileStream) << aCol.getStr();
1279 			m_pFileStream->Write(aBuffer, 11 - aCol.getLength());
1280 
1281             sal_Int32 nPrecision = 0;
1282 			xCol->getPropertyValue(sPropPrec) >>= nPrecision;
1283 			sal_Int32 nScale = 0;
1284 			xCol->getPropertyValue(sPropScale) >>= nScale;
1285 
1286             bool bBinary = false;
1287 
1288 			switch (getINT32(xCol->getPropertyValue(sPropType)))
1289 			{
1290 				case DataType::CHAR:
1291 				case DataType::VARCHAR:
1292 					cTyp = 'C';
1293 					break;
1294                 case DataType::DOUBLE:
1295                     if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1296                         cTyp = 'Y';
1297                     else
1298                         cTyp = 'B';
1299 					break;
1300                 case DataType::INTEGER:
1301                     cTyp = 'I';
1302 				    break;
1303 				case DataType::TINYINT:
1304 				case DataType::SMALLINT:
1305 				case DataType::BIGINT:
1306 				case DataType::DECIMAL:
1307 				case DataType::NUMERIC:
1308 				case DataType::REAL:
1309 					cTyp = 'N';                             // nur dBase 3 format
1310 					break;
1311                 case DataType::TIMESTAMP:
1312                     cTyp = 'T';
1313 				    break;
1314 				case DataType::DATE:
1315 					cTyp = 'D';
1316 					break;
1317 				case DataType::BIT:
1318 					cTyp = 'L';
1319 					break;
1320 				case DataType::LONGVARBINARY:
1321                     bBinary = true;
1322                     // run through
1323 				case DataType::LONGVARCHAR:
1324 					cTyp = 'M';
1325 					break;
1326 				default:
1327 					{
1328 						throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1329 					}
1330 			}
1331 
1332 			(*m_pFileStream) << cTyp;
1333             if ( nDbaseType == VisualFoxPro )
1334                 (*m_pFileStream) << (nRecLength-1);
1335             else
1336 			    m_pFileStream->Write(aBuffer, 4);
1337 
1338 			switch(cTyp)
1339 			{
1340 				case 'C':
1341 					OSL_ENSURE(nPrecision < 255, "ODbaseTable::Create: Column zu lang!");
1342 					if (nPrecision > 254)
1343 					{
1344 						throwInvalidColumnType(STR_INVALID_COLUMN_PRECISION, aName);
1345 					}
1346 					(*m_pFileStream) << (sal_uInt8) Min((sal_uIntPtr)nPrecision, 255UL);      //Feldlaenge
1347                     nRecLength = nRecLength + (sal_uInt16)::std::min((sal_uInt16)nPrecision, (sal_uInt16)255UL);
1348 					(*m_pFileStream) << (sal_uInt8)0;                                                                //Nachkommastellen
1349 					break;
1350 				case 'F':
1351 				case 'N':
1352 					OSL_ENSURE(nPrecision >=  nScale,
1353 							"ODbaseTable::Create: Feldlaenge muss groesser Nachkommastellen sein!");
1354 					if (nPrecision <  nScale)
1355 					{
1356 						throwInvalidColumnType(STR_INVALID_PRECISION_SCALE, aName);
1357 					}
1358 					if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1359 					{
1360 						(*m_pFileStream) << (sal_uInt8)10;          // Standard Laenge
1361 						(*m_pFileStream) << (sal_uInt8)4;
1362 						nRecLength += 10;
1363 					}
1364 					else
1365 					{
1366 						sal_Int32 nPrec = SvDbaseConverter::ConvertPrecisionToDbase(nPrecision,nScale);
1367 
1368 						(*m_pFileStream) << (sal_uInt8)( nPrec);
1369 						(*m_pFileStream) << (sal_uInt8)nScale;
1370                         nRecLength += (sal_uInt16)nPrec;
1371 					}
1372 					break;
1373 				case 'L':
1374 					(*m_pFileStream) << (sal_uInt8)1;
1375 					(*m_pFileStream) << (sal_uInt8)0;
1376 					++nRecLength;
1377 					break;
1378                 case 'I':
1379 					(*m_pFileStream) << (sal_uInt8)4;
1380 					(*m_pFileStream) << (sal_uInt8)0;
1381 					nRecLength += 4;
1382 					break;
1383                 case 'Y':
1384                 case 'B':
1385                 case 'T':
1386 				case 'D':
1387 					(*m_pFileStream) << (sal_uInt8)8;
1388 					(*m_pFileStream) << (sal_uInt8)0;
1389 					nRecLength += 8;
1390 					break;
1391 				case 'M':
1392 					bCreateMemo = sal_True;
1393 					(*m_pFileStream) << (sal_uInt8)10;
1394 					(*m_pFileStream) << (sal_uInt8)0;
1395 					nRecLength += 10;
1396                     if ( bBinary )
1397                         aBuffer[0] = 0x06;
1398 					break;
1399 				default:
1400                     throwInvalidColumnType(STR_INVALID_COLUMN_TYPE, aName);
1401 			}
1402 			m_pFileStream->Write(aBuffer, 14);
1403             aBuffer[0] = 0x00;
1404 		}
1405 
1406 		(*m_pFileStream) << (sal_uInt8)FIELD_DESCRIPTOR_TERMINATOR;              // kopf ende
1407         (*m_pFileStream) << (char)DBF_EOL;
1408 		m_pFileStream->Seek(10L);
1409 		(*m_pFileStream) << nRecLength;                                     // Satzlaenge nachtraeglich eintragen
1410 
1411 		if (bCreateMemo)
1412 		{
1413 			m_pFileStream->Seek(0L);
1414             if (nDbaseType == VisualFoxPro)
1415                 (*m_pFileStream) << (sal_uInt8) FoxProMemo;
1416             else
1417                 (*m_pFileStream) << (sal_uInt8) dBaseIIIMemo;
1418 		} // if (bCreateMemo)
1419 	}
1420 	catch ( const Exception& e )
1421 	{
1422         (void)e;
1423 
1424 		try
1425 		{
1426 			// we have to drop the file because it is corrupted now
1427 			DropImpl();
1428 		}
1429 		catch(const Exception&) { }
1430 		throw;
1431 	}
1432 	return sal_True;
1433 }
1434 
1435 //------------------------------------------------------------------
1436 // erzeugt grundsaetzlich dBase III Datei Format
CreateMemoFile(const INetURLObject & aFile)1437 sal_Bool ODbaseTable::CreateMemoFile(const INetURLObject& aFile)
1438 {
1439     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::CreateMemoFile" );
1440     // Makro zum Filehandling fuers Erzeugen von Tabellen
1441 	m_pMemoStream = createStream_simpleError( aFile.GetMainURL(INetURLObject::NO_DECODE),STREAM_READWRITE | STREAM_SHARE_DENYWRITE);
1442 
1443 	if (!m_pMemoStream)
1444 		return sal_False;
1445 
1446 	char aBuffer[512];              // write buffer
1447 	memset(aBuffer,0,sizeof(aBuffer));
1448 
1449 	m_pMemoStream->SetFiller('\0');
1450 	m_pMemoStream->SetStreamSize(512);
1451 
1452 	m_pMemoStream->Seek(0L);
1453 	(*m_pMemoStream) << long(1);                  // Zeiger auf ersten freien Block
1454 
1455 	m_pMemoStream->Flush();
1456 	delete m_pMemoStream;
1457 	m_pMemoStream = NULL;
1458 	return sal_True;
1459 }
1460 //------------------------------------------------------------------
Drop_Static(const::rtl::OUString & _sUrl,sal_Bool _bHasMemoFields,OCollection * _pIndexes)1461 sal_Bool ODbaseTable::Drop_Static(const ::rtl::OUString& _sUrl,sal_Bool _bHasMemoFields,OCollection* _pIndexes )
1462 {
1463     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::Drop_Static" );
1464 	INetURLObject aURL;
1465 	aURL.SetURL(_sUrl);
1466 
1467 	sal_Bool bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
1468 
1469 	if(bDropped)
1470 	{
1471 		if (_bHasMemoFields)
1472 		{  // delete the memo fields
1473 			aURL.setExtension(String::CreateFromAscii("dbt"));
1474 			bDropped = ::utl::UCBContentHelper::Kill(aURL.GetMainURL(INetURLObject::NO_DECODE));
1475 		}
1476 
1477 		if(bDropped)
1478 		{
1479 			if(_pIndexes)
1480 			{
1481 				try
1482 				{
1483 					sal_Int32 i = _pIndexes->getCount();
1484 					while (i)
1485 					{
1486 						_pIndexes->dropByIndex(--i);
1487 					}
1488 				}
1489 				catch(SQLException)
1490 				{
1491 				}
1492 			}
1493 			//	aFile.SetBase(m_Name);
1494 			aURL.setExtension(String::CreateFromAscii("inf"));
1495 
1496 			// as the inf file does not necessarily exist, we aren't allowed to use UCBContentHelper::Kill
1497 			// 89711 - 16.07.2001 - frank.schoenheit@sun.com
1498 			try
1499 			{
1500 				::ucbhelper::Content aDeleteContent( aURL.GetMainURL( INetURLObject::NO_DECODE ), Reference< XCommandEnvironment > () );
1501 				aDeleteContent.executeCommand( ::rtl::OUString::createFromAscii( "delete" ), makeAny( sal_Bool( sal_True ) ) );
1502 			}
1503 			catch(Exception&)
1504 			{
1505 				// silently ignore this ....
1506 			}
1507 		}
1508 	}
1509 	return bDropped;
1510 }
1511 // -----------------------------------------------------------------------------
DropImpl()1512 sal_Bool ODbaseTable::DropImpl()
1513 {
1514     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::DropImpl" );
1515 	FileClose();
1516 
1517 	if(!m_pIndexes)
1518 		refreshIndexes(); // look for indexes which must be deleted as well
1519 
1520 	sal_Bool bDropped = Drop_Static(getEntry(m_pConnection,m_Name),HasMemoFields(),m_pIndexes);
1521 	if(!bDropped)
1522 	{// we couldn't drop the table so we have to reopen it
1523 		construct();
1524 		if(m_pColumns)
1525 			m_pColumns->refresh();
1526 	}
1527 	return bDropped;
1528 }
1529 
1530 //------------------------------------------------------------------
InsertRow(OValueRefVector & rRow,sal_Bool bFlush,const Reference<XIndexAccess> & _xCols)1531 sal_Bool ODbaseTable::InsertRow(OValueRefVector& rRow, sal_Bool bFlush,const Reference<XIndexAccess>& _xCols)
1532 {
1533     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::InsertRow" );
1534     // Buffer mit Leerzeichen fuellen
1535 	AllocBuffer();
1536 	memset(m_pBuffer, 0, m_aHeader.db_slng);
1537     m_pBuffer[0] = ' ';
1538 
1539 	// Gesamte neue Row uebernehmen:
1540 	// ... und am Ende als neuen Record hinzufuegen:
1541 	sal_uInt32 nTempPos = m_nFilePos,
1542 		   nFileSize = 0,
1543 		   nMemoFileSize = 0;
1544 
1545 	m_nFilePos = (sal_uIntPtr)m_aHeader.db_anz + 1;
1546     sal_Bool bInsertRow = UpdateBuffer( rRow, NULL, _xCols );
1547 	if ( bInsertRow )
1548 	{
1549 		nFileSize = lcl_getFileSize(*m_pFileStream);
1550 
1551 		if (HasMemoFields() && m_pMemoStream)
1552 		{
1553 			m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1554 			nMemoFileSize = m_pMemoStream->Tell();
1555 		}
1556 
1557 		if (!WriteBuffer())
1558 		{
1559             m_pFileStream->SetStreamSize(nFileSize);                // alte Groesse restaurieren
1560 
1561 			if (HasMemoFields() && m_pMemoStream)
1562                 m_pMemoStream->SetStreamSize(nMemoFileSize);    // alte Groesse restaurieren
1563 			m_nFilePos = nTempPos;								// Fileposition restaurieren
1564 		}
1565 		else
1566 		{
1567             (*m_pFileStream) << (char)DBF_EOL; // write EOL
1568 			// Anzahl Datensaetze im Header erhoehen:
1569 			m_pFileStream->Seek( 4L );
1570 			(*m_pFileStream) << (m_aHeader.db_anz + 1);
1571 
1572 			// beim AppendOnly kein Flush!
1573 			if (bFlush)
1574 				m_pFileStream->Flush();
1575 
1576             // bei Erfolg # erhoehen
1577 			m_aHeader.db_anz++;
1578 			*rRow.get()[0] = m_nFilePos;							    // BOOKmark setzen
1579 			m_nFilePos = nTempPos;
1580 		}
1581 	}
1582 	else
1583 		m_nFilePos = nTempPos;
1584 
1585 	return bInsertRow;
1586 }
1587 
1588 //------------------------------------------------------------------
UpdateRow(OValueRefVector & rRow,OValueRefRow & pOrgRow,const Reference<XIndexAccess> & _xCols)1589 sal_Bool ODbaseTable::UpdateRow(OValueRefVector& rRow, OValueRefRow& pOrgRow,const Reference<XIndexAccess>& _xCols)
1590 {
1591     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::UpdateRow" );
1592     // Buffer mit Leerzeichen fuellen
1593 	AllocBuffer();
1594 
1595 	// Auf gewuenschten Record positionieren:
1596 	long nPos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
1597 	m_pFileStream->Seek(nPos);
1598 	m_pFileStream->Read((char*)m_pBuffer, m_aHeader.db_slng);
1599 
1600 	sal_uInt32 nMemoFileSize( 0 );
1601 	if (HasMemoFields() && m_pMemoStream)
1602 	{
1603 		m_pMemoStream->Seek(STREAM_SEEK_TO_END);
1604 		nMemoFileSize = m_pMemoStream->Tell();
1605 	}
1606 	if (!UpdateBuffer(rRow, pOrgRow,_xCols) || !WriteBuffer())
1607 	{
1608 		if (HasMemoFields() && m_pMemoStream)
1609             m_pMemoStream->SetStreamSize(nMemoFileSize);    // alte Groesse restaurieren
1610 	}
1611 	else
1612 	{
1613 		m_pFileStream->Flush();
1614 	}
1615 	return sal_True;
1616 }
1617 
1618 //------------------------------------------------------------------
DeleteRow(const OSQLColumns & _rCols)1619 sal_Bool ODbaseTable::DeleteRow(const OSQLColumns& _rCols)
1620 {
1621     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::DeleteRow" );
1622 	// Einfach das Loesch-Flag setzen (egal, ob es schon gesetzt war
1623 	// oder nicht):
1624 	// Auf gewuenschten Record positionieren:
1625 	long nFilePos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
1626 	m_pFileStream->Seek(nFilePos);
1627 
1628 	OValueRefRow aRow = new OValueRefVector(_rCols.get().size());
1629 
1630 	if (!fetchRow(aRow,_rCols,sal_True,sal_True))
1631 		return sal_False;
1632 
1633 	Reference<XPropertySet> xCol;
1634 	::rtl::OUString aColName;
1635 	::comphelper::UStringMixEqual aCase(isCaseSensitive());
1636 	for (sal_uInt16 i = 0; i < m_pColumns->getCount(); i++)
1637 	{
1638 		Reference<XPropertySet> xIndex = isUniqueByColumnName(i);
1639 		if (xIndex.is())
1640 		{
1641 			::cppu::extractInterface(xCol,m_pColumns->getByIndex(i));
1642 			OSL_ENSURE(xCol.is(),"ODbaseTable::DeleteRow column is null!");
1643 			if(xCol.is())
1644 			{
1645 				xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1646 
1647 				Reference<XUnoTunnel> xTunnel(xIndex,UNO_QUERY);
1648 				OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1649 				ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1650 				OSL_ENSURE(pIndex,"ODbaseTable::DeleteRow: No Index returned!");
1651 
1652 				OSQLColumns::Vector::const_iterator aIter = _rCols.get().begin();
1653 				sal_Int32 nPos = 1;
1654 				for(;aIter != _rCols.get().end();++aIter,++nPos)
1655 				{
1656 					if(aCase(getString((*aIter)->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REALNAME))),aColName))
1657 						break;
1658 				}
1659 				if (aIter == _rCols.get().end())
1660 					continue;
1661 
1662 				pIndex->Delete(m_nFilePos,*(aRow->get())[nPos]);
1663 			}
1664 		}
1665 	}
1666 
1667 	m_pFileStream->Seek(nFilePos);
1668 	(*m_pFileStream) << (sal_uInt8)'*'; // mark the row in the table as deleted
1669 	m_pFileStream->Flush();
1670 	return sal_True;
1671 }
1672 // -------------------------------------------------------------------------
isUniqueByColumnName(sal_Int32 _nColumnPos)1673 Reference<XPropertySet> ODbaseTable::isUniqueByColumnName(sal_Int32 _nColumnPos)
1674 {
1675     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::isUniqueByColumnName" );
1676 	if(!m_pIndexes)
1677 		refreshIndexes();
1678 	if(m_pIndexes->hasElements())
1679 	{
1680 		Reference<XPropertySet> xCol;
1681 		m_pColumns->getByIndex(_nColumnPos) >>= xCol;
1682 		OSL_ENSURE(xCol.is(),"ODbaseTable::isUniqueByColumnName column is null!");
1683 		::rtl::OUString sColName;
1684 		xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sColName;
1685 
1686 		Reference<XPropertySet> xIndex;
1687 		for(sal_Int32 i=0;i<m_pIndexes->getCount();++i)
1688 		{
1689 			::cppu::extractInterface(xIndex,m_pIndexes->getByIndex(i));
1690 			if(xIndex.is() && getBOOL(xIndex->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISUNIQUE))))
1691 			{
1692 				Reference<XNameAccess> xCols(Reference<XColumnsSupplier>(xIndex,UNO_QUERY)->getColumns());
1693 				if(xCols->hasByName(sColName))
1694 					return xIndex;
1695 
1696 			}
1697 		}
1698 	}
1699 	return Reference<XPropertySet>();
1700 }
1701 //------------------------------------------------------------------
toDouble(const ByteString & rString)1702 double toDouble(const ByteString& rString)
1703 {
1704     return ::rtl::math::stringToDouble( rString, '.', ',', NULL, NULL );
1705 }
1706 
1707 //------------------------------------------------------------------
UpdateBuffer(OValueRefVector & rRow,OValueRefRow pOrgRow,const Reference<XIndexAccess> & _xCols)1708 sal_Bool ODbaseTable::UpdateBuffer(OValueRefVector& rRow, OValueRefRow pOrgRow,const Reference<XIndexAccess>& _xCols)
1709 {
1710     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::UpdateBuffer" );
1711 	OSL_ENSURE(m_pBuffer,"Buffer is NULL!");
1712 	if ( !m_pBuffer )
1713 		return sal_False;
1714 	sal_Int32 nByteOffset  = 1;
1715 
1716 	// Felder aktualisieren:
1717 	Reference<XPropertySet> xCol;
1718 	Reference<XPropertySet> xIndex;
1719 	sal_uInt16 i;
1720 	::rtl::OUString aColName;
1721 	const sal_Int32 nColumnCount = m_pColumns->getCount();
1722 	::std::vector< Reference<XPropertySet> > aIndexedCols(nColumnCount);
1723 
1724 	::comphelper::UStringMixEqual aCase(isCaseSensitive());
1725 
1726 	Reference<XIndexAccess> xColumns = m_pColumns;
1727 	// first search a key that exist already in the table
1728 	for (i = 0; i < nColumnCount; ++i)
1729 	{
1730 		sal_Int32 nPos = i;
1731 		if(_xCols != xColumns)
1732 		{
1733 			m_pColumns->getByIndex(i) >>= xCol;
1734 			OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1735 			xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1736 
1737 			for(nPos = 0;nPos<_xCols->getCount();++nPos)
1738 			{
1739 				Reference<XPropertySet> xFindCol;
1740 				::cppu::extractInterface(xFindCol,_xCols->getByIndex(nPos));
1741 				OSL_ENSURE(xFindCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1742 				if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1743 					break;
1744 			}
1745 			if (nPos >= _xCols->getCount())
1746 				continue;
1747 		}
1748 
1749 		++nPos;
1750 		xIndex = isUniqueByColumnName(i);
1751 		aIndexedCols[i] = xIndex;
1752 		if (xIndex.is())
1753 		{
1754 			// first check if the value is different to the old one and when if it conform to the index
1755 			if(pOrgRow.isValid() && (rRow.get()[nPos]->getValue().isNull() || rRow.get()[nPos] == (pOrgRow->get())[nPos]))
1756 				continue;
1757 			else
1758 			{
1759 				//	ODbVariantRef xVar = (pVal == NULL) ? new ODbVariant() : pVal;
1760 				Reference<XUnoTunnel> xTunnel(xIndex,UNO_QUERY);
1761 				OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1762 				ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1763 				OSL_ENSURE(pIndex,"ODbaseTable::UpdateBuffer: No Index returned!");
1764 
1765 				if (pIndex->Find(0,*rRow.get()[nPos]))
1766 				{
1767 					// es existiert kein eindeutiger Wert
1768 					if ( !aColName.getLength() )
1769 					{
1770 						m_pColumns->getByIndex(i) >>= xCol;
1771 						OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1772 						xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1773 						xCol.clear();
1774 					} // if ( !aColName.getLength() )
1775                     const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1776                             STR_DUPLICATE_VALUE_IN_COLUMN
1777                             ,"$columnname$", aColName
1778                          ) );
1779                     ::dbtools::throwGenericSQLException( sError, *this );
1780 				}
1781 			}
1782 		}
1783 	}
1784 
1785 	// when we are here there is no double key in the table
1786 
1787 	for (i = 0; i < nColumnCount && nByteOffset <= m_nBufferSize ; ++i)
1788 	{
1789 		// Laengen je nach Datentyp:
1790 		OSL_ENSURE(i < m_aPrecisions.size(),"Illegal index!");
1791 		sal_Int32 nLen = 0;
1792 		sal_Int32 nType = 0;
1793 		sal_Int32 nScale = 0;
1794 		if ( i < m_aPrecisions.size() )
1795 		{
1796 			nLen	= m_aPrecisions[i];
1797 			nType	= m_aTypes[i];
1798 			nScale	= m_aScales[i];
1799 		}
1800 		else
1801 		{
1802 			m_pColumns->getByIndex(i) >>= xCol;
1803 			if ( xCol.is() )
1804 			{
1805 				xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PRECISION))	>>= nLen;
1806 				xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE))		>>= nType;
1807 				xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_SCALE))		>>= nScale;
1808 			}
1809 		}
1810 
1811         bool bSetZero = false;
1812 		switch (nType)
1813 		{
1814             case DataType::INTEGER:
1815             case DataType::DOUBLE:
1816             case DataType::TIMESTAMP:
1817                 bSetZero = true;
1818             case DataType::LONGVARBINARY:
1819 			case DataType::DATE:
1820             case DataType::BIT:
1821 			case DataType::LONGVARCHAR:
1822                 nLen = m_aRealFieldLengths[i];
1823                 break;
1824 			case DataType::DECIMAL:
1825 				nLen = SvDbaseConverter::ConvertPrecisionToDbase(nLen,nScale);
1826 				break;	// das Vorzeichen und das Komma
1827 			default:
1828                 break;
1829 
1830 		} // switch (nType)
1831 
1832 		sal_Int32 nPos = i;
1833 		if(_xCols != xColumns)
1834 		{
1835 			m_pColumns->getByIndex(i) >>= xCol;
1836 			OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1837 			xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1838 			for(nPos = 0;nPos<_xCols->getCount();++nPos)
1839 			{
1840 				Reference<XPropertySet> xFindCol;
1841 				::cppu::extractInterface(xFindCol,_xCols->getByIndex(nPos));
1842 				if(aCase(getString(xFindCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),aColName))
1843 					break;
1844 			}
1845 			if (nPos >= _xCols->getCount())
1846 			{
1847 				nByteOffset += nLen;
1848 				continue;
1849 			}
1850 		}
1851 
1852 
1853 
1854 		++nPos; // the row values start at 1
1855 		// Ist die Variable ueberhaupt gebunden?
1856 		if ( !rRow.get()[nPos]->isBound() )
1857 		{
1858 			// Nein - naechstes Feld.
1859 			nByteOffset += nLen;
1860 			continue;
1861 		}
1862 		if (aIndexedCols[i].is())
1863 		{
1864 			Reference<XUnoTunnel> xTunnel(aIndexedCols[i],UNO_QUERY);
1865 			OSL_ENSURE(xTunnel.is(),"No TunnelImplementation!");
1866 			ODbaseIndex* pIndex = reinterpret_cast< ODbaseIndex* >( xTunnel->getSomething(ODbaseIndex::getUnoTunnelImplementationId()) );
1867 			OSL_ENSURE(pIndex,"ODbaseTable::UpdateBuffer: No Index returned!");
1868 			// Update !!
1869 			if (pOrgRow.isValid() && !rRow.get()[nPos]->getValue().isNull() )//&& pVal->isModified())
1870 				pIndex->Update(m_nFilePos,*(pOrgRow->get())[nPos],*rRow.get()[nPos]);
1871 			else
1872 				pIndex->Insert(m_nFilePos,*rRow.get()[nPos]);
1873 		}
1874 
1875 		char* pData = (char *)(m_pBuffer + nByteOffset);
1876 		if (rRow.get()[nPos]->getValue().isNull())
1877 		{
1878             if ( bSetZero )
1879                 memset(pData,0,nLen);	// Zuruecksetzen auf NULL
1880             else
1881 			    memset(pData,' ',nLen);	// Zuruecksetzen auf NULL
1882 			nByteOffset += nLen;
1883 			OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
1884 			continue;
1885 		}
1886 
1887         sal_Bool bHadError = sal_False;
1888 		try
1889 		{
1890 			switch (nType)
1891 			{
1892                 case DataType::TIMESTAMP:
1893                     {
1894                         OSL_ENSURE(nLen == 8, "Invalid length for timestamp field");
1895                         if (nLen != 8) {
1896                             bHadError = true;
1897                             break;
1898                         }
1899                         sal_Int32 nJulianDate = 0, nJulianTime = 0;
1900                         lcl_CalcJulDate(nJulianDate,nJulianTime,rRow.get()[nPos]->getValue());
1901                         // Genau 8 Byte kopieren:
1902 					    memcpy(pData,&nJulianDate,4);
1903                         memcpy(pData+4,&nJulianTime,4);
1904                     }
1905                     break;
1906 				case DataType::DATE:
1907 				{
1908                     OSL_ENSURE(nLen == 8, "Invalid length for date field");
1909                     if (nLen != 8) {
1910                         bHadError = true;
1911                         break;
1912                     }
1913 					::com::sun::star::util::Date aDate;
1914 					if(rRow.get()[nPos]->getValue().getTypeKind() == DataType::DOUBLE)
1915 						aDate = ::dbtools::DBTypeConversion::toDate(rRow.get()[nPos]->getValue().getDouble());
1916 					else
1917 						aDate = rRow.get()[nPos]->getValue();
1918 					char s[9];
1919 					snprintf(s,
1920 						sizeof(s),
1921 						"%04d%02d%02d",
1922 						(int)aDate.Year,
1923 						(int)aDate.Month,
1924 						(int)aDate.Day);
1925 
1926 					// Genau 8 Byte kopieren:
1927 					strncpy(pData,s,sizeof s - 1);
1928 				} break;
1929                 case DataType::INTEGER:
1930                     {
1931                         OSL_ENSURE(nLen == 4, "Invalid length for integer field");
1932                         if (nLen != 4) {
1933                             bHadError = true;
1934                             break;
1935                         }
1936                         sal_Int32 nValue = rRow.get()[nPos]->getValue();
1937                         memcpy(pData,&nValue,nLen);
1938                     }
1939                     break;
1940                 case DataType::DOUBLE:
1941                     {
1942                         OSL_ENSURE(nLen == 8, "Invalid length for double field");
1943                         if (nLen != 8) {
1944                             bHadError = true;
1945                             break;
1946                         }
1947                         const double d = rRow.get()[nPos]->getValue();
1948                         m_pColumns->getByIndex(i) >>= xCol;
1949 
1950                         if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1951                         {
1952                             sal_Int64 nValue = 0;
1953                             if ( m_aScales[i] )
1954                                 nValue = (sal_Int64)(d * pow(10.0,(int)m_aScales[i]));
1955                             else
1956                                 nValue = (sal_Int64)(d);
1957                             memcpy(pData,&nValue,nLen);
1958                         } // if (getBOOL(xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISCURRENCY)))) // Currency wird gesondert behandelt
1959                         else
1960                             memcpy(pData,&d,nLen);
1961                     }
1962                     break;
1963 				case DataType::DECIMAL:
1964 				{
1965 					memset(pData,' ',nLen);	// Zuruecksetzen auf NULL
1966 
1967 					const double n = rRow.get()[nPos]->getValue();
1968 
1969 					// ein const_cast, da GetFormatPrecision am SvNumberFormat nicht const ist, obwohl es das eigentlich
1970 					// sein koennte und muesste
1971 
1972 					const ByteString aDefaultValue( ::rtl::math::doubleToString( n, rtl_math_StringFormat_F, nScale, '.', NULL, 0));
1973                     sal_Bool bValidLength  = aDefaultValue.Len() <= nLen;
1974                     if ( bValidLength )
1975                     {
1976 					    strncpy(pData,aDefaultValue.GetBuffer(),nLen);
1977 					    // write the resulting double back
1978 					    *rRow.get()[nPos] = toDouble(aDefaultValue);
1979                     }
1980                     else
1981 					{
1982 						m_pColumns->getByIndex(i) >>= xCol;
1983 						OSL_ENSURE(xCol.is(),"ODbaseTable::UpdateBuffer column is null!");
1984 						xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
1985                         ::std::list< ::std::pair<const sal_Char* , ::rtl::OUString > > aStringToSubstitutes;
1986                         aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$columnname$", aColName));
1987                         aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$precision$", String::CreateFromInt32(nLen)));
1988                         aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$scale$", String::CreateFromInt32(nScale)));
1989                         aStringToSubstitutes.push_back(::std::pair<const sal_Char* , ::rtl::OUString >("$value$", ::rtl::OStringToOUString(aDefaultValue,RTL_TEXTENCODING_UTF8)));
1990 
1991                         const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
1992                                 STR_INVALID_COLUMN_DECIMAL_VALUE
1993                                 ,aStringToSubstitutes
1994                              ) );
1995                         ::dbtools::throwGenericSQLException( sError, *this );
1996 					}
1997 				} break;
1998 				case DataType::BIT:
1999                     OSL_ENSURE(nLen == 1, "Invalid length for bit field");
2000                     if (nLen != 1) {
2001                         bHadError = true;
2002                         break;
2003                     }
2004 					*pData = rRow.get()[nPos]->getValue().getBool() ? 'T' : 'F';
2005 					break;
2006                 case DataType::LONGVARBINARY:
2007 				case DataType::LONGVARCHAR:
2008 				{
2009 					char cNext = pData[nLen]; // merken und temporaer durch 0 ersetzen
2010 					pData[nLen] = '\0';		  // das geht, da der Puffer immer ein Zeichen groesser ist ...
2011 
2012 					sal_uIntPtr nBlockNo = strtol((const char *)pData,NULL,10);	// Blocknummer lesen
2013 
2014 					// Naechstes Anfangszeichen wieder restaurieren:
2015 					pData[nLen] = cNext;
2016 					if (!m_pMemoStream || !WriteMemo(rRow.get()[nPos]->get(), nBlockNo))
2017 						break;
2018 
2019 					ByteString aStr;
2020 					ByteString aBlock(ByteString::CreateFromInt32(nBlockNo));
2021 					aStr.Expand(static_cast<sal_uInt16>(nLen - aBlock.Len()), '0' );
2022 					aStr += aBlock;
2023 					// Zeichen kopieren:
2024 					memset(pData,' ',nLen);	// Zuruecksetzen auf NULL
2025 					memcpy(pData, aStr.GetBuffer(), nLen);
2026 				}	break;
2027 				default:
2028 				{
2029 					memset(pData,' ',nLen);	// Zuruecksetzen auf NULL
2030 
2031                     ::rtl::OUString sStringToWrite( rRow.get()[nPos]->getValue().getString() );
2032 
2033                     // convert the string, using the connection's encoding
2034                     ::rtl::OString sEncoded;
2035 
2036                     DBTypeConversion::convertUnicodeStringToLength( sStringToWrite, sEncoded, nLen, m_eEncoding );
2037                     memcpy( pData, sEncoded.getStr(), sEncoded.getLength() );
2038 
2039 				}
2040                 break;
2041 			}
2042 		}
2043 		catch( SQLException&  )
2044         {
2045             throw;
2046         }
2047 		catch ( Exception& ) { bHadError = sal_True; }
2048 
2049 		if ( bHadError )
2050 		{
2051 			m_pColumns->getByIndex(i) >>= xCol;
2052 			OSL_ENSURE( xCol.is(), "ODbaseTable::UpdateBuffer column is null!" );
2053             if ( xCol.is() )
2054 			    xCol->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= aColName;
2055 
2056 			const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2057                     STR_INVALID_COLUMN_VALUE,
2058                     "$columnname$", aColName
2059                  ) );
2060             ::dbtools::throwGenericSQLException( sError, *this );
2061 		}
2062 		// Und weiter ...
2063 		nByteOffset += nLen;
2064 		OSL_ENSURE( nByteOffset <= m_nBufferSize ,"ByteOffset > m_nBufferSize!");
2065 	}
2066 	return sal_True;
2067 }
2068 
2069 // -----------------------------------------------------------------------------
WriteMemo(ORowSetValue & aVariable,sal_uIntPtr & rBlockNr)2070 sal_Bool ODbaseTable::WriteMemo(ORowSetValue& aVariable, sal_uIntPtr& rBlockNr)
2071 {
2072     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::WriteMemo" );
2073 	// wird die BlockNr 0 vorgegeben, wird der block ans Ende gehaengt
2074     sal_uIntPtr nSize = 0;
2075     ::rtl::OString aStr;
2076     ::com::sun::star::uno::Sequence<sal_Int8> aValue;
2077 	sal_uInt8 nHeader[4];
2078     const bool bBinary = aVariable.getTypeKind() == DataType::LONGVARBINARY && m_aMemoHeader.db_typ == MemoFoxPro;
2079     if ( bBinary )
2080     {
2081         aValue = aVariable.getSequence();
2082         nSize = aValue.getLength();
2083     }
2084     else
2085     {
2086         nSize = DBTypeConversion::convertUnicodeString( aVariable.getString(), aStr, m_eEncoding );
2087     }
2088 
2089 	// Anhaengen oder ueberschreiben
2090 	sal_Bool bAppend = rBlockNr == 0;
2091 
2092 	if (!bAppend)
2093 	{
2094 		switch (m_aMemoHeader.db_typ)
2095 		{
2096 			case MemodBaseIII: // dBase III-Memofeld, endet mit 2 * Ctrl-Z
2097 				bAppend = nSize > (512 - 2);
2098 				break;
2099 			case MemoFoxPro:
2100 			case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2101 			{
2102 				char sHeader[4];
2103 				m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2104 				m_pMemoStream->SeekRel(4L);
2105 				m_pMemoStream->Read(sHeader,4);
2106 
2107 				sal_uIntPtr nOldSize;
2108 				if (m_aMemoHeader.db_typ == MemoFoxPro)
2109 					nOldSize = ((((unsigned char)sHeader[0]) * 256 +
2110 								 (unsigned char)sHeader[1]) * 256 +
2111 								 (unsigned char)sHeader[2]) * 256 +
2112 								 (unsigned char)sHeader[3];
2113 				else
2114 					nOldSize = ((((unsigned char)sHeader[3]) * 256 +
2115 								 (unsigned char)sHeader[2]) * 256 +
2116 								 (unsigned char)sHeader[1]) * 256 +
2117 								 (unsigned char)sHeader[0]  - 8;
2118 
2119 				// passt die neue Laenge in die belegten Bloecke
2120 				sal_uIntPtr nUsedBlocks = ((nSize + 8) / m_aMemoHeader.db_size) + (((nSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0),
2121 					  nOldUsedBlocks = ((nOldSize + 8) / m_aMemoHeader.db_size) + (((nOldSize + 8) % m_aMemoHeader.db_size > 0) ? 1 : 0);
2122 				bAppend = nUsedBlocks > nOldUsedBlocks;
2123 			}
2124 		}
2125 	}
2126 
2127 	if (bAppend)
2128 	{
2129 		sal_uIntPtr nStreamSize = m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2130 		// letzten block auffuellen
2131 		rBlockNr = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2132 
2133 		m_pMemoStream->SetStreamSize(rBlockNr * m_aMemoHeader.db_size);
2134 		m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2135 	}
2136 	else
2137 	{
2138 		m_pMemoStream->Seek(rBlockNr * m_aMemoHeader.db_size);
2139 	}
2140 
2141 	switch (m_aMemoHeader.db_typ)
2142 	{
2143 		case MemodBaseIII: // dBase III-Memofeld, endet mit Ctrl-Z
2144 		{
2145 			const char cEOF = (char) DBF_EOL;
2146 			nSize++;
2147 			m_pMemoStream->Write( aStr.getStr(), aStr.getLength() );
2148 			(*m_pMemoStream) << cEOF << cEOF;
2149 		} break;
2150 		case MemoFoxPro:
2151 		case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2152 		{
2153             if ( MemodBaseIV == m_aMemoHeader.db_typ )
2154 			    (*m_pMemoStream) << (sal_uInt8)0xFF
2155 							     << (sal_uInt8)0xFF
2156 							     << (sal_uInt8)0x08;
2157             else
2158                 (*m_pMemoStream) << (sal_uInt8)0x00
2159 							     << (sal_uInt8)0x00
2160 							     << (sal_uInt8)0x00;
2161 
2162 			sal_uInt32 nWriteSize = nSize;
2163 			if (m_aMemoHeader.db_typ == MemoFoxPro)
2164 			{
2165                 if ( bBinary )
2166                     (*m_pMemoStream) << (sal_uInt8) 0x00; // Picture
2167                 else
2168 				    (*m_pMemoStream) << (sal_uInt8) 0x01; // Memo
2169 				for (int i = 4; i > 0; nWriteSize >>= 8)
2170 					nHeader[--i] = (sal_uInt8) (nWriteSize % 256);
2171 			}
2172 			else
2173 			{
2174 				(*m_pMemoStream) << (sal_uInt8) 0x00;
2175 				nWriteSize += 8;
2176 				for (int i = 0; i < 4; nWriteSize >>= 8)
2177 					nHeader[i++] = (sal_uInt8) (nWriteSize % 256);
2178 			}
2179 
2180 			m_pMemoStream->Write(nHeader,4);
2181             if ( bBinary )
2182                 m_pMemoStream->Write( aValue.getConstArray(), aValue.getLength() );
2183             else
2184 			    m_pMemoStream->Write( aStr.getStr(), aStr.getLength() );
2185 			m_pMemoStream->Flush();
2186 		}
2187 	}
2188 
2189 
2190 	// Schreiben der neuen Blocknummer
2191 	if (bAppend)
2192 	{
2193 		sal_uIntPtr nStreamSize = m_pMemoStream->Seek(STREAM_SEEK_TO_END);
2194 		m_aMemoHeader.db_next = (nStreamSize / m_aMemoHeader.db_size) + ((nStreamSize % m_aMemoHeader.db_size) > 0 ? 1 : 0);
2195 
2196 		// Schreiben der neuen Blocknummer
2197 		m_pMemoStream->Seek(0L);
2198 		(*m_pMemoStream) << m_aMemoHeader.db_next;
2199 		m_pMemoStream->Flush();
2200 	}
2201 	return sal_True;
2202 }
2203 
2204 // -----------------------------------------------------------------------------
2205 // XAlterTable
alterColumnByName(const::rtl::OUString & colName,const Reference<XPropertySet> & descriptor)2206 void SAL_CALL ODbaseTable::alterColumnByName( const ::rtl::OUString& colName, const Reference< XPropertySet >& descriptor ) throw(SQLException, NoSuchElementException, RuntimeException)
2207 {
2208     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumnByName" );
2209 	::osl::MutexGuard aGuard(m_aMutex);
2210 	checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2211 
2212 
2213 	Reference<XDataDescriptorFactory> xOldColumn;
2214 	m_pColumns->getByName(colName) >>= xOldColumn;
2215 
2216 	alterColumn(m_pColumns->findColumn(colName)-1,descriptor,xOldColumn);
2217 }
2218 // -------------------------------------------------------------------------
alterColumnByIndex(sal_Int32 index,const Reference<XPropertySet> & descriptor)2219 void SAL_CALL ODbaseTable::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
2220 {
2221     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumnByIndex" );
2222 	::osl::MutexGuard aGuard(m_aMutex);
2223 	checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2224 
2225 	if(index < 0 || index >= m_pColumns->getCount())
2226 		throw IndexOutOfBoundsException(::rtl::OUString::valueOf(index),*this);
2227 
2228 	Reference<XDataDescriptorFactory> xOldColumn;
2229 	m_pColumns->getByIndex(index) >>= xOldColumn;
2230 	alterColumn(index,descriptor,xOldColumn);
2231 }
2232 // -----------------------------------------------------------------------------
alterColumn(sal_Int32 index,const Reference<XPropertySet> & descriptor,const Reference<XDataDescriptorFactory> & xOldColumn)2233 void ODbaseTable::alterColumn(sal_Int32 index,
2234 							  const Reference< XPropertySet >& descriptor ,
2235 							  const Reference< XDataDescriptorFactory >& xOldColumn )
2236 {
2237     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::alterColumn" );
2238 	if(index < 0 || index >= m_pColumns->getCount())
2239 		throw IndexOutOfBoundsException(::rtl::OUString::valueOf(index),*this);
2240 
2241 	ODbaseTable* pNewTable = NULL;
2242 	try
2243 	{
2244 		OSL_ENSURE(descriptor.is(),"ODbaseTable::alterColumn: descriptor can not be null!");
2245 		// creates a copy of the original column and copy all properties from descriptor in xCopyColumn
2246 		Reference<XPropertySet> xCopyColumn;
2247 		if(xOldColumn.is())
2248 			xCopyColumn = xOldColumn->createDataDescriptor();
2249 		else
2250 			xCopyColumn = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2251 
2252 		::comphelper::copyProperties(descriptor,xCopyColumn);
2253 
2254 		// creates a temp file
2255 
2256 		String sTempName = createTempFile();
2257 
2258 		pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2259 		Reference<XPropertySet> xHoldTable = pNewTable;
2260 		pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2261 		Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2262 		OSL_ENSURE(xAppend.is(),"ODbaseTable::alterColumn: No XAppend interface!");
2263 
2264 		// copy the structure
2265 		sal_Int32 i=0;
2266 		for(;i < index;++i)
2267 		{
2268 			Reference<XPropertySet> xProp;
2269 			m_pColumns->getByIndex(i) >>= xProp;
2270 			Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2271 			Reference<XPropertySet> xCpy;
2272 			if(xColumn.is())
2273 				xCpy = xColumn->createDataDescriptor();
2274 			else
2275 				xCpy = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2276 			::comphelper::copyProperties(xProp,xCpy);
2277 			xAppend->appendByDescriptor(xCpy);
2278 		}
2279 		++i; // now insert our new column
2280 		xAppend->appendByDescriptor(xCopyColumn);
2281 
2282 		for(;i < m_pColumns->getCount();++i)
2283 		{
2284 			Reference<XPropertySet> xProp;
2285 			m_pColumns->getByIndex(i) >>= xProp;
2286 			Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2287 			Reference<XPropertySet> xCpy;
2288 			if(xColumn.is())
2289 				xCpy = xColumn->createDataDescriptor();
2290 			else
2291 				xCpy = new OColumn(getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers());
2292 			::comphelper::copyProperties(xProp,xCpy);
2293 			xAppend->appendByDescriptor(xCpy);
2294 		}
2295 
2296 		// construct the new table
2297 		if(!pNewTable->CreateImpl())
2298 		{
2299             const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2300                     STR_COLUMN_NOT_ALTERABLE,
2301                     "$columnname$", ::comphelper::getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2302                  ) );
2303             ::dbtools::throwGenericSQLException( sError, *this );
2304 		}
2305 
2306 		pNewTable->construct();
2307 
2308 		// copy the data
2309 		copyData(pNewTable,0);
2310 
2311 		// now drop the old one
2312 		if( DropImpl() ) // we don't want to delete the memo columns too
2313 		{
2314 			// rename the new one to the old one
2315 			pNewTable->renameImpl(m_Name);
2316 			// release the temp file
2317 			pNewTable = NULL;
2318 			::comphelper::disposeComponent(xHoldTable);
2319 		}
2320 		else
2321 		{
2322 			pNewTable = NULL;
2323 		}
2324 		FileClose();
2325 		construct();
2326 		if(m_pColumns)
2327 			m_pColumns->refresh();
2328 
2329 	}
2330 	catch(const SQLException&)
2331 	{
2332 		throw;
2333 	}
2334 	catch(const Exception&)
2335 	{
2336 		OSL_ENSURE(0,"ODbaseTable::alterColumn: Exception occurred!");
2337 		throw;
2338 	}
2339 }
2340 // -----------------------------------------------------------------------------
getMetaData() const2341 Reference< XDatabaseMetaData> ODbaseTable::getMetaData() const
2342 {
2343     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getMetaData" );
2344 	return getConnection()->getMetaData();
2345 }
2346 // -------------------------------------------------------------------------
rename(const::rtl::OUString & newName)2347 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)
2348 {
2349     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::rename" );
2350 	::osl::MutexGuard aGuard(m_aMutex);
2351 	checkDisposed(OTableDescriptor_BASE::rBHelper.bDisposed);
2352 	if(m_pTables && m_pTables->hasByName(newName))
2353 		throw ElementExistException(newName,*this);
2354 
2355 
2356 	renameImpl(newName);
2357 
2358 	ODbaseTable_BASE::rename(newName);
2359 
2360 	construct();
2361 	if(m_pColumns)
2362 		m_pColumns->refresh();
2363 }
2364 namespace
2365 {
renameFile(OConnection * _pConenction,const::rtl::OUString & oldName,const::rtl::OUString & newName,const String & _sExtension)2366 	void renameFile(OConnection* _pConenction,const ::rtl::OUString& oldName,
2367 					const ::rtl::OUString& newName,const String& _sExtension)
2368 	{
2369 		String aName = ODbaseTable::getEntry(_pConenction,oldName);
2370 		if(!aName.Len())
2371 		{
2372 			::rtl::OUString aIdent = _pConenction->getContent()->getIdentifier()->getContentIdentifier();
2373 			if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2374 				aIdent += ::rtl::OUString::createFromAscii("/");
2375 			aIdent += oldName;
2376 			aName = aIdent;
2377 		}
2378 		INetURLObject aURL;
2379 		aURL.SetURL(aName);
2380 
2381 		aURL.setExtension( _sExtension );
2382 		String sNewName(newName);
2383 		sNewName.AppendAscii(".");
2384 		sNewName += _sExtension;
2385 
2386 		try
2387 		{
2388 			Content aContent(aURL.GetMainURL(INetURLObject::NO_DECODE),Reference<XCommandEnvironment>());
2389 
2390 			Sequence< PropertyValue > aProps( 1 );
2391 			aProps[0].Name		= ::rtl::OUString::createFromAscii("Title");
2392 			aProps[0].Handle	= -1; // n/a
2393 			aProps[0].Value		= makeAny( ::rtl::OUString(sNewName) );
2394 			Sequence< Any > aValues;
2395 			aContent.executeCommand( rtl::OUString::createFromAscii( "setPropertyValues" ),makeAny(aProps) ) >>= aValues;
2396 			if(aValues.getLength() && aValues[0].hasValue())
2397 				throw Exception();
2398 		}
2399 		catch(Exception&)
2400 		{
2401 			throw ElementExistException(newName,NULL);
2402 		}
2403 	}
2404 }
2405 // -------------------------------------------------------------------------
renameImpl(const::rtl::OUString & newName)2406 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)
2407 {
2408     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getEntry" );
2409 	::osl::MutexGuard aGuard(m_aMutex);
2410 
2411 	FileClose();
2412 
2413 
2414 	renameFile(m_pConnection,m_Name,newName,m_pConnection->getExtension());
2415 	if ( HasMemoFields() )
2416 	{  // delete the memo fields
2417 		String sExt = String::CreateFromAscii("dbt");
2418 		renameFile(m_pConnection,m_Name,newName,sExt);
2419 	}
2420 }
2421 // -----------------------------------------------------------------------------
addColumn(const Reference<XPropertySet> & _xNewColumn)2422 void ODbaseTable::addColumn(const Reference< XPropertySet >& _xNewColumn)
2423 {
2424     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::addColumn" );
2425 	String sTempName = createTempFile();
2426 
2427 	ODbaseTable* pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2428 	Reference< XPropertySet > xHold = pNewTable;
2429 	pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2430 	{
2431 		Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2432 		sal_Bool bCase = getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers();
2433 		// copy the structure
2434 		for(sal_Int32 i=0;i < m_pColumns->getCount();++i)
2435 		{
2436 			Reference<XPropertySet> xProp;
2437 			m_pColumns->getByIndex(i) >>= xProp;
2438 			Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2439 			Reference<XPropertySet> xCpy;
2440 			if(xColumn.is())
2441 				xCpy = xColumn->createDataDescriptor();
2442 			else
2443 			{
2444 				xCpy = new OColumn(bCase);
2445 				::comphelper::copyProperties(xProp,xCpy);
2446 			}
2447 
2448 			xAppend->appendByDescriptor(xCpy);
2449 		}
2450 		Reference<XPropertySet> xCpy = new OColumn(bCase);
2451 		::comphelper::copyProperties(_xNewColumn,xCpy);
2452 		xAppend->appendByDescriptor(xCpy);
2453 	}
2454 
2455 	// construct the new table
2456 	if(!pNewTable->CreateImpl())
2457 	{
2458         const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2459                 STR_COLUMN_NOT_ADDABLE,
2460                 "$columnname$", ::comphelper::getString(_xNewColumn->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)))
2461              ) );
2462         ::dbtools::throwGenericSQLException( sError, *this );
2463 	}
2464 
2465 	sal_Bool bAlreadyDroped = sal_False;
2466 	try
2467 	{
2468 		pNewTable->construct();
2469 		// copy the data
2470 		copyData(pNewTable,pNewTable->m_pColumns->getCount());
2471 		// drop the old table
2472 		if(DropImpl())
2473 		{
2474 			bAlreadyDroped = sal_True;
2475 			pNewTable->renameImpl(m_Name);
2476 			// release the temp file
2477 		}
2478 		xHold = pNewTable = NULL;
2479 
2480 		FileClose();
2481 		construct();
2482 		if(m_pColumns)
2483 			m_pColumns->refresh();
2484 	}
2485 	catch(const SQLException&)
2486 	{
2487 		// here we know that the old table wasn't droped before
2488 		if(!bAlreadyDroped)
2489 			xHold = pNewTable = NULL;
2490 
2491 		throw;
2492 	}
2493 }
2494 // -----------------------------------------------------------------------------
dropColumn(sal_Int32 _nPos)2495 void ODbaseTable::dropColumn(sal_Int32 _nPos)
2496 {
2497     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::dropColumn" );
2498 	String sTempName = createTempFile();
2499 
2500 	ODbaseTable* pNewTable = new ODbaseTable(m_pTables,static_cast<ODbaseConnection*>(m_pConnection));
2501 	Reference< XPropertySet > xHold = pNewTable;
2502 	pNewTable->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(::rtl::OUString(sTempName)));
2503 	{
2504 		Reference<XAppend> xAppend(pNewTable->getColumns(),UNO_QUERY);
2505 		sal_Bool bCase = getConnection()->getMetaData()->supportsMixedCaseQuotedIdentifiers();
2506 		// copy the structure
2507 		for(sal_Int32 i=0;i < m_pColumns->getCount();++i)
2508 		{
2509 			if(_nPos != i)
2510 			{
2511 				Reference<XPropertySet> xProp;
2512 				m_pColumns->getByIndex(i) >>= xProp;
2513 				Reference<XDataDescriptorFactory> xColumn(xProp,UNO_QUERY);
2514 				Reference<XPropertySet> xCpy;
2515 				if(xColumn.is())
2516 					xCpy = xColumn->createDataDescriptor();
2517 				else
2518 				{
2519 					xCpy = new OColumn(bCase);
2520 					::comphelper::copyProperties(xProp,xCpy);
2521 				}
2522 				xAppend->appendByDescriptor(xCpy);
2523 			}
2524 		}
2525 	}
2526 
2527 	// construct the new table
2528 	if(!pNewTable->CreateImpl())
2529 	{
2530 		xHold = pNewTable = NULL;
2531         const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2532                 STR_COLUMN_NOT_DROP,
2533                 "$position$", ::rtl::OUString::valueOf(_nPos)
2534              ) );
2535         ::dbtools::throwGenericSQLException( sError, *this );
2536 	}
2537 	pNewTable->construct();
2538 	// copy the data
2539 	copyData(pNewTable,_nPos);
2540 	// drop the old table
2541 	if(DropImpl())
2542 		pNewTable->renameImpl(m_Name);
2543 		// release the temp file
2544 
2545 	xHold = pNewTable = NULL;
2546 
2547 	FileClose();
2548 	construct();
2549 }
2550 // -----------------------------------------------------------------------------
createTempFile()2551 String ODbaseTable::createTempFile()
2552 {
2553     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::createTempFile" );
2554 	::rtl::OUString aIdent = m_pConnection->getContent()->getIdentifier()->getContentIdentifier();
2555 	if ( aIdent.lastIndexOf('/') != (aIdent.getLength()-1) )
2556 		aIdent += ::rtl::OUString::createFromAscii("/");
2557 	String sTempName(aIdent);
2558 	String sExt;
2559 	sExt.AssignAscii(".");
2560 	sExt += m_pConnection->getExtension();
2561 
2562 	String sName(m_Name);
2563 	TempFile aTempFile(sName,&sExt,&sTempName);
2564 	if(!aTempFile.IsValid())
2565         getConnection()->throwGenericSQLException(STR_COULD_NOT_ALTER_TABLE,*this);
2566 
2567 	INetURLObject aURL;
2568 	aURL.SetSmartProtocol(INET_PROT_FILE);
2569 	aURL.SetURL(aTempFile.GetURL());
2570 
2571 	String sNewName(aURL.getName());
2572 	sNewName.Erase(sNewName.Len() - sExt.Len());
2573 	return sNewName;
2574 }
2575 // -----------------------------------------------------------------------------
copyData(ODbaseTable * _pNewTable,sal_Int32 _nPos)2576 void ODbaseTable::copyData(ODbaseTable* _pNewTable,sal_Int32 _nPos)
2577 {
2578     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::copyData" );
2579 	sal_Int32 nPos = _nPos + 1; // +1 because we always have the bookmark column as well
2580 	OValueRefRow aRow = new OValueRefVector(m_pColumns->getCount());
2581 	OValueRefRow aInsertRow;
2582 	if(_nPos)
2583 	{
2584 		aInsertRow = new OValueRefVector(_pNewTable->m_pColumns->getCount());
2585 		::std::for_each(aInsertRow->get().begin(),aInsertRow->get().end(),TSetRefBound(sal_True));
2586 	}
2587 	else
2588 		aInsertRow = aRow;
2589 
2590 	// we only have to bind the values which we need to copy into the new table
2591 	::std::for_each(aRow->get().begin(),aRow->get().end(),TSetRefBound(sal_True));
2592 	if(_nPos && (_nPos < (sal_Int32)aRow->get().size()))
2593 		(aRow->get())[nPos]->setBound(sal_False);
2594 
2595 
2596 	sal_Bool bOk = sal_True;
2597 	sal_Int32 nCurPos;
2598 	OValueRefVector::Vector::iterator aIter;
2599 	for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.db_anz;++nRowPos)
2600 	{
2601         bOk = seekRow( IResultSetHelper::BOOKMARK, nRowPos+1, nCurPos );
2602         if ( bOk )
2603 		{
2604             bOk = fetchRow( aRow, m_aColumns.getBody(), sal_True, sal_True);
2605             if ( bOk && !aRow->isDeleted() ) // copy only not deleted rows
2606 			{
2607 				// special handling when pos == 0 then we don't have to distinguish	between the two rows
2608 				if(_nPos)
2609 				{
2610 					aIter = aRow->get().begin()+1;
2611 					sal_Int32 nCount = 1;
2612 					for(OValueRefVector::Vector::iterator aInsertIter = aInsertRow->get().begin()+1; aIter != aRow->get().end() && aInsertIter != aInsertRow->get().end();++aIter,++nCount)
2613 					{
2614 						if(nPos != nCount)
2615 						{
2616 							(*aInsertIter)->setValue( (*aIter)->getValue() );
2617 							++aInsertIter;
2618 						}
2619 					}
2620 				}
2621 				bOk = _pNewTable->InsertRow(*aInsertRow,sal_True,_pNewTable->m_pColumns);
2622 				OSL_ENSURE(bOk,"Row could not be inserted!");
2623 			}
2624 			else
2625 				OSL_ENSURE(bOk,"Row could not be fetched!");
2626 		}
2627 		else
2628 		{
2629 			OSL_ASSERT(0);
2630 		}
2631 	} // for(sal_uInt32 nRowPos = 0; nRowPos < m_aHeader.db_anz;++nRowPos)
2632 }
2633 // -----------------------------------------------------------------------------
throwInvalidDbaseFormat()2634 void ODbaseTable::throwInvalidDbaseFormat()
2635 {
2636     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::throwInvalidDbaseFormat" );
2637 	FileClose();
2638 	// no dbase file
2639 
2640     const ::rtl::OUString sError( getConnection()->getResources().getResourceStringWithSubstitution(
2641                 STR_INVALID_DBASE_FILE,
2642                 "$filename$", getEntry(m_pConnection,m_Name)
2643              ) );
2644     ::dbtools::throwGenericSQLException( sError, *this );
2645 }
2646 // -----------------------------------------------------------------------------
refreshHeader()2647 void ODbaseTable::refreshHeader()
2648 {
2649     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::refreshHeader" );
2650     if ( m_aHeader.db_anz == 0 )
2651 	    readHeader();
2652 }
2653 //------------------------------------------------------------------
seekRow(IResultSetHelper::Movement eCursorPosition,sal_Int32 nOffset,sal_Int32 & nCurPos)2654 sal_Bool ODbaseTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
2655 {
2656     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::seekRow" );
2657 	// ----------------------------------------------------------
2658 	// Positionierung vorbereiten:
2659 	OSL_ENSURE(m_pFileStream,"ODbaseTable::seekRow: FileStream is NULL!");
2660 
2661 	sal_uInt32  nNumberOfRecords = (sal_uInt32)m_aHeader.db_anz;
2662 	sal_uInt32 nTempPos = m_nFilePos;
2663 	m_nFilePos = nCurPos;
2664 
2665 	switch(eCursorPosition)
2666 	{
2667 		case IResultSetHelper::NEXT:
2668 			++m_nFilePos;
2669 			break;
2670 		case IResultSetHelper::PRIOR:
2671 			if (m_nFilePos > 0)
2672 				--m_nFilePos;
2673 			break;
2674 		case IResultSetHelper::FIRST:
2675 			m_nFilePos = 1;
2676 			break;
2677 		case IResultSetHelper::LAST:
2678 			m_nFilePos = nNumberOfRecords;
2679 			break;
2680 		case IResultSetHelper::RELATIVE:
2681 			m_nFilePos = (((sal_Int32)m_nFilePos) + nOffset < 0) ? 0L
2682 							: (sal_uInt32)(((sal_Int32)m_nFilePos) + nOffset);
2683 			break;
2684 		case IResultSetHelper::ABSOLUTE:
2685 		case IResultSetHelper::BOOKMARK:
2686 			m_nFilePos = (sal_uInt32)nOffset;
2687 			break;
2688 	}
2689 
2690 	if (m_nFilePos > (sal_Int32)nNumberOfRecords)
2691 		m_nFilePos = (sal_Int32)nNumberOfRecords + 1;
2692 
2693 	if (m_nFilePos == 0 || m_nFilePos == (sal_Int32)nNumberOfRecords + 1)
2694 		goto Error;
2695 	else
2696 	{
2697 		sal_uInt16 nEntryLen = m_aHeader.db_slng;
2698 
2699 		OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: ungueltige Record-Position");
2700 		sal_Int32 nPos = m_aHeader.db_kopf + (sal_Int32)(m_nFilePos-1) * nEntryLen;
2701 
2702 		sal_uIntPtr nLen = m_pFileStream->Seek(nPos);
2703 		if (m_pFileStream->GetError() != ERRCODE_NONE)
2704 			goto Error;
2705 
2706 		nLen = m_pFileStream->Read((char*)m_pBuffer, nEntryLen);
2707 		if (m_pFileStream->GetError() != ERRCODE_NONE)
2708 			goto Error;
2709 	}
2710 	goto End;
2711 
2712 Error:
2713 	switch(eCursorPosition)
2714 	{
2715 		case IResultSetHelper::PRIOR:
2716 		case IResultSetHelper::FIRST:
2717 			m_nFilePos = 0;
2718 			break;
2719 		case IResultSetHelper::LAST:
2720 		case IResultSetHelper::NEXT:
2721 		case IResultSetHelper::ABSOLUTE:
2722 		case IResultSetHelper::RELATIVE:
2723 			if (nOffset > 0)
2724 				m_nFilePos = nNumberOfRecords + 1;
2725 			else if (nOffset < 0)
2726 				m_nFilePos = 0;
2727 			break;
2728 		case IResultSetHelper::BOOKMARK:
2729 			m_nFilePos = nTempPos;	 // vorherige Position
2730 	}
2731 	//	aStatus.Set(SDB_STAT_NO_DATA_FOUND);
2732 	return sal_False;
2733 
2734 End:
2735 	nCurPos = m_nFilePos;
2736 	return sal_True;
2737 }
2738 // -----------------------------------------------------------------------------
ReadMemo(sal_uIntPtr nBlockNo,ORowSetValue & aVariable)2739 sal_Bool ODbaseTable::ReadMemo(sal_uIntPtr nBlockNo, ORowSetValue& aVariable)
2740 {
2741     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::ReadMemo" );
2742 	sal_Bool bIsText = sal_True;
2743 	//	SdbConnection* pConnection = GetConnection();
2744 
2745 	m_pMemoStream->Seek(nBlockNo * m_aMemoHeader.db_size);
2746 	switch (m_aMemoHeader.db_typ)
2747 	{
2748 		case MemodBaseIII: // dBase III-Memofeld, endet mit Ctrl-Z
2749 		{
2750 			const char cEOF = (char) DBF_EOL;
2751 			ByteString aBStr;
2752 			static char aBuf[514];
2753 			aBuf[512] = 0;			// sonst kann der Zufall uebel mitspielen
2754 			sal_Bool bReady = sal_False;
2755 
2756 			do
2757 			{
2758 				m_pMemoStream->Read(&aBuf,512);
2759 
2760 				sal_uInt16 i = 0;
2761 				while (aBuf[i] != cEOF && ++i < 512)
2762 					;
2763 				bReady = aBuf[i] == cEOF;
2764 
2765 				aBuf[i] = 0;
2766 				aBStr += aBuf;
2767 
2768 			} while (!bReady && !m_pMemoStream->IsEof() && aBStr.Len() < STRING_MAXLEN);
2769 
2770 			::rtl::OUString aStr(aBStr.GetBuffer(), aBStr.Len(),m_eEncoding);
2771 			aVariable = aStr;
2772 
2773 		} break;
2774 		case MemoFoxPro:
2775 		case MemodBaseIV: // dBase IV-Memofeld mit Laengenangabe
2776 		{
2777 			char sHeader[4];
2778 			m_pMemoStream->Read(sHeader,4);
2779 			// Foxpro stores text and binary data
2780 			if (m_aMemoHeader.db_typ == MemoFoxPro)
2781 			{
2782 //				if (((sal_uInt8)sHeader[0]) != 0 || ((sal_uInt8)sHeader[1]) != 0 || ((sal_uInt8)sHeader[2]) != 0)
2783 //				{
2784 ////					String aText = String(SdbResId(STR_STAT_IResultSetHelper::INVALID));
2785 ////					aText.SearchAndReplace(String::CreateFromAscii("%%d"),m_pMemoStream->GetFileName());
2786 ////					aText.SearchAndReplace(String::CreateFromAscii("%%t"),aStatus.TypeToString(MEMO));
2787 ////					aStatus.Set(SDB_STAT_ERROR,
2788 ////							String::CreateFromAscii("01000"),
2789 ////							aStatus.CreateErrorMessage(aText),
2790 ////							0, String() );
2791 //					return sal_False;
2792 //				}
2793 //
2794 				bIsText = sHeader[3] != 0;
2795 			}
2796 			else if (((sal_uInt8)sHeader[0]) != 0xFF || ((sal_uInt8)sHeader[1]) != 0xFF || ((sal_uInt8)sHeader[2]) != 0x08)
2797 			{
2798 //				String aText = String(SdbResId(STR_STAT_IResultSetHelper::INVALID));
2799 //				aText.SearchAndReplace(String::CreateFromAscii("%%d"),m_pMemoStream->GetFileName());
2800 //				aText.SearchAndReplace(String::CreateFromAscii("%%t"),aStatus.TypeToString(MEMO));
2801 //				aStatus.Set(SDB_STAT_ERROR,
2802 //						String::CreateFromAscii("01000"),
2803 //						aStatus.CreateErrorMessage(aText),
2804 //						0, String() );
2805 				return sal_False;
2806 			}
2807 
2808 			sal_uInt32 nLength(0);
2809 			(*m_pMemoStream) >> nLength;
2810 
2811 			if (m_aMemoHeader.db_typ == MemodBaseIV)
2812 				nLength -= 8;
2813 
2814             if ( nLength )
2815             {
2816                 if ( bIsText )
2817                 {
2818 			        //	char cChar;
2819 					::rtl::OUStringBuffer aStr;
2820 			        while ( nLength > STRING_MAXLEN )
2821 			        {
2822 				        ByteString aBStr;
2823 				        aBStr.Expand(STRING_MAXLEN);
2824 				        m_pMemoStream->Read(aBStr.AllocBuffer(STRING_MAXLEN),STRING_MAXLEN);
2825 						aStr.append(::rtl::OUString(aBStr.GetBuffer(),aBStr.Len(), m_eEncoding));
2826 				        nLength -= STRING_MAXLEN;
2827 			        }
2828 			        if ( nLength > 0 )
2829 			        {
2830 				        ByteString aBStr;
2831 				        aBStr.Expand(static_cast<xub_StrLen>(nLength));
2832 				        m_pMemoStream->Read(aBStr.AllocBuffer(static_cast<xub_StrLen>(nLength)),nLength);
2833 				        //	aBStr.ReleaseBufferAccess();
2834 						aStr.append(::rtl::OUString(aBStr.GetBuffer(),aBStr.Len(), m_eEncoding));
2835 			        }
2836 			        if ( aStr.getLength() )
2837 						aVariable = aStr.makeStringAndClear();
2838                 } // if ( bIsText )
2839                 else
2840                 {
2841                     ::com::sun::star::uno::Sequence< sal_Int8 > aData(nLength);
2842                     m_pMemoStream->Read(aData.getArray(),nLength);
2843                     aVariable = aData;
2844                 }
2845             } // if ( nLength )
2846 		}
2847 	}
2848 	return sal_True;
2849 }
2850 // -----------------------------------------------------------------------------
AllocBuffer()2851 void ODbaseTable::AllocBuffer()
2852 {
2853     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::AllocBuffer" );
2854 	sal_uInt16 nSize = m_aHeader.db_slng;
2855 	OSL_ENSURE(nSize > 0, "Size too small");
2856 
2857 	if (m_nBufferSize != nSize)
2858 	{
2859 		delete m_pBuffer;
2860 		m_pBuffer = NULL;
2861 	}
2862 
2863 	// Falls noch kein Puffer vorhanden: allozieren:
2864 	if (m_pBuffer == NULL && nSize > 0)
2865 	{
2866 		m_nBufferSize = nSize;
2867 		m_pBuffer		= new sal_uInt8[m_nBufferSize+1];
2868 	}
2869 }
2870 // -----------------------------------------------------------------------------
WriteBuffer()2871 sal_Bool ODbaseTable::WriteBuffer()
2872 {
2873     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::WriteBuffer" );
2874 	OSL_ENSURE(m_nFilePos >= 1,"SdbDBFCursor::FileFetchRow: ungueltige Record-Position");
2875 
2876 	// Auf gewuenschten Record positionieren:
2877 	long nPos = m_aHeader.db_kopf + (long)(m_nFilePos-1) * m_aHeader.db_slng;
2878 	m_pFileStream->Seek(nPos);
2879 	return m_pFileStream->Write((char*) m_pBuffer, m_aHeader.db_slng) > 0;
2880 }
2881 // -----------------------------------------------------------------------------
getCurrentLastPos() const2882 sal_Int32 ODbaseTable::getCurrentLastPos() const
2883 {
2884     RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "dbase", "Ocke.Janssen@sun.com", "ODbaseTable::getCurrentLastPos" );
2885 	return m_aHeader.db_anz;
2886 }
2887