summaryrefslogtreecommitdiff
path: root/connectivity/source/drivers/mork/MQueryHelper.cxx
blob: 05dd1219f6fc9360cb6bb528565ff2192d598e9b (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */


#include "MColumnAlias.hxx"
#include "MQueryHelper.hxx"
#include "MConnection.hxx"

#include "MorkParser.hxx"
#include <stdlib.h>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <string.h>

#include "resource/mork_res.hrc"
#include "resource/common_res.hrc"

#include <connectivity/dbexception.hxx>
#include <unotools/textsearch.hxx>

using namespace connectivity::mork;
using namespace connectivity;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;


extern
::std::vector< sal_Bool > entryMatchedByExpression(MQueryHelper* _aQuery, MQueryExpression* _aExpr, MQueryHelperResultEntry* entry);

MQueryHelperResultEntry::MQueryHelperResultEntry()
{
}

MQueryHelperResultEntry::~MQueryHelperResultEntry()
{
}

OUString MQueryHelperResultEntry::getValue( const OString &key ) const
{
    FieldMap::const_iterator iter = m_Fields.find( key );
    if ( iter == m_Fields.end() )
    {
        return OUString();
    }
    else
    {
        return iter->second;
    }
}

void MQueryHelperResultEntry::setValue( const OString &key, const OUString & rValue)
{
//    SAL_INFO("connectivity.mork", "MQueryHelper::setValue()" );
//    SAL_INFO("connectivity.mork", "key: " << &key << " value: " << &rValue);

    m_Fields[ key ] = rValue;
}

MQueryHelper::MQueryHelper(const OColumnAlias& _ca)
    :m_nIndex( 0 )
    ,m_bHasMore( sal_True )
    ,m_bAtEnd( sal_False )
    ,m_rColumnAlias( _ca )
    ,m_aError()
{
    m_aResults.clear();
}

MQueryHelper::~MQueryHelper()
{
    SAL_INFO("connectivity.mork", "MQueryHelper::~MQueryHelper()");

    clear_results();
    OSL_TRACE("OUT MQueryHelper::~MQueryHelper()");
}

// -------------------------------------------------------------------------
void MQueryHelper::setAddressbook(OUString &ab)
{
    SAL_INFO("connectivity.mork", "MQueryHelper::setAddressbook()");

    ::osl::MutexGuard aGuard(m_aMutex);

    m_aAddressbook = ab;

    OSL_TRACE("\tOUT MQuery::setAddressbook()");
}
// -------------------------------------------------------------------------
void MQueryHelper::setExpression( MQueryExpression &_expr )
{
    SAL_INFO("connectivity.mork", "MQueryHelper::setExpression()");
    OSL_TRACE("IN MQueryHelper::setExpression()");
    ::osl::MutexGuard aGuard(m_aMutex);

    m_aExpr = _expr;

    OSL_TRACE("\tOUT MQuery::setExpression()");
}

void MQueryHelper::append(MQueryHelperResultEntry* resEnt)
{
//    SAL_INFO("connectivity.mork", "MQueryHelper::append()");

    if ( resEnt != NULL ) {
        m_aResults.push_back( resEnt );
        m_bAtEnd   = sal_False;
    }
}

void MQueryHelper::clear_results()
{
    resultsArray::iterator iter = m_aResults.begin();
    while ( iter != m_aResults.end() ) {
        delete (*iter);
        ++iter;
    }
    m_aResults.clear();
}

void MQueryHelper::reset()
{
    m_nIndex = 0;
    m_bHasMore = sal_True;
    m_bAtEnd = sal_False;
    clear_results();
    m_aError.reset();
}

MQueryHelperResultEntry*
MQueryHelper::getByIndex(sal_uInt32 nRow)
{
    // Row numbers are from 1 to N, need to ensure this, and then
    // substract 1
    if ( nRow < 1 ) {
        return( NULL );
    }
    return m_aResults[nRow -1];
}

sal_Int32 MQueryHelper::getResultCount() const
{
//    SAL_INFO("connectivity.mork", "MQueryHelper::getResultCount()" );
    sal_Int32 result = static_cast<sal_Int32>(m_aResults.size());
//    SAL_INFO("connectivity.mork", "result: " << result);

    return result;
}

// -------------------------------------------------------------------------

sal_Bool MQueryHelper::queryComplete() const
{
    return sal_True;
}

sal_Bool MQueryHelper::checkRowAvailable( sal_Int32 nDBRow )
{
/*
    while (!queryComplete() && getResultCount() <= (sal_uInt32)nDBRow)
    {
        if ( !m_aQueryHelper->waitForRow( nDBRow ) ) {
            m_aError = m_aQueryHelper->getError();
            return( sal_False );
        }
    }
*/
    return( getResultCount() > nDBRow );
}


sal_Bool MQueryHelper::getRowValue( ORowSetValue& rValue, sal_Int32 nDBRow,const OUString& aDBColumnName, sal_Int32 nType )
{
    SAL_INFO("connectivity.mork", "MQueryHelper::getRowValue()" );
    MQueryHelperResultEntry* xResEntry = getByIndex( nDBRow );

    OSL_ENSURE( xResEntry != NULL, "xResEntry == NULL");
    if (xResEntry == NULL )
    {
        rValue.setNull();
        return sal_False;
    }
    switch ( nType )
    {
        case DataType::VARCHAR:
            rValue = xResEntry->getValue( m_rColumnAlias.getProgrammaticNameOrFallbackToUTF8Alias( aDBColumnName ) );
            break;

        default:
            rValue.setNull();
            break;
    }

    return sal_True;
}

sal_Int32 MQueryHelper::executeQuery(OConnection* xConnection)
{
    SAL_INFO("connectivity.mork", "MQueryHelper::executeQuery()");
    reset();

    OString oStringTable = OUStringToOString( m_aAddressbook, RTL_TEXTENCODING_UTF8 );
    std::set<int> listRecords;
    bool handleListTable = false;
    MorkParser* xMork = xConnection->getMorkParser(oStringTable);

    // check if we are retrieving the default table
    if (oStringTable != "AddressBook" && oStringTable != "CollectedAddressBook")
    {
        handleListTable = true;
        // retrieve row ids for that list table
        std::string listTable = oStringTable.getStr();
        xMork->getRecordKeysForListTable(listTable, listRecords);
    }
    MorkTableMap::iterator tableIter;
    MorkTableMap *Tables = xMork->getTables( 0x80 );
    MorkRowMap *Rows = 0;
    MorkRowMap::iterator rowIter;

    // Iterate all tables
    for ( tableIter = Tables->begin(); tableIter != Tables->end(); ++tableIter )
    {
        if (tableIter->first != 1) break;
        Rows = xMork->getRows( 0x80, &tableIter->second );
        if ( Rows )
        {
            // Iterate all rows
            for ( rowIter = Rows->begin(); rowIter != Rows->end(); ++rowIter )
            {
                // list specific table
                // only retrieve rowIds that belong to that list table.
                if (handleListTable)
                {
                    int rowId = rowIter->first;
                    // belongs this row id to the list table?
                    if (listRecords.end() == std::find(listRecords.begin(), listRecords.end(), rowId))
                    {
                        // no, skip it
                        continue;
                    }
                }

                MQueryHelperResultEntry* entry = new MQueryHelperResultEntry();
                for (MorkCells::iterator CellsIter = rowIter->second.begin();
                     CellsIter != rowIter->second.end(); ++CellsIter )
                {
                    std::string column = xMork->getColumn(CellsIter->first);
                    std::string value = xMork->getValue(CellsIter->second);
                    OString key(column.c_str(), static_cast<sal_Int32>(column.size()));
                    OString valueOString(value.c_str(), static_cast<sal_Int32>(value.size()));
                    OUString valueOUString = OStringToOUString( valueOString, RTL_TEXTENCODING_UTF8 );
                    entry->setValue(key, valueOUString);
                }
                ::std::vector< sal_Bool > vector = entryMatchedByExpression(this, &m_aExpr, entry);
                sal_Bool result = sal_True;
                for (::std::vector<sal_Bool>::iterator iter = vector.begin(); iter != vector.end(); ++iter)
                {
                    result = result && *iter;
                }
                if (result)
                {
                    append(entry);
                }
                else
                {
                    delete entry;
                }
            }
        }
    }
    return 0;
}

::std::vector< sal_Bool > entryMatchedByExpression(MQueryHelper* _aQuery, MQueryExpression* _aExpr, MQueryHelperResultEntry* entry)
{
    ::std::vector< sal_Bool > resultVector;
    MQueryExpression::ExprVector::iterator evIter;
    for( evIter = _aExpr->getExpressions().begin();
         evIter != _aExpr->getExpressions().end();
         ++evIter )
    {
        if ( (*evIter)->isStringExpr() ) {
            MQueryExpressionString* evStr = static_cast<MQueryExpressionString*> (*evIter);
            // Set the 'name' property of the boolString.
            OString attrName = _aQuery->getColumnAlias().getProgrammaticNameOrFallbackToUTF8Alias( evStr->getName() );
            SAL_INFO("connectivity.mork", "Name = " << attrName.getStr());
            sal_Bool requiresValue = sal_True;
            OUString currentValue = entry->getValue(attrName);
            if (evStr->getCond() == MQueryOp::Exists || evStr->getCond() == MQueryOp::DoesNotExist)
            {
                requiresValue = sal_False;
            }
            if (requiresValue)
            {
                SAL_INFO("connectivity.mork", "Value = " << evStr->getValue() );
                OUString searchedValue = evStr->getValue();
                if (evStr->getCond() == MQueryOp::Is) {
                    SAL_INFO("connectivity.mork", "MQueryOp::Is; done");
                    resultVector.push_back((currentValue == searchedValue) ? sal_True : sal_False);
                } else if (evStr->getCond() == MQueryOp::IsNot) {
                    SAL_INFO("connectivity.mork", "MQueryOp::IsNot; done");
                    resultVector.push_back((currentValue == searchedValue) ? sal_False : sal_True);
                } else if (evStr->getCond() == MQueryOp::EndsWith) {
                    SAL_INFO("connectivity.mork", "MQueryOp::EndsWith; done");
                    resultVector.push_back((currentValue.endsWith(searchedValue)) ? sal_True : sal_False);
                } else if (evStr->getCond() == MQueryOp::BeginsWith) {
                    SAL_INFO("connectivity.mork", "MQueryOp::BeginsWith; done");
                    resultVector.push_back((currentValue.startsWith(searchedValue)) ? sal_True : sal_False);
                } else if (evStr->getCond() == MQueryOp::Contains) {
                    SAL_INFO("connectivity.mork", "MQueryOp::Contains; done");
                    resultVector.push_back((currentValue.indexOf(searchedValue) == -1) ? sal_False : sal_True);
                } else if (evStr->getCond() == MQueryOp::DoesNotContain) {
                    SAL_INFO("connectivity.mork", "MQueryOp::DoesNotContain; done");
                    resultVector.push_back((currentValue.indexOf(searchedValue) == -1) ? sal_True : sal_False);
                } else if (evStr->getCond() == MQueryOp::RegExp) {
                    SAL_INFO("connectivity.mork", "MQueryOp::RegExp; done");
                    utl::SearchParam param(
                        searchedValue, utl::SearchParam::SRCH_REGEXP);
                    utl::TextSearch ts(param, LANGUAGE_DONTKNOW);
                    sal_Int32 start = 0;
                    sal_Int32 end = currentValue.getLength();
                    resultVector.push_back(
                        ts.SearchForward(currentValue, &start, &end));
                }
            } else if (evStr->getCond() == MQueryOp::Exists) {
                SAL_INFO("connectivity.mork", "MQueryOp::Exists; done");
                resultVector.push_back((currentValue.isEmpty()) ? sal_False : sal_True);
            } else if (evStr->getCond() == MQueryOp::DoesNotExist) {
                SAL_INFO("connectivity.mork", "MQueryOp::DoesNotExist; done");
                resultVector.push_back((currentValue.isEmpty()) ? sal_True : sal_False);
            }
        }
        else if ( (*evIter)->isExpr() ) {
            SAL_INFO("connectivity.mork", "Appending Subquery Expression");
            MQueryExpression* queryExpression = static_cast<MQueryExpression*> (*evIter);
            // recursive call
            ::std::vector<sal_Bool> subquery_result = entryMatchedByExpression(_aQuery, queryExpression, entry);
            MQueryExpression::bool_cond condition = queryExpression->getExpressionCondition();
            if (condition == MQueryExpression::OR) {
                sal_Bool result = sal_False;
                for (::std::vector<sal_Bool>::iterator iter =  subquery_result.begin(); iter != subquery_result.end(); ++iter) {
                    result = result || *iter;
                }
                resultVector.push_back(result);
            } else if (condition == MQueryExpression::AND) {
                sal_Bool result = sal_True;
                for (::std::vector<sal_Bool>::iterator iter = subquery_result.begin(); iter != subquery_result.end(); ++iter) {
                    result = result && *iter;
                }
                resultVector.push_back(result);
            } else {
                OSL_FAIL("Unknown Expression Type");
            }
        }
        else {
            // Should never see this...
            SAL_WARN("connectivity.mork", "Unknown Expression Type!");
            _aQuery->getError().setResId(STR_ERROR_GET_ROW);
            return resultVector;
        }
    }
    return resultVector;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */