summaryrefslogtreecommitdiff
path: root/connectivity/source/commontools/TTableHelper.cxx
blob: 9bb0298c867324368b17e7713346cbef9421a86b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: TTableHelper.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "connectivity/TTableHelper.hxx"
#include <com/sun/star/sdbc/XRow.hpp>
#include <com/sun/star/sdbc/XResultSet.hpp>
#include <com/sun/star/sdbcx/KeyType.hpp>
#include <com/sun/star/sdbc/KeyRule.hpp>
#include <cppuhelper/typeprovider.hxx>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <comphelper/sequence.hxx>
#include <comphelper/extract.hxx>
#include <comphelper/types.hxx>
#include "connectivity/dbtools.hxx"
#include "connectivity/sdbcx/VCollection.hxx"
#include <unotools/sharedunocomponent.hxx>
#include "TConnection.hxx"

using namespace ::comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
                           const Reference< XConnection >& _xConnection,
                           sal_Bool _bCase)
    :OTable_TYPEDEF(_pTables,_bCase)
    ,m_xConnection(_xConnection)
{
    try
    {
        m_xMetaData = m_xConnection->getMetaData();
    }
    catch(const Exception&)
    {
    }
}
// -------------------------------------------------------------------------
OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
                            const Reference< XConnection >& _xConnection,
                            sal_Bool _bCase,
                            const ::rtl::OUString& _Name,
                            const ::rtl::OUString& _Type,
                            const ::rtl::OUString& _Description ,
                            const ::rtl::OUString& _SchemaName,
                            const ::rtl::OUString& _CatalogName
                        ) : OTable_TYPEDEF(_pTables,
                                            _bCase,
                                            _Name,
                                          _Type,
                                          _Description,
                                          _SchemaName,
                                          _CatalogName)
                        ,m_xConnection(_xConnection)
{
    try
    {
        m_xMetaData = m_xConnection->getMetaData();
    }
    catch(const Exception&)
    {
    }
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::disposing()
{
    OTable_TYPEDEF::disposing();
    ::osl::MutexGuard aGuard(m_aMutex);
    m_xConnection   = NULL;
    m_xMetaData     = NULL;
}

// -------------------------------------------------------------------------
namespace
{
    typedef sal_Int32   OrdinalPosition;
    struct ColumnDesc
    {
        ::rtl::OUString sName;
        OrdinalPosition nOrdinalPosition;

        ColumnDesc() {}
        ColumnDesc( const ::rtl::OUString& _rName, OrdinalPosition _nPosition )
            :sName( _rName )
            ,nOrdinalPosition( _nPosition )
        {
        }
    };

    /** collects ColumnDesc's from a resultset produced by XDatabaseMetaData::getColumns
    */
    void lcl_collectColumnDescs_throw( const Reference< XResultSet >& _rxResult, ::std::vector< ColumnDesc >& _out_rColumns )
    {
        Reference< XRow > xRow( _rxResult, UNO_QUERY_THROW );
        ::rtl::OUString sName;
        OrdinalPosition nOrdinalPosition( 0 );
        while ( _rxResult->next() )
        {
            sName = xRow->getString( 4 );           // COLUMN_NAME
            nOrdinalPosition = xRow->getInt( 17 );  // ORDINAL_POSITION
            _out_rColumns.push_back( ColumnDesc( sName, nOrdinalPosition ) );
        }
    }

    /** checks a given array of ColumnDesc's whether it has reasonable ordinal positions. If not,
        they will be normalized to be the array index.
    */
    void lcl_sanitizeColumnDescs( ::std::vector< ColumnDesc >& _rColumns )
    {
        if ( _rColumns.empty() )
            return;

        // collect all used ordinals
        ::std::set< OrdinalPosition > aUsedOrdinals;
        for (   ::std::vector< ColumnDesc >::iterator collect = _rColumns.begin();
                collect != _rColumns.end();
                ++collect
            )
            aUsedOrdinals.insert( collect->nOrdinalPosition );

        // we need to have as much different ordinals as we have different columns
        bool bDuplicates = aUsedOrdinals.size() != _rColumns.size();
        // and it needs to be a continuous range
        size_t nOrdinalsRange = *aUsedOrdinals.rbegin() - *aUsedOrdinals.begin() + 1;
        bool bGaps = nOrdinalsRange != _rColumns.size();

        // if that's not the case, normalize it
        if ( bGaps || bDuplicates )
        {
            OSL_ENSURE( false, "lcl_sanitizeColumnDescs: database did provide invalid ORDINAL_POSITION values!" );

            OrdinalPosition nNormalizedPosition = 1;
            for (   ::std::vector< ColumnDesc >::iterator normalize = _rColumns.begin();
                    normalize != _rColumns.end();
                    ++normalize
                )
                normalize->nOrdinalPosition = nNormalizedPosition++;
            return;
        }

        // what's left is that the range might not be from 1 to <column count>, but for instance
        // 0 to <column count>-1.
        size_t nOffset = *aUsedOrdinals.begin() - 1;
        for (   ::std::vector< ColumnDesc >::iterator offset = _rColumns.begin();
                offset != _rColumns.end();
                ++offset
            )
            offset->nOrdinalPosition -= nOffset;
    }
}

// -------------------------------------------------------------------------
void OTableHelper::refreshColumns()
{
    TStringVector aVector;
    if(!isNew())
    {
        Any aCatalog;
        if ( m_CatalogName.getLength() )
            aCatalog <<= m_CatalogName;

        ::utl::SharedUNOComponent< XResultSet > xResult( getMetaData()->getColumns(
            aCatalog,
            m_SchemaName,
            m_Name,
            ::rtl::OUString::createFromAscii("%")
        ) );

        // collect the column names, together with their ordinal position
        ::std::vector< ColumnDesc > aColumns;
        lcl_collectColumnDescs_throw( xResult, aColumns );

        // ensure that the ordinal positions as obtained from the meta data do make sense
        lcl_sanitizeColumnDescs( aColumns );

        // sort by ordinal position
        ::std::map< OrdinalPosition, ::rtl::OUString > aSortedColumns;
        for (   ::std::vector< ColumnDesc >::const_iterator copy = aColumns.begin();
                copy != aColumns.end();
                ++copy
            )
            aSortedColumns[ copy->nOrdinalPosition ] = copy->sName;

        // copy them to aVector, now that we have the proper ordering
        ::std::transform(
            aSortedColumns.begin(),
            aSortedColumns.end(),
            ::std::insert_iterator< TStringVector >( aVector, aVector.begin() ),
            ::std::select2nd< ::std::map< OrdinalPosition, ::rtl::OUString >::value_type >()
        );
    }

    if(m_pColumns)
        m_pColumns->reFill(aVector);
    else
        m_pColumns  = createColumns(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshPrimaryKeys(std::vector< ::rtl::OUString>& _rKeys)
{
    Any aCatalog;
    if ( m_CatalogName.getLength() )
        aCatalog <<= m_CatalogName;
    Reference< XResultSet > xResult = getMetaData()->getPrimaryKeys(aCatalog,m_SchemaName,m_Name);

    if(xResult.is())
    {
        Reference< XRow > xRow(xResult,UNO_QUERY);
        if(xResult->next()) // there can be only one primary key
        {
            ::rtl::OUString aPkName = xRow->getString(6);
            _rKeys.push_back(aPkName);
        }
        ::comphelper::disposeComponent(xResult);
    }
}
// -------------------------------------------------------------------------
void OTableHelper::refreshForgeinKeys(std::vector< ::rtl::OUString>& _rKeys)
{
    Any aCatalog;
    if ( m_CatalogName.getLength() )
        aCatalog <<= m_CatalogName;
    Reference< XResultSet > xResult = getMetaData()->getImportedKeys(aCatalog,m_SchemaName,m_Name);
    Reference< XRow > xRow(xResult,UNO_QUERY);

    if ( xRow.is() )
    {
        while( xResult->next() )
        {
            sal_Int32 nKeySeq = xRow->getInt(9);
            if ( nKeySeq == 1 )
            { // only append when the sequnce number is 1 to forbid serveral inserting the same key name
                ::rtl::OUString sFkName = xRow->getString(12);
                if ( !xRow->wasNull() && sFkName.getLength() )
                    _rKeys.push_back(sFkName);
            }
        }
        ::comphelper::disposeComponent(xResult);
    }
}
// -------------------------------------------------------------------------
void OTableHelper::refreshKeys()
{
    TStringVector aVector;

    if(!isNew())
    {
        refreshPrimaryKeys(aVector);
        refreshForgeinKeys(aVector);
    }
    if(m_pKeys)
        m_pKeys->reFill(aVector);
    else
        m_pKeys = createKeys(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshIndexes()
{
    TStringVector aVector;
    if(!isNew())
    {
        // fill indexes
        Any aCatalog;
        if ( m_CatalogName.getLength() )
            aCatalog <<= m_CatalogName;
        Reference< XResultSet > xResult = getMetaData()->getIndexInfo(aCatalog,m_SchemaName,m_Name,sal_False,sal_False);

        if(xResult.is())
        {
            Reference< XRow > xRow(xResult,UNO_QUERY);
            ::rtl::OUString aName;
            ::rtl::OUString sCatalogSep = getMetaData()->getCatalogSeparator();
            ::rtl::OUString sPreviousRoundName;
            while( xResult->next() )
            {
                aName = xRow->getString(5);
                if(aName.getLength())
                    aName += sCatalogSep;
                aName += xRow->getString(6);
                if ( aName.getLength() )
                {
                    // don't insert the name if the last one we inserted was the same
                    if (sPreviousRoundName != aName)
                        aVector.push_back(aName);
                }
                sPreviousRoundName = aName;
            }
            ::comphelper::disposeComponent(xResult);
        }
    }

    if(m_pIndexes)
        m_pIndexes->reFill(aVector);
    else
        m_pIndexes  = createIndexes(aVector);
}
// -----------------------------------------------------------------------------
::rtl::OUString OTableHelper::getRenameStart() const
{
    ::rtl::OUString sSql(RTL_CONSTASCII_USTRINGPARAM("RENAME "));
    if ( m_Type == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
        sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" VIEW "));
    else
        sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" TABLE "));

    return sSql;
}
// -------------------------------------------------------------------------
// XRename
void SAL_CALL OTableHelper::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(
#ifdef GCC
        ::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
        rBHelper.bDisposed
#endif
        );

    if(!isNew())
    {
        ::rtl::OUString sSql = getRenameStart();
        ::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString(  );

        ::rtl::OUString sCatalog,sSchema,sTable;
        ::dbtools::qualifiedNameComponents(getMetaData(),newName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);

        ::rtl::OUString sComposedName;
        sComposedName = ::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sal_True,::dbtools::eInDataManipulation);
        sSql += sComposedName
             + ::rtl::OUString::createFromAscii(" TO ");
        sComposedName = ::dbtools::composeTableName(getMetaData(),sCatalog,sSchema,sTable,sal_True,::dbtools::eInDataManipulation);
        sSql += sComposedName;

        Reference< XStatement > xStmt = m_xConnection->createStatement(  );
        if ( xStmt.is() )
        {
            xStmt->execute(sSql);
            ::comphelper::disposeComponent(xStmt);
        }

        OTable_TYPEDEF::rename(newName);
    }
    else
        ::dbtools::qualifiedNameComponents(getMetaData(),newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInTableDefinitions);
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OTableHelper::getMetaData() const
{
    return m_xMetaData;
}
// -------------------------------------------------------------------------
void SAL_CALL OTableHelper::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(
#ifdef GCC
        ::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
        rBHelper.bDisposed
#endif
        );

    Reference< XPropertySet > xOld;
    if(::cppu::extractInterface(xOld,m_pColumns->getByIndex(index)) && xOld.is())
        alterColumnByName(getString(xOld->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),descriptor);
}

// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTableHelper::getName() throw(RuntimeException)
{
    ::rtl::OUString sComposedName;
    sComposedName = ::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sal_False,::dbtools::eInDataManipulation);
    return sComposedName;
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::acquire() throw()
{
    OTable_TYPEDEF::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::release() throw()
{
    OTable_TYPEDEF::release();
}
// -----------------------------------------------------------------------------