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