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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
|
/* This file is part of the KDE project
Copyright (C) 2003-2006 Jaroslaw Staniek <js@iidea.pl>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This program 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "sqlitecursor.h"
#include "sqliteconnection.h"
#include "sqliteconnection_p.h"
#include <kexidb/error.h>
#include <kexidb/driver.h>
#include <kexiutils/utils.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <kdebug.h>
#include <klocale.h>
#include <tqptrvector.h>
#include <tqdatetime.h>
using namespace KexiDB;
//! safer interpretations of boolean values for SQLite
static bool sqliteStringToBool(const TQString& s)
{
return s.lower()=="yes" || (s.lower()!="no" && s!="0");
}
//----------------------------------------------------
class KexiDB::SQLiteCursorData : public SQLiteConnectionInternal
{
public:
SQLiteCursorData(Connection* conn)
:
SQLiteConnectionInternal(conn)
// : curr_cols(0)
// errmsg_p(0)
// , res(SQLITE_OK)
, curr_coldata(0)
, curr_colname(0)
, cols_pointers_mem_size(0)
// , rec_stored(false)
/* MOVED TO Cursor:
, cols_pointers_mem_size(0)
, records_in_buf(0)
, buffering_completed(false)
, at_buffer(false)*/
//#ifdef SQLITE3
// , rowDataReadyToFetch(false)
//#endif
{
data_owned = false;
}
/*#ifdef SQLITE3
void fetchRowDataIfNeeded()
{
if (!rowDataReadyToFetch)
return true;
rowDataReadyToFetch = false;
m_fieldCount = sqlite3_data_count(data);
for (int i=0; i<m_fieldCount; i++) {
}
}
#endif*/
TQCString st;
//for sqlite:
// sqlite_struct *data; //! taken from SQLiteConnection
#ifdef SQLITE2
sqlite_vm *prepared_st_handle; //vm
#else //SQLITE3
sqlite3_stmt *prepared_st_handle;
#endif
char *utail;
// TQString errmsg; //<! server-specific message of last operation
// char *errmsg_p; //<! temporary: server-specific message of last operation
// int res; //<! result code of last operation on server
// int curr_cols;
const char **curr_coldata;
const char **curr_colname;
int next_cols;
// const char **next_coldata;
// const char **next_colname;
// bool rec_stored : 1; //! true, current record is stored in next_coldata
/* MOVED TO Cursor:
uint cols_pointers_mem_size; //! size of record's array of pointers to values
int records_in_buf; //! number of records currently stored in the buffer
bool buffering_completed; //! true if we have already all records stored in the buffer
TQPtrVector<const char*> records; //buffer data
bool at_buffer; //! true if we already point to the buffer with curr_coldata
*/
/* int prev_cols;
const char **prev_coldata;
const char **prev_colname;*/
uint cols_pointers_mem_size; //! size of record's array of pointers to values
TQPtrVector<const char*> records;//! buffer data
//#ifdef SQLITE3
// bool rowDataReadyToFetch : 1;
//#endif
#ifdef SQLITE3
inline TQVariant getValue(Field *f, int i)
{
int type = sqlite3_column_type(prepared_st_handle, i);
if (type==SQLITE_NULL) {
return TQVariant();
}
else if (!f || type==SQLITE_TEXT) {
//TODO: support for UTF-16
#define GET_sqlite3_column_text TQString::fromUtf8( (const char*)sqlite3_column_text(prepared_st_handle, i) )
if (!f || f->isTextType())
return GET_sqlite3_column_text;
else {
switch (f->type()) {
case Field::Date:
return TQDate::fromString( GET_sqlite3_column_text, Qt::ISODate );
case Field::Time:
//TQDateTime - a hack needed because TQVariant(TQTime) has broken isNull()
return KexiUtils::stringToHackedTQTime(GET_sqlite3_column_text);
case Field::DateTime: {
TQString tmp( GET_sqlite3_column_text );
tmp[10] = 'T'; //for ISODate compatibility
return TQDateTime::fromString( tmp, Qt::ISODate );
}
case Field::Boolean:
return TQVariant(sqliteStringToBool(GET_sqlite3_column_text), 1);
default:
return TQVariant(); //TODO
}
}
}
else if (type==SQLITE_INTEGER) {
switch (f->type()) {
case Field::Byte:
case Field::ShortInteger:
case Field::Integer:
return TQVariant( sqlite3_column_int(prepared_st_handle, i) );
case Field::BigInteger:
return TQVariant( (TQ_LLONG)sqlite3_column_int64(prepared_st_handle, i) );
case Field::Boolean:
return TQVariant( sqlite3_column_int(prepared_st_handle, i)!=0, 1 );
default:;
}
if (f->isFPNumericType()) //WEIRD, YEAH?
return TQVariant( (double)sqlite3_column_int(prepared_st_handle, i) );
else
return TQVariant(); //TODO
}
else if (type==SQLITE_FLOAT) {
if (f && f->isFPNumericType())
return TQVariant( sqlite3_column_double(prepared_st_handle, i) );
else if (!f || f->isIntegerType())
return TQVariant( (double)sqlite3_column_double(prepared_st_handle, i) );
else
return TQVariant(); //TODO
}
else if (type==SQLITE_BLOB) {
if (f && f->type()==Field::BLOB) {
TQByteArray ba;
//! @todo efficient enough?
ba.duplicate((const char*)sqlite3_column_blob(prepared_st_handle, i),
sqlite3_column_bytes(prepared_st_handle, i));
return ba;
} else
return TQVariant(); //TODO
}
return TQVariant();
}
#endif //SQLITE3
};
SQLiteCursor::SQLiteCursor(Connection* conn, const TQString& statement, uint options)
: Cursor( conn, statement, options )
, d( new SQLiteCursorData(conn) )
{
d->data = static_cast<SQLiteConnection*>(conn)->d->data;
}
SQLiteCursor::SQLiteCursor(Connection* conn, QuerySchema& query, uint options )
: Cursor( conn, query, options )
, d( new SQLiteCursorData(conn) )
{
d->data = static_cast<SQLiteConnection*>(conn)->d->data;
}
SQLiteCursor::~SQLiteCursor()
{
close();
delete d;
}
bool SQLiteCursor::drv_open()
{
// d->st.resize(statement.length()*2);
//TODO: decode
// d->st = statement.local8Bit();
// d->st = m_conn->driver()->escapeString( statement.local8Bit() );
if(! d->data) {
// this may as example be the case if SQLiteConnection::drv_useDatabase()
// wasn't called before. Normaly sqlite_compile/sqlite3_prepare
// should handle it, but it crashes in in sqlite3SafetyOn at util.c:786
kdWarning() << "SQLiteCursor::drv_open(): Database handle undefined." << endl;
return false;
}
#ifdef SQLITE2
d->st = m_sql.local8Bit();
d->res = sqlite_compile(
d->data,
d->st.data(),
(const char**)&d->utail,
&d->prepared_st_handle,
&d->errmsg_p );
#else //SQLITE3
d->st = m_sql.utf8();
d->res = sqlite3_prepare(
d->data, /* Database handle */
d->st.data(), /* SQL statement, UTF-8 encoded */
d->st.length(), /* Length of zSql in bytes. */
&d->prepared_st_handle, /* OUT: Statement handle */
0/*const char **pzTail*/ /* OUT: Pointer to unused portion of zSql */
);
#endif
if (d->res!=SQLITE_OK) {
d->storeResult();
return false;
}
//cursor is automatically @ first record
// m_beforeFirst = true;
if (isBuffered()) {
d->records.resize(128); //TODO: manage size dynamically
}
return true;
}
/*bool SQLiteCursor::drv_getFirstRecord()
{
bool ok = drv_getNextRecord();*/
/* if ((m_options & Buffered) && ok) { //1st record is there:
//compute parameters for cursor's buffer:
//-size of record's array of pointer to values
d->cols_pointers_mem_size = d->curr_cols * sizeof(char*);
d->records_in_buf = 1;
}*/
/*return ok;
}*/
bool SQLiteCursor::drv_close()
{
#ifdef SQLITE2
d->res = sqlite_finalize( d->prepared_st_handle, &d->errmsg_p );
#else //SQLITE3
d->res = sqlite3_finalize( d->prepared_st_handle );
#endif
if (d->res!=SQLITE_OK) {
d->storeResult();
return false;
}
return true;
}
void SQLiteCursor::drv_getNextRecord()
{
#ifdef SQLITE2
static int _fieldCount;
d->res = sqlite_step(
d->prepared_st_handle,
&_fieldCount,
&d->curr_coldata,
&d->curr_colname);
#else //SQLITE3
d->res = sqlite3_step( d->prepared_st_handle );
#endif
if (d->res == SQLITE_ROW) {
m_result = FetchOK;
#ifdef SQLITE2
m_fieldCount = (uint)_fieldCount;
#else
m_fieldCount = sqlite3_data_count(d->prepared_st_handle);
//#else //for SQLITE3 data fetching is delayed. Now we even do not take field count information
// // -- just set a flag that we've a data not fetched but available
// d->rowDataReadyToFetch = true;
#endif
//(m_logicalFieldCount introduced) m_fieldCount -= (m_containsROWIDInfo ? 1 : 0);
} else {
//#ifdef SQLITE3
// d->rowDataReadyToFetch = false;
//#endif
if (d->res==SQLITE_DONE)
m_result = FetchEnd;
else
m_result = FetchError;
}
//debug
/* if (((int)m_result == (int)FetchOK) && d->curr_coldata) {
for (uint i=0;i<m_fieldCount;i++) {
KexiDBDrvDbg<<"col."<< i<<": "<< d->curr_colname[i]<<" "<< d->curr_colname[m_fieldCount+i]
<< " = " << (d->curr_coldata[i] ? TQString::fromLocal8Bit(d->curr_coldata[i]) : "(NULL)") <<endl;
}
KexiDBDrvDbg << "SQLiteCursor::drv_getNextRecord(): "<<m_fieldCount<<" col(s) fetched"<<endl;
}*/
}
void SQLiteCursor::drv_appendCurrentRecordToBuffer()
{
// KexiDBDrvDbg << "SQLiteCursor::drv_appendCurrentRecordToBuffer():" <<endl;
if (!d->curr_coldata)
return;
if (!d->cols_pointers_mem_size)
d->cols_pointers_mem_size = m_fieldCount * sizeof(char*);
const char **record = (const char**)malloc(d->cols_pointers_mem_size);
const char **src_col = d->curr_coldata;
const char **dest_col = record;
for (uint i=0; i<m_fieldCount; i++,src_col++,dest_col++) {
// KexiDBDrvDbg << i <<": '" << *src_col << "'" <<endl;
// KexiDBDrvDbg << "src_col: " << src_col << endl;
*dest_col = *src_col ? strdup(*src_col) : 0;
}
d->records.insert(m_records_in_buf,record);
// KexiDBDrvDbg << "SQLiteCursor::drv_appendCurrentRecordToBuffer() ok." <<endl;
}
void SQLiteCursor::drv_bufferMovePointerNext()
{
d->curr_coldata++; //move to next record in the buffer
}
void SQLiteCursor::drv_bufferMovePointerPrev()
{
d->curr_coldata--; //move to prev record in the buffer
}
//compute a place in the buffer that contain next record's data
//and move internal buffer pointer to that place
void SQLiteCursor::drv_bufferMovePointerTo(TQ_LLONG at)
{
d->curr_coldata = d->records.at(at);
}
void SQLiteCursor::drv_clearBuffer()
{
if (d->cols_pointers_mem_size>0) {
const uint records_in_buf = m_records_in_buf;
const char ***r_ptr = d->records.data();
for (uint i=0; i<records_in_buf; i++, r_ptr++) {
// const char **record = m_records.at(i);
const char **field_data = *r_ptr;
// for (int col=0; col<d->curr_cols; col++, field_data++) {
for (uint col=0; col<m_fieldCount; col++, field_data++) {
free((void*)*field_data); //free field memory
}
free(*r_ptr); //free pointers to fields array
}
}
// d->curr_cols=0;
// m_fieldCount=0;
m_records_in_buf=0;
d->cols_pointers_mem_size=0;
// m_at_buffer=false;
d->records.clear();
}
/*
void SQLiteCursor::drv_storeCurrentRecord()
{
#if 0
assert(!m_data->rec_stored);
m_data->rec_stored = true;
m_data->next_cols = m_data->curr_cols;
for (int i=0;i<m_data->curr_cols;i++) {
KexiDBDrvDbg<<"[COPY] "<<i<<": "<< m_data->curr_coldata[i]<<endl;
if (m_data->curr_coldata[i])
m_data->next_coldata[i] = strdup( m_data->curr_coldata[i] );
else
m_data->next_coldata[i] = 0;
}
#endif
}
*/
/*TODO
const char *** SQLiteCursor::bufferData()
{
if (!isBuffered())
return 0;
return m_records.data();
}*/
const char ** SQLiteCursor::rowData() const
{
return d->curr_coldata;
}
void SQLiteCursor::storeCurrentRow(RowData &data) const
{
#ifdef SQLITE2
const char **col = d->curr_coldata;
#endif
//const uint realCount = m_fieldCount + (m_containsROWIDInfo ? 1 : 0);
data.resize(m_fieldCount);
if (!m_fieldsExpanded) {//simple version: without types
for( uint i=0; i<m_fieldCount; i++ ) {
#ifdef SQLITE2
data[i] = TQVariant( *col );
col++;
#else //SQLITE3
data[i] = TQString::fromUtf8( (const char*)sqlite3_column_text(d->prepared_st_handle, i) );
#endif
}
return;
}
//const uint fieldsExpandedCount = m_fieldsExpanded->count();
const uint maxCount = TQMIN(m_fieldCount, m_fieldsExpanded->count());
// i - visible field's index, j - physical index
for( uint i=0, j=0; i<m_fieldCount; i++, j++ ) {
// while (j < m_detailedVisibility.count() && !m_detailedVisibility[j]) //!m_query->isColumnVisible(j))
// j++;
while (j < maxCount && !m_fieldsExpanded->at(j)->visible)
j++;
if (j >= (maxCount /*+(m_containsROWIDInfo ? 1 : 0)*/)) {
//ERR!
break;
}
//(m_logicalFieldCount introduced) Field *f = (m_containsROWIDInfo && i>=m_fieldCount) ? 0 : m_fieldsExpanded->at(j)->field;
Field *f = (i>=m_fieldCount) ? 0 : m_fieldsExpanded->at(j)->field;
// KexiDBDrvDbg << "SQLiteCursor::storeCurrentRow(): col=" << (col ? *col : 0) << endl;
#ifdef SQLITE2
if (!*col)
data[i] = TQVariant();
else if (f && f->isTextType())
# ifdef SQLITE_UTF8
data[i] = TQString::fromUtf8( *col );
# else
data[i] = TQVariant( *col ); //only latin1
# endif
else if (f && f->isFPNumericType())
data[i] = TQVariant( TQCString(*col).toDouble() );
else {
switch (f ? f->type() : Field::Integer/*ROWINFO*/) {
//todo: use short, etc.
case Field::Byte:
case Field::ShortInteger:
case Field::Integer:
data[i] = TQVariant( TQCString(*col).toInt() );
case Field::BigInteger:
data[i] = TQVariant( TQString::fromLatin1(*col).toLongLong() );
case Field::Boolean:
data[i] = TQVariant( sqliteStringToBool(TQString::fromLatin1(*col)), 1 );
break;
case Field::Date:
data[i] = TQDate::fromString( TQString::fromLatin1(*col), Qt::ISODate );
break;
case Field::Time:
//TQDateTime - a hack needed because TQVariant(TQTime) has broken isNull()
data[i] = KexiUtils::stringToHackedTQTime(TQString::fromLatin1(*col));
break;
case Field::DateTime: {
TQString tmp( TQString::fromLatin1(*col) );
tmp[10] = 'T';
data[i] = TQDateTime::fromString( tmp, Qt::ISODate );
break;
}
default:
data[i] = TQVariant( *col );
}
}
col++;
#else //SQLITE3
data[i] = d->getValue(f, i); //, !f /*!f means ROWID*/);
#endif
}
}
TQVariant SQLiteCursor::value(uint i)
{
// if (i > (m_fieldCount-1+(m_containsROWIDInfo?1:0))) //range checking
if (i > (m_fieldCount-1)) //range checking
return TQVariant();
//TODO: allow disable range checking! - performance reasons
// const KexiDB::Field *f = m_query ? m_query->field(i) : 0;
KexiDB::Field *f = (m_fieldsExpanded && i<m_fieldsExpanded->count())
? m_fieldsExpanded->at(i)->field : 0;
#ifdef SQLITE2
//from most to least frequently used types:
//(m_logicalFieldCount introduced) if (i==m_fieldCount || f && f->isIntegerType())
if (!f || f->isIntegerType())
return TQVariant( TQCString(d->curr_coldata[i]).toInt() );
else if (!f || f->isTextType())
return TQVariant( d->curr_coldata[i] );
else if (f->isFPNumericType())
return TQVariant( TQCString(d->curr_coldata[i]).toDouble() );
return TQVariant( d->curr_coldata[i] ); //default
#else
return d->getValue(f, i); //, i==m_logicalFieldCount/*ROWID*/);
#endif
}
/*! Stores string value taken from field number \a i to \a str.
\return false when range checking failed.
bool SQLiteCursor::storeStringValue(uint i, TQString &str)
{
if (i > (m_fieldCount-1)) //range checking
return false;
str = d->curr_coldata[i];
return true;
}*/
int SQLiteCursor::serverResult()
{
return d->res;
}
TQString SQLiteCursor::serverResultName()
{
#ifdef SQLITE2
return TQString::fromLatin1( sqlite_error_string(d->res) );
#else //SQLITE3
return TQString::fromLatin1( d->result_name );
#endif
}
TQString SQLiteCursor::serverErrorMsg()
{
return d->errmsg;
}
void SQLiteCursor::drv_clearServerResult()
{
d->res = SQLITE_OK;
d->errmsg_p = 0;
}
|