LCOV - code coverage report
Current view: top level - connectivity/source/drivers/dbase - DTable.cxx (source / functions) Hit Total Coverage
Test: commit c8344322a7af75b84dd3ca8f78b05543a976dfd5 Lines: 507 1444 35.1 %
Date: 2015-06-13 12:38:46 Functions: 27 50 54.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.11