~oif-team/ubuntu/natty/qt4-x11/xi2.1

« back to all changes in this revision

Viewing changes to src/qt3support/sql/q3sqlcursor.cpp

  • Committer: Bazaar Package Importer
  • Author(s): Adam Conrad
  • Date: 2005-08-24 04:09:09 UTC
  • Revision ID: james.westby@ubuntu.com-20050824040909-xmxe9jfr4a0w5671
Tags: upstream-4.0.0
ImportĀ upstreamĀ versionĀ 4.0.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/****************************************************************************
 
2
**
 
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
 
4
**
 
5
** This file is part of the Qt 3 compatibility classes of the Qt Toolkit.
 
6
**
 
7
** This file may be distributed under the terms of the Q Public License
 
8
** as defined by Trolltech AS of Norway and appearing in the file
 
9
** LICENSE.QPL included in the packaging of this file.
 
10
**
 
11
** This file may be distributed and/or modified under the terms of the
 
12
** GNU General Public License version 2 as published by the Free Software
 
13
** Foundation and appearing in the file LICENSE.GPL included in the
 
14
** packaging of this file.
 
15
**
 
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
 
17
**   information about Qt Commercial License Agreements.
 
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
 
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
 
20
**
 
21
** Contact info@trolltech.com if any conditions of this licensing are
 
22
** not clear to you.
 
23
**
 
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 
26
**
 
27
****************************************************************************/
 
28
 
 
29
#include <qplatformdefs.h>
 
30
#include "q3sqlcursor.h"
 
31
 
 
32
#ifndef QT_NO_SQL
 
33
 
 
34
#include "qsqldriver.h"
 
35
#include "qsqlresult.h"
 
36
#include "qdatetime.h"
 
37
#include "qsqldatabase.h"
 
38
#include "qsql.h"
 
39
#include "q3sqlrecordinfo.h"
 
40
#include "q3sqlfieldinfo.h"
 
41
 
 
42
class Q3SqlCursorPrivate
 
43
{
 
44
public:
 
45
 
 
46
    Q3SqlCursorPrivate(const QString& name, QSqlDatabase sdb)
 
47
        : lastAt(QSql::BeforeFirst), nm(name), srt(name), md(0), db(sdb), q(0)
 
48
    {}
 
49
    ~Q3SqlCursorPrivate()
 
50
    {
 
51
        delete q;
 
52
    }
 
53
 
 
54
    QSqlQuery* query()
 
55
    {
 
56
        if (!q)
 
57
            q = new QSqlQuery(QString(), db);
 
58
        return q;
 
59
    }
 
60
 
 
61
    int lastAt;
 
62
    QString nm;         //name
 
63
    QSqlIndex srt;        //sort
 
64
    QString ftr;        //filter
 
65
    int md;         //mode
 
66
    QSqlIndex priIndx;    //primary index
 
67
    QSqlRecord editBuffer;
 
68
    // the primary index as it was before the user changed the values in editBuffer
 
69
    QString editIndex;
 
70
    Q3SqlRecordInfo infoBuffer;
 
71
    QSqlDatabase db;
 
72
    QSqlQuery *q;
 
73
};
 
74
 
 
75
QString qOrderByClause(const QSqlIndex & i, const QString& prefix = QString())
 
76
{
 
77
    QString str;
 
78
    int k = i.count();
 
79
    if(k == 0)
 
80
        return QString();
 
81
    str = " order by " + i.toString(prefix);
 
82
    return str;
 
83
}
 
84
 
 
85
QString qWhereClause(const QString& prefix, QSqlField* field, const QSqlDriver* driver)
 
86
{
 
87
    QString f;
 
88
    if (field && driver) {
 
89
        if (!prefix.isEmpty())
 
90
            f += prefix + QString(".");
 
91
        f += field->name();
 
92
        if (field->isNull()) {
 
93
            f += " IS NULL";
 
94
        } else {
 
95
            f += " = " + driver->formatValue(field);
 
96
        }
 
97
    }
 
98
    return f;
 
99
}
 
100
 
 
101
QString qWhereClause(QSqlRecord* rec, const QString& prefix, const QString& sep,
 
102
                      const QSqlDriver* driver)
 
103
{
 
104
    static QString blank(" ");
 
105
    QString filter;
 
106
    bool separator = false;
 
107
    for (int j = 0; j < rec->count(); ++j) {
 
108
        QSqlField f = rec->field(j);
 
109
        if (rec->isGenerated(j)) {
 
110
            if (separator)
 
111
                filter += sep + blank;
 
112
            filter += qWhereClause(prefix, &f, driver);
 
113
            filter += blank;
 
114
            separator = true;
 
115
        }
 
116
    }
 
117
    return filter;
 
118
}
 
119
 
 
120
/*!
 
121
    \class Q3SqlCursor q3sqlcursor.h
 
122
    \brief The Q3SqlCursor class provides browsing and editing of SQL
 
123
    tables and views.
 
124
 
 
125
    \compat
 
126
 
 
127
    A Q3SqlCursor is a database record (see \l QSqlRecord) that
 
128
    corresponds to a table or view within an SQL database (see \l
 
129
    QSqlDatabase). There are two buffers in a cursor, one used for
 
130
    browsing and one used for editing records. Each buffer contains a
 
131
    list of fields which correspond to the fields in the table or
 
132
    view.
 
133
 
 
134
    When positioned on a valid record, the browse buffer contains the
 
135
    values of the current record's fields from the database. The edit
 
136
    buffer is separate, and is used for editing existing records and
 
137
    inserting new records.
 
138
 
 
139
    For browsing data, a cursor must first select() data from the
 
140
    database. After a successful select() the cursor is active
 
141
    (isActive() returns true), but is initially not positioned on a
 
142
    valid record (isValid() returns false). To position the cursor on
 
143
    a valid record, use one of the navigation functions, next(),
 
144
    previous(), first(), last(), or seek(). Once positioned on a valid
 
145
    record, data can be retrieved from the browse buffer using
 
146
    value(). If a navigation function is not successful, it returns
 
147
    false, the cursor will no longer be positioned on a valid record
 
148
    and the values returned by value() are undefined.
 
149
 
 
150
    For example:
 
151
 
 
152
    \code
 
153
    Q3SqlCursor cur( "staff" ); // Specify the table/view name
 
154
    cur.select(); // We'll retrieve every record
 
155
    while ( cur.next() ) {
 
156
        qDebug( cur.value( "id" ).toString() + ": " +
 
157
        cur.value( "surname" ).toString() + " " +
 
158
        cur.value( "salary" ).toString() );
 
159
    }
 
160
    \endcode
 
161
 
 
162
    In the above example, a cursor is created specifying a table or
 
163
    view name in the database. Then, select() is called, which can be
 
164
    optionally parameterised to filter and order the records
 
165
    retrieved. Each record in the cursor is retrieved using next().
 
166
    When next() returns false, there are no more records to process,
 
167
    and the loop terminates.
 
168
 
 
169
    For editing records (rows of data), a cursor contains a separate
 
170
    edit buffer which is independent of the fields used when browsing.
 
171
    The functions insert(), update() and del() operate on the edit
 
172
    buffer. This allows the cursor to be repositioned to other
 
173
    records while simultaneously maintaining a separate buffer for
 
174
    edits. You can get a pointer to the edit buffer using
 
175
    editBuffer(). The primeInsert(), primeUpdate() and primeDelete()
 
176
    functions also return a pointer to the edit buffer and prepare it
 
177
    for insert, update and delete respectively. Edit operations only
 
178
    affect a single row at a time. Note that update() and del()
 
179
    require that the table or view contain a primaryIndex() to ensure
 
180
    that edit operations affect a unique record within the database.
 
181
 
 
182
    For example:
 
183
 
 
184
    \code
 
185
    Q3SqlCursor cur( "prices" );
 
186
    cur.select( "id=202" );
 
187
    if ( cur.next() ) {
 
188
        QSqlRecord *buffer = cur.primeUpdate();
 
189
        double price = buffer->value( "price" ).toDouble();
 
190
        double newprice = price * 1.05;
 
191
        buffer->setValue( "price", newprice );
 
192
        cur.update();
 
193
    }
 
194
    \endcode
 
195
 
 
196
    To edit an existing database record, first move to the record you
 
197
    wish to update. Call primeUpdate() to get the pointer to the
 
198
    cursor's edit buffer. Then use this pointer to modify the values
 
199
    in the edit buffer. Finally, call update() to save the changes to
 
200
    the database. The values in the edit buffer will be used to
 
201
    locate the appropriate record when updating the database (see
 
202
    primaryIndex()).
 
203
 
 
204
    Similarly, when deleting an existing database record, first move
 
205
    to the record you wish to delete. Then, call primeDelete() to get
 
206
    the pointer to the edit buffer. Finally, call del() to delete the
 
207
    record from the database. Again, the values in the edit buffer
 
208
    will be used to locate and delete the appropriate record.
 
209
 
 
210
    To insert a new record, call primeInsert() to get the pointer to
 
211
    the edit buffer. Use this pointer to populate the edit buffer
 
212
    with new values and then insert() the record into the database.
 
213
 
 
214
    After calling insert(), update() or del(), the cursor is no longer
 
215
    positioned on a valid record and can no longer be navigated
 
216
    (isValid() return false). The reason for this is that any changes
 
217
    made to the database will not be visible until select() is called
 
218
    to refresh the cursor. You can change this behavior by passing
 
219
    false to insert(), update() or del() which will prevent the cursor
 
220
    from becoming invalid. The edits will still not be visible when
 
221
    navigating the cursor until select() is called.
 
222
 
 
223
    Q3SqlCursor contains virtual methods which allow editing behavior
 
224
    to be customized by subclasses. This allows custom cursors to be
 
225
    created that encapsulate the editing behavior of a database table
 
226
    for an entire application. For example, a cursor can be customized
 
227
    to always auto-number primary index fields, or provide fields with
 
228
    suitable default values, when inserting new records. Q3SqlCursor
 
229
    generates SQL statements which are sent to the database engine;
 
230
    you can control which fields are included in these statements
 
231
    using setGenerated().
 
232
 
 
233
    Note that Q3SqlCursor does not inherit from QObject. This means
 
234
    that you are responsible for destroying instances of this class
 
235
    yourself. However if you create a Q3SqlCursor and use it in a
 
236
    \l Q3DataTable, \l Q3DataBrowser or a \l Q3DataView these classes will
 
237
    usually take ownership of the cursor and destroy it when they
 
238
    don't need it anymore. The documentation for Q3DataTable,
 
239
    Q3DataBrowser and Q3DataView explicitly states which calls take
 
240
    ownership of the cursor.
 
241
*/
 
242
 
 
243
/*!
 
244
    \enum Q3SqlCursor::Mode
 
245
 
 
246
    This enum type describes how Q3SqlCursor operates on records in the
 
247
    database.
 
248
 
 
249
    \value ReadOnly  the cursor can only SELECT records from the
 
250
    database.
 
251
 
 
252
    \value Insert  the cursor can INSERT records into the database.
 
253
 
 
254
    \value Update  the cursor can UPDATE records in the database.
 
255
 
 
256
    \value Delete  the cursor can DELETE records from the database.
 
257
 
 
258
    \value Writable  the cursor can INSERT, UPDATE and DELETE records
 
259
    in the database.
 
260
*/
 
261
 
 
262
/*!
 
263
    \fn QVariant Q3SqlCursor::value(const QString &name) const
 
264
 
 
265
    \overload
 
266
 
 
267
    Returns the value of the field named \a name.
 
268
*/
 
269
 
 
270
/*!
 
271
    \fn void Q3SqlCursor::setValue(const QString &name, const QVariant &val)
 
272
 
 
273
    \overload
 
274
 
 
275
    Sets the value for the field named \a name to \a val.
 
276
*/
 
277
 
 
278
/*!
 
279
    Constructs a cursor on database \a db using table or view \a name.
 
280
 
 
281
    If \a autopopulate is true (the default), the \a name of the
 
282
    cursor must correspond to an existing table or view name in the
 
283
    database so that field information can be automatically created.
 
284
    If the table or view does not exist, the cursor will not be
 
285
    functional.
 
286
 
 
287
    The cursor is created with an initial mode of Q3SqlCursor::Writable
 
288
    (meaning that records can be inserted, updated or deleted using
 
289
    the cursor). If the cursor does not have a unique primary index,
 
290
    update and deletes cannot be performed.
 
291
 
 
292
    Note that \a autopopulate refers to populating the cursor with
 
293
    meta-data, e.g. the names of the table's fields, not with
 
294
    retrieving data. The select() function is used to populate the
 
295
    cursor with data.
 
296
 
 
297
    \sa setName() setMode()
 
298
*/
 
299
 
 
300
Q3SqlCursor::Q3SqlCursor(const QString & name, bool autopopulate, QSqlDatabase db)
 
301
    : QSqlRecord(), QSqlQuery(QString(), db)
 
302
{
 
303
    d = new Q3SqlCursorPrivate(name, db);
 
304
    setMode(Writable);
 
305
    if (!d->nm.isEmpty())
 
306
        setName(d->nm, autopopulate);
 
307
}
 
308
 
 
309
/*!
 
310
    Constructs a copy of \a other.
 
311
*/
 
312
 
 
313
Q3SqlCursor::Q3SqlCursor(const Q3SqlCursor & other)
 
314
    : QSqlRecord(other), QSqlQuery(other)
 
315
{
 
316
    d = new Q3SqlCursorPrivate(other.d->nm, other.d->db);
 
317
    d->lastAt = other.d->lastAt;
 
318
    d->nm = other.d->nm;
 
319
    d->srt = other.d->srt;
 
320
    d->ftr = other.d->ftr;
 
321
    d->priIndx = other.d->priIndx;
 
322
    d->editBuffer = other.d->editBuffer;
 
323
    d->infoBuffer = other.d->infoBuffer;
 
324
    d->q = 0; // do not share queries
 
325
    setMode(other.mode());
 
326
}
 
327
 
 
328
/*!
 
329
    Destroys the object and frees any allocated resources.
 
330
*/
 
331
 
 
332
Q3SqlCursor::~Q3SqlCursor()
 
333
{
 
334
    delete d;
 
335
}
 
336
 
 
337
/*!
 
338
    Sets the cursor equal to \a other.
 
339
*/
 
340
 
 
341
Q3SqlCursor& Q3SqlCursor::operator=(const Q3SqlCursor& other)
 
342
{
 
343
    QSqlRecord::operator=(other);
 
344
    QSqlQuery::operator=(other);
 
345
    delete d;
 
346
    d = new Q3SqlCursorPrivate(other.d->nm, other.d->db);
 
347
    d->lastAt = other.d->lastAt;
 
348
    d->nm = other.d->nm;
 
349
    d->srt = other.d->srt;
 
350
    d->ftr = other.d->ftr;
 
351
    d->priIndx = other.d->priIndx;
 
352
    d->editBuffer = other.d->editBuffer;
 
353
    d->infoBuffer = other.d->infoBuffer;
 
354
    d->q = 0; // do not share queries
 
355
    setMode(other.mode());
 
356
    return *this;
 
357
}
 
358
 
 
359
/*!
 
360
    Sets the current sort to \a sort. Note that no new records are
 
361
    selected. To select new records, use select(). The \a sort will
 
362
    apply to any subsequent select() calls that do not explicitly
 
363
    specify a sort.
 
364
*/
 
365
 
 
366
void Q3SqlCursor::setSort(const QSqlIndex& sort)
 
367
{
 
368
    d->srt = sort;
 
369
}
 
370
 
 
371
/*!
 
372
    Returns the current sort, or an empty index if there is no current
 
373
    sort.
 
374
*/
 
375
QSqlIndex Q3SqlCursor::sort() const
 
376
{
 
377
    return d->srt;
 
378
}
 
379
 
 
380
/*!
 
381
    Sets the current filter to \a filter. Note that no new records are
 
382
    selected. To select new records, use select(). The \a filter will
 
383
    apply to any subsequent select() calls that do not explicitly
 
384
    specify a filter.
 
385
 
 
386
    The filter is a SQL \c WHERE clause without the keyword 'WHERE',
 
387
    e.g. \c{name='Dave'} which will be processed by the DBMS.
 
388
*/
 
389
void Q3SqlCursor::setFilter(const QString& filter)
 
390
{
 
391
    d->ftr = filter;
 
392
}
 
393
 
 
394
/*!
 
395
    Returns the current filter, or an empty string if there is no
 
396
    current filter.
 
397
*/
 
398
QString Q3SqlCursor::filter() const
 
399
{
 
400
    return d->ftr;
 
401
}
 
402
 
 
403
/*!
 
404
    Sets the name of the cursor to \a name. If \a autopopulate is true
 
405
    (the default), the \a name must correspond to a valid table or
 
406
    view name in the database. Also, note that all references to the
 
407
    cursor edit buffer become invalidated when fields are
 
408
    auto-populated. See the Q3SqlCursor constructor documentation for
 
409
    more information.
 
410
*/
 
411
void Q3SqlCursor::setName(const QString& name, bool autopopulate)
 
412
{
 
413
    d->nm = name;
 
414
    if (autopopulate) {
 
415
        if (driver()) {
 
416
            d->infoBuffer = driver()->record(name);
 
417
            *this = d->infoBuffer.toRecord();
 
418
            d->editBuffer = *this;
 
419
            d->priIndx = driver()->primaryIndex(name);
 
420
        }
 
421
        if (isEmpty())
 
422
            qWarning("Q3SqlCursor::setName: unable to build record, does '%s' exist?", name.latin1());
 
423
    }
 
424
}
 
425
 
 
426
/*!
 
427
    Returns the name of the cursor.
 
428
*/
 
429
 
 
430
QString Q3SqlCursor::name() const
 
431
{
 
432
    return d->nm;
 
433
}
 
434
 
 
435
/*! \internal
 
436
*/
 
437
 
 
438
QString Q3SqlCursor::toString(const QString& prefix, const QString& sep) const
 
439
{
 
440
    QString pflist;
 
441
    QString pfix =  prefix.isEmpty() ? prefix : prefix + ".";
 
442
    bool comma = false;
 
443
 
 
444
    for (int i = 0; i < count(); ++i) {
 
445
        const QString fname = fieldName(i);
 
446
        if (isGenerated(i)) {
 
447
            if(comma)
 
448
                pflist += sep + " ";
 
449
            pflist += pfix + fname;
 
450
            comma = true;
 
451
        }
 
452
    }
 
453
    return pflist;
 
454
}
 
455
 
 
456
/*!
 
457
  \internal
 
458
 
 
459
  Assigns the record \a list.
 
460
 
 
461
*/
 
462
QSqlRecord & Q3SqlCursor::operator=(const QSqlRecord & list)
 
463
{
 
464
    return QSqlRecord::operator=(list);
 
465
}
 
466
 
 
467
/*!
 
468
    Append a copy of field \a fieldInfo to the end of the cursor. Note
 
469
    that all references to the cursor edit buffer become invalidated.
 
470
*/
 
471
 
 
472
void Q3SqlCursor::append(const Q3SqlFieldInfo& fieldInfo)
 
473
{
 
474
    d->editBuffer.append(fieldInfo.toField());
 
475
    d->infoBuffer.append(fieldInfo);
 
476
    QSqlRecord::append(fieldInfo.toField());
 
477
}
 
478
 
 
479
/*!
 
480
    Removes all fields from the cursor. Note that all references to
 
481
    the cursor edit buffer become invalidated.
 
482
*/
 
483
void Q3SqlCursor::clear()
 
484
{
 
485
    d->editBuffer.clear();
 
486
    d->infoBuffer.clear();
 
487
    QSqlRecord::clear();
 
488
}
 
489
 
 
490
 
 
491
/*!
 
492
    Insert a copy of \a fieldInfo at position \a pos. If a field
 
493
    already exists at \a pos, it is removed. Note that all references
 
494
    to the cursor edit buffer become invalidated.
 
495
*/
 
496
 
 
497
void  Q3SqlCursor::insert(int pos, const Q3SqlFieldInfo& fieldInfo)
 
498
{
 
499
    d->editBuffer.replace(pos, fieldInfo.toField());
 
500
    d->infoBuffer[pos] = fieldInfo;
 
501
    QSqlRecord::replace(pos, fieldInfo.toField());
 
502
}
 
503
 
 
504
/*!
 
505
    Removes the field at \a pos. If \a pos does not exist, nothing
 
506
    happens. Note that all references to the cursor edit buffer become
 
507
    invalidated.
 
508
*/
 
509
 
 
510
void Q3SqlCursor::remove(int pos)
 
511
{
 
512
    d->editBuffer.remove(pos);
 
513
    d->infoBuffer[pos] = Q3SqlFieldInfo();
 
514
    QSqlRecord::remove(pos);
 
515
}
 
516
 
 
517
/*!
 
518
    Sets the generated flag for the field \a name to \a generated. If
 
519
    the field does not exist, nothing happens. Only fields that have
 
520
    \a generated set to true are included in the SQL that is
 
521
    generated.
 
522
*/
 
523
 
 
524
void Q3SqlCursor::setGenerated(const QString& name, bool generated)
 
525
{
 
526
    int pos = indexOf(name);
 
527
    if (pos == -1)
 
528
        return;
 
529
    QSqlRecord::setGenerated(name, generated);
 
530
    d->editBuffer.setGenerated(name, generated);
 
531
    d->infoBuffer[pos].setGenerated(generated);
 
532
}
 
533
 
 
534
/*!
 
535
    \overload
 
536
 
 
537
    Sets the generated flag for the field \a i to \a generated.
 
538
*/
 
539
void Q3SqlCursor::setGenerated(int i, bool generated)
 
540
{
 
541
    if (i < 0 || i >= (int)d->infoBuffer.count())
 
542
        return;
 
543
    QSqlRecord::setGenerated(i, generated);
 
544
    d->editBuffer.setGenerated(i, generated);
 
545
    d->infoBuffer[i].setGenerated(generated);
 
546
}
 
547
 
 
548
/*!
 
549
    Returns the primary index associated with the cursor as defined in
 
550
    the database, or an empty index if there is no primary index. If
 
551
    \a setFromCursor is true (the default), the index fields are
 
552
    populated with the corresponding values in the cursor's current
 
553
    record.
 
554
*/
 
555
 
 
556
QSqlIndex Q3SqlCursor::primaryIndex(bool setFromCursor) const
 
557
{
 
558
    if (setFromCursor) {
 
559
        for (int i = 0; i < d->priIndx.count(); ++i) {
 
560
            const QString fn = d->priIndx.fieldName(i);
 
561
            if (contains(fn))
 
562
                d->priIndx.setValue(i, QSqlRecord::value(fn));
 
563
        }
 
564
    }
 
565
    return d->priIndx;
 
566
}
 
567
 
 
568
/*!
 
569
    Sets the primary index associated with the cursor to the index \a
 
570
    idx. Note that this index must contain a field or set of fields
 
571
    which identify a unique record within the underlying database
 
572
    table or view so that update() and del() will execute as expected.
 
573
 
 
574
    \sa update() del()
 
575
*/
 
576
 
 
577
void Q3SqlCursor::setPrimaryIndex(const QSqlIndex& idx)
 
578
{
 
579
    d->priIndx = idx;
 
580
}
 
581
 
 
582
 
 
583
/*!
 
584
    Returns an index composed of \a fieldNames, all in ASCending
 
585
    order. Note that all field names must exist in the cursor,
 
586
    otherwise an empty index is returned.
 
587
 
 
588
    \sa QSqlIndex
 
589
*/
 
590
 
 
591
QSqlIndex Q3SqlCursor::index(const QStringList& fieldNames) const
 
592
{
 
593
    QSqlIndex idx;
 
594
    for (QStringList::ConstIterator it = fieldNames.begin(); it != fieldNames.end(); ++it) {
 
595
        QSqlField f = field((*it));
 
596
        if (!f.isValid()) { /* all fields must exist */
 
597
            idx.clear();
 
598
            break;
 
599
        }
 
600
        idx.append(f);
 
601
    }
 
602
    return idx;
 
603
}
 
604
 
 
605
/*!
 
606
    \overload
 
607
 
 
608
    Returns an index based on \a fieldName.
 
609
*/
 
610
 
 
611
QSqlIndex Q3SqlCursor::index(const QString& fieldName) const
 
612
{
 
613
    QStringList fl(fieldName);
 
614
    return index(fl);
 
615
}
 
616
 
 
617
/*!
 
618
    Selects all fields in the cursor from the database matching the
 
619
    filter criteria \a filter. The data is returned in the order
 
620
    specified by the index \a sort. Returns true if the data was
 
621
    successfully selected; otherwise returns false.
 
622
 
 
623
    The \a filter is a string containing a SQL \c WHERE clause but
 
624
    without the 'WHERE' keyword. The cursor is initially positioned at
 
625
    an invalid row after this function is called. To move to a valid
 
626
    row, use seek(), first(), last(), previous() or next().
 
627
 
 
628
    Example:
 
629
    \code
 
630
    Q3SqlCursor cur("Employee"); // Use the Employee table or view
 
631
    cur.select("deptno=10"); // select all records in department 10
 
632
    while(cur.next()) {
 
633
        ... // process data
 
634
    }
 
635
    ...
 
636
    // select records in other departments, ordered by department number
 
637
    cur.select("deptno>10", cur.index("deptno"));
 
638
    ...
 
639
    \endcode
 
640
 
 
641
    The filter will apply to any subsequent select() calls that do not
 
642
    explicitly specify another filter. Similarly the sort will apply
 
643
    to any subsequent select() calls that do not explicitly specify
 
644
    another sort.
 
645
 
 
646
    \code
 
647
    Q3SqlCursor cur("Employee");
 
648
    cur.select("deptno=10"); // select all records in department 10
 
649
    while(cur.next()) {
 
650
        ... // process data
 
651
    }
 
652
    ...
 
653
    cur.select(); // re-selects all records in department 10
 
654
    ...
 
655
    \endcode
 
656
 
 
657
*/
 
658
 
 
659
bool Q3SqlCursor::select(const QString & filter, const QSqlIndex & sort)
 
660
{
 
661
    QString fieldList = toString(d->nm);
 
662
    if (fieldList.isEmpty())
 
663
        return false;
 
664
    QString str= "select " + fieldList;
 
665
    str += " from " + d->nm;
 
666
    if (!filter.isEmpty()) {
 
667
        d->ftr = filter;
 
668
        str += " where " + filter;
 
669
    } else
 
670
        d->ftr = QString();
 
671
    if (sort.count() > 0)
 
672
        str += " order by " + sort.toString(d->nm);
 
673
    d->srt = sort;
 
674
    return exec(str);
 
675
}
 
676
 
 
677
/*!
 
678
    \overload
 
679
 
 
680
    Selects all fields in the cursor from the database. The rows are
 
681
    returned in the order specified by the last call to setSort() or
 
682
    the last call to select() that specified a sort, whichever is the
 
683
    most recent. If there is no current sort, the order in which the
 
684
    rows are returned is undefined. The records are filtered according
 
685
    to the filter specified by the last call to setFilter() or the
 
686
    last call to select() that specified a filter, whichever is the
 
687
    most recent. If there is no current filter, all records are
 
688
    returned. The cursor is initially positioned at an invalid row. To
 
689
    move to a valid row, use seek(), first(), last(), previous() or
 
690
    next().
 
691
 
 
692
    \sa setSort() setFilter()
 
693
*/
 
694
 
 
695
bool Q3SqlCursor::select()
 
696
{
 
697
    return select(filter(), sort());
 
698
}
 
699
 
 
700
/*!
 
701
    \overload
 
702
 
 
703
    Selects all fields in the cursor from the database. The data is
 
704
    returned in the order specified by the index \a sort. The records
 
705
    are filtered according to the filter specified by the last call to
 
706
    setFilter() or the last call to select() that specified a filter,
 
707
    whichever is the most recent. The cursor is initially positioned
 
708
    at an invalid row. To move to a valid row, use seek(), first(),
 
709
    last(), previous() or next().
 
710
*/
 
711
 
 
712
bool Q3SqlCursor::select(const QSqlIndex& sort)
 
713
{
 
714
    return select(filter(), sort);
 
715
}
 
716
 
 
717
/*!
 
718
    \overload
 
719
 
 
720
    Selects all fields in the cursor matching the filter index \a
 
721
    filter. The data is returned in the order specified by the index
 
722
    \a sort. The \a filter index works by constructing a WHERE clause
 
723
    using the names of the fields from the \a filter and their values
 
724
    from the current cursor record. The cursor is initially positioned
 
725
    at an invalid row. To move to a valid row, use seek(), first(),
 
726
    last(), previous() or next(). This function is useful, for example,
 
727
    for retrieving data based upon a table's primary index:
 
728
 
 
729
    \code
 
730
    Q3SqlCursor cur("Employee");
 
731
    QSqlIndex pk = cur.primaryIndex();
 
732
    cur.setValue("id", 10);
 
733
    cur.select(pk, pk); // generates "SELECT ... FROM Employee WHERE id=10 ORDER BY id"
 
734
    ...
 
735
    \endcode
 
736
 
 
737
    In this example the QSqlIndex, pk, is used for two different
 
738
    purposes. When used as the filter (first) argument, the field
 
739
    names it contains are used to construct the WHERE clause, each set
 
740
    to the current cursor value, \c{WHERE id=10}, in this case. When
 
741
    used as the sort (second) argument the field names it contains are
 
742
    used for the ORDER BY clause, \c{ORDER BY id} in this example.
 
743
*/
 
744
 
 
745
bool Q3SqlCursor::select(const QSqlIndex & filter, const QSqlIndex & sort)
 
746
{
 
747
    return select(toString(filter, this, d->nm, "=", "and"), sort);
 
748
}
 
749
 
 
750
/*!
 
751
    Sets the cursor mode to \a mode. This value can be an OR'ed
 
752
    combination of \l Q3SqlCursor::Mode values. The default mode for a
 
753
    cursor is \c Q3SqlCursor::Writable.
 
754
 
 
755
    \code
 
756
    Q3SqlCursor cur("Employee");
 
757
    cur.setMode(Q3SqlCursor::Writable); // allow insert/update/delete
 
758
    ...
 
759
    cur.setMode(Q3SqlCursor::Insert | Q3SqlCursor::Update); // allow inserts and updates only
 
760
    ...
 
761
    cur.setMode(Q3SqlCursor::ReadOnly); // no inserts/updates/deletes allowed
 
762
 
 
763
    \endcode
 
764
*/
 
765
 
 
766
void Q3SqlCursor::setMode(int mode)
 
767
{
 
768
    d->md = mode;
 
769
}
 
770
 
 
771
/*!
 
772
    Returns the current cursor mode.
 
773
 
 
774
    \sa setMode()
 
775
*/
 
776
 
 
777
int Q3SqlCursor::mode() const
 
778
{
 
779
    return d->md;
 
780
}
 
781
 
 
782
/*!
 
783
    Sets field \a name to \a calculated. If the field \a name does not
 
784
    exist, nothing happens. The value of a calculated field is set by
 
785
    the calculateField() virtual function which you must reimplement
 
786
    (or the field value will be an invalid QVariant). Calculated
 
787
    fields do not appear in generated SQL statements sent to the
 
788
    database.
 
789
 
 
790
    \sa calculateField()
 
791
*/
 
792
 
 
793
void Q3SqlCursor::setCalculated(const QString& name, bool calculated)
 
794
{
 
795
    int pos = indexOf(name);
 
796
    if (pos < 0)
 
797
        return;
 
798
    d->infoBuffer[pos].setCalculated(calculated);
 
799
    if (calculated)
 
800
        setGenerated(pos, false);
 
801
}
 
802
 
 
803
/*!
 
804
    Returns true if the field \a name exists and is calculated;
 
805
    otherwise returns false.
 
806
 
 
807
    \sa setCalculated()
 
808
*/
 
809
 
 
810
bool Q3SqlCursor::isCalculated(const QString& name) const
 
811
{
 
812
    int pos = indexOf(name);
 
813
    if (pos < 0)
 
814
        return false;
 
815
    return d->infoBuffer[pos].isCalculated();
 
816
}
 
817
 
 
818
/*!
 
819
    Sets field \a{name}'s trimmed status to \a trim. If the field \a
 
820
    name does not exist, nothing happens.
 
821
 
 
822
    When a trimmed field of type string is read from the
 
823
    database any trailing (right-most) spaces are removed.
 
824
 
 
825
    \sa isTrimmed() QVariant
 
826
*/
 
827
 
 
828
void Q3SqlCursor::setTrimmed(const QString& name, bool trim)
 
829
{
 
830
    int pos = indexOf(name);
 
831
    if (pos < 0)
 
832
        return;
 
833
    d->infoBuffer[pos].setTrim(trim);
 
834
}
 
835
 
 
836
/*!
 
837
    Returns true if the field \a name exists and is trimmed; otherwise
 
838
    returns false.
 
839
 
 
840
    When a trimmed field of type string or cstring is read from the
 
841
    database any trailing (right-most) spaces are removed.
 
842
 
 
843
    \sa setTrimmed()
 
844
*/
 
845
 
 
846
bool Q3SqlCursor::isTrimmed(const QString& name) const
 
847
{
 
848
    int pos = indexOf(name);
 
849
    if (pos < 0)
 
850
        return false;
 
851
    return d->infoBuffer[pos].isTrim();
 
852
}
 
853
 
 
854
/*!
 
855
    Returns true if the cursor is read-only; otherwise returns false.
 
856
    The default is false. Read-only cursors cannot be edited using
 
857
    insert(), update() or del().
 
858
 
 
859
    \sa setMode()
 
860
*/
 
861
 
 
862
bool Q3SqlCursor::isReadOnly() const
 
863
{
 
864
    return d->md == 0;
 
865
}
 
866
 
 
867
/*!
 
868
    Returns true if the cursor will perform inserts; otherwise returns
 
869
    false.
 
870
 
 
871
    \sa setMode()
 
872
*/
 
873
 
 
874
bool Q3SqlCursor::canInsert() const
 
875
{
 
876
    return ((d->md & Insert) == Insert) ;
 
877
}
 
878
 
 
879
 
 
880
/*!
 
881
    Returns true if the cursor will perform updates; otherwise returns
 
882
    false.
 
883
 
 
884
    \sa setMode()
 
885
*/
 
886
 
 
887
bool Q3SqlCursor::canUpdate() const
 
888
{
 
889
    return ((d->md & Update) == Update) ;
 
890
}
 
891
 
 
892
/*!
 
893
    Returns true if the cursor will perform deletes; otherwise returns
 
894
    false.
 
895
 
 
896
    \sa setMode()
 
897
*/
 
898
 
 
899
bool Q3SqlCursor::canDelete() const
 
900
{
 
901
    return ((d->md & Delete) == Delete) ;
 
902
}
 
903
 
 
904
/*!
 
905
    \overload
 
906
 
 
907
    Returns a formatted string composed of the \a prefix (e.g. table
 
908
    or view name), ".", the \a field name, the \a fieldSep and the
 
909
    field value. If the \a prefix is empty then the string will begin
 
910
    with the \a field name. This function is useful for generating SQL
 
911
    statements.
 
912
*/
 
913
 
 
914
QString Q3SqlCursor::toString(const QString& prefix, QSqlField* field, const QString& fieldSep) const
 
915
{
 
916
    QString f;
 
917
    if (field && driver()) {
 
918
        f = (prefix.length() > 0 ? prefix + QString(".") : QString()) + field->name();
 
919
        f += " " + fieldSep + " ";
 
920
        if (field->isNull()) {
 
921
            f += "NULL";
 
922
        } else {
 
923
            f += driver()->formatValue(field);
 
924
        }
 
925
    }
 
926
    return f;
 
927
}
 
928
 
 
929
/*!
 
930
    Returns a formatted string composed of all the fields in \a rec.
 
931
    Each field is composed of the \a prefix (e.g. table or view name),
 
932
    ".", the field name, the \a fieldSep and the field value. If the
 
933
    \a prefix is empty then each field will begin with the field name.
 
934
    The fields are then joined together separated by \a sep. Fields
 
935
    where isGenerated() returns false are not included. This function
 
936
    is useful for generating SQL statements.
 
937
*/
 
938
 
 
939
QString Q3SqlCursor::toString(QSqlRecord* rec, const QString& prefix, const QString& fieldSep,
 
940
                              const QString& sep) const
 
941
{
 
942
    static QString blank(" ");
 
943
    QString filter;
 
944
    bool separator = false;
 
945
    for (int j = 0; j < count(); ++j) {
 
946
        QSqlField f = rec->field(j);
 
947
        if (rec->isGenerated(j)) {
 
948
            if (separator)
 
949
                filter += sep + blank;
 
950
            filter += toString(prefix, &f, fieldSep);
 
951
            filter += blank;
 
952
            separator = true;
 
953
        }
 
954
    }
 
955
    return filter;
 
956
}
 
957
 
 
958
/*!
 
959
    \overload
 
960
 
 
961
    Returns a formatted string composed of all the fields in the index
 
962
    \a i. Each field is composed of the \a prefix (e.g. table or view
 
963
    name), ".", the field name, the \a fieldSep and the field value.
 
964
    If the \a prefix is empty then each field will begin with the field
 
965
    name. The field values are taken from \a rec. The fields are then
 
966
    joined together separated by \a sep. Fields where isGenerated()
 
967
    returns false are ignored. This function is useful for generating
 
968
    SQL statements.
 
969
*/
 
970
 
 
971
QString Q3SqlCursor::toString(const QSqlIndex& i, QSqlRecord* rec, const QString& prefix,
 
972
                                const QString& fieldSep, const QString& sep) const
 
973
{
 
974
    QString filter;
 
975
    bool separator = false;
 
976
    for(int j = 0; j < i.count(); ++j){
 
977
        if (rec->isGenerated(j)) {
 
978
            if(separator) {
 
979
                filter += " " + sep + " " ;
 
980
            }
 
981
            QString fn = i.fieldName(j);
 
982
            QSqlField f = rec->field(fn);
 
983
            filter += toString(prefix, &f, fieldSep);
 
984
            separator = true;
 
985
        }
 
986
    }
 
987
    return filter;
 
988
}
 
989
 
 
990
/*!
 
991
    Inserts the current contents of the cursor's edit record buffer
 
992
    into the database, if the cursor allows inserts. Returns the
 
993
    number of rows affected by the insert. For error information, use
 
994
    lastError().
 
995
 
 
996
    If \a invalidate is true (the default), the cursor will no longer
 
997
    be positioned on a valid record and can no longer be navigated. A
 
998
    new select() call must be made before navigating to a valid
 
999
    record.
 
1000
 
 
1001
    \code
 
1002
    Q3SqlCursor cur("prices");
 
1003
    QSqlRecord *buffer = cur.primeInsert();
 
1004
    buffer->setValue("id",    53981);
 
1005
    buffer->setValue("name",  "Thingy");
 
1006
    buffer->setValue("price", 105.75);
 
1007
    cur.insert();
 
1008
    \endcode
 
1009
 
 
1010
    In the above example, a cursor is created on the 'prices' table
 
1011
    and a pointer to the insert buffer is aquired using primeInsert().
 
1012
    Each field's value is set to the desired value and then insert()
 
1013
    is called to insert the data into the database. Remember: all edit
 
1014
    operations (insert(), update() and delete()) operate on the
 
1015
    contents of the cursor edit buffer and not on the contents of the
 
1016
    cursor itself.
 
1017
 
 
1018
    \sa setMode() lastError()
 
1019
*/
 
1020
 
 
1021
int Q3SqlCursor::insert(bool invalidate)
 
1022
{
 
1023
    if ((d->md & Insert) != Insert || !driver())
 
1024
        return false;
 
1025
    int k = d->editBuffer.count();
 
1026
    if (k == 0)
 
1027
        return 0;
 
1028
 
 
1029
    QString fList;
 
1030
    QString vList;
 
1031
    bool comma = false;
 
1032
    // use a prepared query if the driver supports it
 
1033
    if (driver()->hasFeature(QSqlDriver::PreparedQueries)) {
 
1034
        int cnt = 0;
 
1035
        bool oraStyle = driver()->hasFeature(QSqlDriver::NamedPlaceholders);
 
1036
        for(int j = 0; j < k; ++j) {
 
1037
            QSqlField f = d->editBuffer.field(j);
 
1038
            if (d->editBuffer.isGenerated(j)) {
 
1039
                if (comma) {
 
1040
                    fList += ",";
 
1041
                    vList += ",";
 
1042
                }
 
1043
                fList += f.name();
 
1044
                vList += (oraStyle == true) ? ":f" + QString::number(cnt) : QString("?");
 
1045
                cnt++;
 
1046
                comma = true;
 
1047
            }
 
1048
        }
 
1049
        if (!comma) {
 
1050
            return 0;
 
1051
        }
 
1052
        QString str;
 
1053
        str.append("insert into ").append(name()).append(" (").append(fList).append(") values (").append(vList). append (")");
 
1054
        return applyPrepared(str, invalidate);
 
1055
    } else {
 
1056
        for(int j = 0; j < k; ++j) {
 
1057
            QSqlField f = d->editBuffer.field(j);
 
1058
            if (d->editBuffer.isGenerated(j)) {
 
1059
                if (comma) {
 
1060
                    fList += ",";
 
1061
                    vList += ",";
 
1062
                }
 
1063
                fList += f.name();
 
1064
                vList += driver()->formatValue(&f);
 
1065
                comma = true;
 
1066
            }
 
1067
        }
 
1068
 
 
1069
        if (!comma) {
 
1070
            // no valid fields found
 
1071
            return 0;
 
1072
        }
 
1073
        QString str;
 
1074
        str.append("insert into ").append(name()).append(" (").append(fList).append(") values (").append(vList). append (")");
 
1075
        return apply(str, invalidate);
 
1076
    }
 
1077
}
 
1078
 
 
1079
/*!
 
1080
    Returns the current internal edit buffer. If \a copy is true (the
 
1081
    default is false), the current cursor field values are first
 
1082
    copied into the edit buffer. The edit buffer is valid as long as
 
1083
    the cursor remains valid. The cursor retains ownership of the
 
1084
    returned pointer, so it must not be deleted or modified.
 
1085
 
 
1086
    \sa primeInsert(), primeUpdate() primeDelete()
 
1087
*/
 
1088
 
 
1089
QSqlRecord* Q3SqlCursor::editBuffer(bool copy)
 
1090
{
 
1091
    sync();
 
1092
    if (copy) {
 
1093
        for(int i = 0; i < d->editBuffer.count(); i++) {
 
1094
            if (QSqlRecord::isNull(i)) {
 
1095
                d->editBuffer.setNull(i);
 
1096
            } else {
 
1097
                d->editBuffer.setValue(i, value(i));
 
1098
            }
 
1099
        }
 
1100
    }
 
1101
    return &d->editBuffer;
 
1102
}
 
1103
 
 
1104
/*!
 
1105
    This function primes the edit buffer's field values for update and
 
1106
    returns the edit buffer. The default implementation copies the
 
1107
    field values from the current cursor record into the edit buffer
 
1108
    (therefore, this function is equivalent to calling editBuffer(
 
1109
    true)). The cursor retains ownership of the returned pointer, so
 
1110
    it must not be deleted or modified.
 
1111
 
 
1112
    \sa editBuffer() update()
 
1113
*/
 
1114
 
 
1115
QSqlRecord* Q3SqlCursor::primeUpdate()
 
1116
{
 
1117
    // memorize the primary keys as they were before the user changed the values in editBuffer
 
1118
    QSqlRecord* buf = editBuffer(true);
 
1119
    QSqlIndex idx = primaryIndex(false);
 
1120
    if (!idx.isEmpty())
 
1121
        d->editIndex = toString(idx, buf, d->nm, "=", "and");
 
1122
    else
 
1123
        d->editIndex = qWhereClause(buf, d->nm, "and", driver());
 
1124
    return buf;
 
1125
}
 
1126
 
 
1127
/*!
 
1128
    This function primes the edit buffer's field values for delete and
 
1129
    returns the edit buffer. The default implementation copies the
 
1130
    field values from the current cursor record into the edit buffer
 
1131
    (therefore, this function is equivalent to calling editBuffer(
 
1132
    true)). The cursor retains ownership of the returned pointer, so
 
1133
    it must not be deleted or modified.
 
1134
 
 
1135
    \sa editBuffer() del()
 
1136
*/
 
1137
 
 
1138
QSqlRecord* Q3SqlCursor::primeDelete()
 
1139
{
 
1140
    return editBuffer(true);
 
1141
}
 
1142
 
 
1143
/*!
 
1144
    This function primes the edit buffer's field values for insert and
 
1145
    returns the edit buffer. The default implementation clears all
 
1146
    field values in the edit buffer. The cursor retains ownership of
 
1147
    the returned pointer, so it must not be deleted or modified.
 
1148
 
 
1149
    \sa editBuffer() insert()
 
1150
*/
 
1151
 
 
1152
QSqlRecord* Q3SqlCursor::primeInsert()
 
1153
{
 
1154
    d->editBuffer.clearValues();
 
1155
    return &d->editBuffer;
 
1156
}
 
1157
 
 
1158
 
 
1159
/*!
 
1160
    Updates the database with the current contents of the edit buffer.
 
1161
    Returns the number of records which were updated.
 
1162
    For error information, use lastError().
 
1163
 
 
1164
    Only records which meet the filter criteria specified by the
 
1165
    cursor's primary index are updated. If the cursor does not contain
 
1166
    a primary index, no update is performed and 0 is returned.
 
1167
 
 
1168
    If \a invalidate is true (the default), the current cursor can no
 
1169
    longer be navigated. A new select() call must be made before you
 
1170
    can move to a valid record. For example:
 
1171
 
 
1172
    \code
 
1173
    Q3SqlCursor cur("prices");
 
1174
    cur.select("id=202");
 
1175
    if (cur.next()) {
 
1176
        QSqlRecord *buffer = cur.primeUpdate();
 
1177
        double price = buffer->value("price").toDouble();
 
1178
        double newprice = price * 1.05;
 
1179
        buffer->setValue("price", newprice);
 
1180
        cur.update();
 
1181
    }
 
1182
    \endcode
 
1183
 
 
1184
    In the above example, a cursor is created on the 'prices' table
 
1185
    and is positioned on the record to be updated. Then a pointer to
 
1186
    the cursor's edit buffer is acquired using primeUpdate(). A new
 
1187
    value is calculated and placed into the edit buffer with the
 
1188
    setValue() call. Finally, an update() call is made on the cursor
 
1189
    which uses the tables's primary index to update the record in the
 
1190
    database with the contents of the cursor's edit buffer. Remember:
 
1191
    all edit operations (insert(), update() and delete()) operate on
 
1192
    the contents of the cursor edit buffer and not on the contents of
 
1193
    the cursor itself.
 
1194
 
 
1195
    Note that if the primary index does not uniquely distinguish
 
1196
    records the database may be changed into an inconsistent state.
 
1197
 
 
1198
    \sa setMode() lastError()
 
1199
*/
 
1200
 
 
1201
int Q3SqlCursor::update(bool invalidate)
 
1202
{
 
1203
    if (d->editIndex.isEmpty())
 
1204
        return 0;
 
1205
    return update(d->editIndex, invalidate);
 
1206
}
 
1207
 
 
1208
/*!
 
1209
    \overload
 
1210
 
 
1211
    Updates the database with the current contents of the cursor edit
 
1212
    buffer using the specified \a filter. Returns the number of
 
1213
    records which were updated.
 
1214
    For error information, use lastError().
 
1215
 
 
1216
    Only records which meet the filter criteria are updated, otherwise
 
1217
    all records in the table are updated.
 
1218
 
 
1219
    If \a invalidate is true (the default), the cursor can no longer
 
1220
    be navigated. A new select() call must be made before you can move
 
1221
    to a valid record.
 
1222
 
 
1223
    \sa primeUpdate() setMode() lastError()
 
1224
*/
 
1225
 
 
1226
int Q3SqlCursor::update(const QString & filter, bool invalidate)
 
1227
{
 
1228
    if ((d->md & Update) != Update) {
 
1229
        return false;
 
1230
    }
 
1231
    int k = count();
 
1232
    if (k == 0) {
 
1233
        return 0;
 
1234
    }
 
1235
    
 
1236
    // use a prepared query if the driver supports it
 
1237
    if (driver()->hasFeature(QSqlDriver::PreparedQueries)) {
 
1238
        QString fList;
 
1239
        bool comma = false;
 
1240
        int cnt = 0;
 
1241
        bool oraStyle = driver()->hasFeature(QSqlDriver::NamedPlaceholders);
 
1242
        for(int j = 0; j < k; ++j) {
 
1243
            QSqlField f = d->editBuffer.field(j);
 
1244
            if (d->editBuffer.isGenerated(j)) {
 
1245
                if (comma) {
 
1246
                    fList += ",";
 
1247
                }
 
1248
                fList += f.name() + " = " + (oraStyle == true ? ":f" + QString::number(cnt) : QString("?"));
 
1249
                cnt++;
 
1250
                comma = true;
 
1251
            }
 
1252
        }
 
1253
        if (!comma) {
 
1254
            return 0;
 
1255
        }
 
1256
        QString str = "update " + name() + " set " + fList;
 
1257
        if (filter.length()) {
 
1258
            str+= " where " + filter;
 
1259
        }
 
1260
        return applyPrepared(str, invalidate);
 
1261
    } else {
 
1262
        QString str = "update " + name();
 
1263
        str += " set " + toString(&d->editBuffer, QString(), "=", ",");
 
1264
        if (filter.length()) {
 
1265
            str+= " where " + filter;
 
1266
        }
 
1267
        return apply(str, invalidate);
 
1268
    }
 
1269
}
 
1270
 
 
1271
/*!
 
1272
    Deletes a record from the database using the cursor's primary
 
1273
    index and the contents of the cursor edit buffer. Returns the
 
1274
    number of records which were deleted.
 
1275
    For error information, use lastError().
 
1276
 
 
1277
    Only records which meet the filter criteria specified by the
 
1278
    cursor's primary index are deleted. If the cursor does not contain
 
1279
    a primary index, no delete is performed and 0 is returned. If \a
 
1280
    invalidate is true (the default), the current cursor can no longer
 
1281
    be navigated. A new select() call must be made before you can move
 
1282
    to a valid record. For example:
 
1283
 
 
1284
    \code
 
1285
    Q3SqlCursor cur("prices");
 
1286
    cur.select("id=999");
 
1287
    if (cur.next()) {
 
1288
        cur.primeDelete();
 
1289
        cur.del();
 
1290
    }
 
1291
    \endcode
 
1292
 
 
1293
    In the above example, a cursor is created on the 'prices' table
 
1294
    and positioned to the record to be deleted. First primeDelete() is
 
1295
    called to populate the edit buffer with the current cursor values,
 
1296
    e.g. with an id of 999, and then del() is called to actually
 
1297
    delete the record from the database. Remember: all edit operations
 
1298
    (insert(), update() and delete()) operate on the contents of the
 
1299
    cursor edit buffer and not on the contents of the cursor itself.
 
1300
 
 
1301
    \sa primeDelete() setMode() lastError()
 
1302
*/
 
1303
 
 
1304
int Q3SqlCursor::del(bool invalidate)
 
1305
{
 
1306
    QSqlIndex idx = primaryIndex(false);
 
1307
    if (idx.isEmpty())
 
1308
        return del(qWhereClause(&d->editBuffer, d->nm, "and", driver()), invalidate);
 
1309
    return del(toString(primaryIndex(), &d->editBuffer, d->nm, "=", "and"), invalidate);
 
1310
}
 
1311
 
 
1312
/*!
 
1313
    \overload
 
1314
 
 
1315
    Deletes the current cursor record from the database using the
 
1316
    filter \a filter. Only records which meet the filter criteria are
 
1317
    deleted. Returns the number of records which were deleted. If \a
 
1318
    invalidate is true (the default), the current cursor can no longer
 
1319
    be navigated. A new select() call must be made before you can move
 
1320
    to a valid record. For error information, use lastError().
 
1321
 
 
1322
    The \a filter is an SQL \c WHERE clause, e.g. \c{id=500}.
 
1323
 
 
1324
    \sa setMode() lastError()
 
1325
*/
 
1326
 
 
1327
int Q3SqlCursor::del(const QString & filter, bool invalidate)
 
1328
{
 
1329
    if ((d->md & Delete) != Delete)
 
1330
        return 0;
 
1331
    int k = count();
 
1332
    if(k == 0) return 0;
 
1333
    QString str = "delete from " + name();
 
1334
    if (filter.length())
 
1335
        str+= " where " + filter;
 
1336
    return apply(str, invalidate);
 
1337
}
 
1338
 
 
1339
/*
 
1340
  \internal
 
1341
*/
 
1342
 
 
1343
int Q3SqlCursor::apply(const QString& q, bool invalidate)
 
1344
{
 
1345
    int ar = 0;
 
1346
    if (invalidate) {
 
1347
        if (exec(q))
 
1348
            ar = numRowsAffected();
 
1349
    } else if (driver()) {
 
1350
        QSqlQuery* sql = d->query();
 
1351
        if (sql && sql->exec(q))
 
1352
            ar = sql->numRowsAffected();
 
1353
    }
 
1354
    return ar;
 
1355
}
 
1356
 
 
1357
/*
 
1358
  \internal
 
1359
*/
 
1360
 
 
1361
int Q3SqlCursor::applyPrepared(const QString& q, bool invalidate)
 
1362
{
 
1363
    int ar = 0;
 
1364
    QSqlQuery* sql = 0;
 
1365
 
 
1366
    if (invalidate) {
 
1367
        sql = (QSqlQuery*)this;
 
1368
        d->lastAt = QSql::BeforeFirst;
 
1369
    } else {
 
1370
        sql = d->query();
 
1371
    }
 
1372
    if (!sql)
 
1373
        return 0;
 
1374
 
 
1375
    if (invalidate || sql->lastQuery() != q) {
 
1376
        if (!sql->prepare(q))
 
1377
            return 0;
 
1378
    }
 
1379
 
 
1380
    int cnt = 0;
 
1381
    int fieldCount = (int)count();
 
1382
    for (int j = 0; j < fieldCount; ++j) {
 
1383
        const QSqlField f = d->editBuffer.field(j);
 
1384
        if (d->editBuffer.isGenerated(j)) {
 
1385
            if (f.type() == QVariant::ByteArray)
 
1386
                sql->bindValue(cnt, f.value(), QSql::In | QSql::Binary);
 
1387
            else
 
1388
                sql->bindValue(cnt, f.value());
 
1389
            cnt++;
 
1390
        }
 
1391
    }
 
1392
    if (sql->exec()) {
 
1393
        ar = sql->numRowsAffected();
 
1394
    }
 
1395
    return ar;
 
1396
}
 
1397
 
 
1398
/*!
 
1399
  Executes the SQL query \a sql. Returns true of the cursor is
 
1400
  active, otherwise returns false.
 
1401
*/
 
1402
bool Q3SqlCursor::exec(const QString & sql)
 
1403
{
 
1404
    d->lastAt = QSql::BeforeFirst;
 
1405
    QSqlQuery::exec(sql);
 
1406
    return isActive();
 
1407
}
 
1408
 
 
1409
/*!
 
1410
    Protected virtual function which is called whenever a field needs
 
1411
    to be calculated. If calculated fields are being used, derived
 
1412
    classes must reimplement this function and return the appropriate
 
1413
    value for field \a name. The default implementation returns an
 
1414
    invalid QVariant.
 
1415
 
 
1416
    \sa setCalculated()
 
1417
*/
 
1418
 
 
1419
QVariant Q3SqlCursor::calculateField(const QString&)
 
1420
{
 
1421
    return QVariant();
 
1422
}
 
1423
 
 
1424
/*! \internal
 
1425
   Ensure fieldlist is synced with query.
 
1426
 
 
1427
*/
 
1428
 
 
1429
static QString qTrim(const QString& s)
 
1430
{
 
1431
    QString result = s;
 
1432
    int end = result.length() - 1;
 
1433
    while (end >= 0 && result[end].isSpace()) // skip white space from end
 
1434
        end--;
 
1435
    result.truncate(end + 1);
 
1436
    return result;
 
1437
}
 
1438
 
 
1439
/*! \internal
 
1440
 */
 
1441
 
 
1442
void Q3SqlCursor::sync()
 
1443
{
 
1444
    if (isActive() && isValid() && d->lastAt != at()) {
 
1445
        d->lastAt = at();
 
1446
        int i = 0;
 
1447
        int j = 0;
 
1448
        bool haveCalculatedFields = false;
 
1449
        for (; i < count(); ++i) {
 
1450
            if (!haveCalculatedFields && d->infoBuffer[i].isCalculated()) {
 
1451
                haveCalculatedFields = true;
 
1452
            }
 
1453
            if (QSqlRecord::isGenerated(i)) {
 
1454
                QVariant v = QSqlQuery::value(j);
 
1455
                if ((v.type() == QVariant::String) &&
 
1456
                        d->infoBuffer[i].isTrim()) {
 
1457
                    v = qTrim(v.toString());
 
1458
                }
 
1459
                QSqlRecord::setValue(i, v);
 
1460
                if (QSqlQuery::isNull(j))
 
1461
                    QSqlRecord::field(i).clear();
 
1462
                j++;
 
1463
            }
 
1464
        }
 
1465
        if (haveCalculatedFields) {
 
1466
            for (i = 0; i < count(); ++i) {
 
1467
                if (d->infoBuffer[i].isCalculated())
 
1468
                    QSqlRecord::setValue(i, calculateField(fieldName(i)));
 
1469
            }
 
1470
        }
 
1471
    }
 
1472
}
 
1473
 
 
1474
/*!
 
1475
    Returns the value of field number \a i.
 
1476
*/
 
1477
 
 
1478
QVariant Q3SqlCursor::value(int i) const
 
1479
{
 
1480
    const_cast<Q3SqlCursor *>(this)->sync();
 
1481
    return QSqlRecord::value(i);
 
1482
}
 
1483
 
 
1484
/*! \internal
 
1485
  cursors should be filled with Q3SqlFieldInfos...
 
1486
*/
 
1487
void Q3SqlCursor::append(const QSqlField& field)
 
1488
{
 
1489
    append(Q3SqlFieldInfo(field));
 
1490
}
 
1491
 
 
1492
/*!
 
1493
    Returns true if the field \a i is NULL or if there is no field at
 
1494
    position \a i; otherwise returns false.
 
1495
 
 
1496
    This is the same as calling QSqlRecord::isNull(\a i)
 
1497
*/
 
1498
bool Q3SqlCursor::isNull(int i) const
 
1499
{
 
1500
    const_cast<Q3SqlCursor *>(this)->sync();
 
1501
    return QSqlRecord::isNull(i);
 
1502
}
 
1503
/*!
 
1504
    \overload
 
1505
 
 
1506
    Returns true if the field called \a name is NULL or if there is no
 
1507
    field called \a name; otherwise returns false.
 
1508
 
 
1509
    This is the same as calling QSqlRecord::isNull(\a name)
 
1510
*/
 
1511
bool Q3SqlCursor::isNull(const QString& name) const
 
1512
{
 
1513
    const_cast<Q3SqlCursor *>(this)->sync();
 
1514
    return QSqlRecord::isNull(name);
 
1515
}
 
1516
 
 
1517
/*! \internal */
 
1518
void Q3SqlCursor::setValue(int i, const QVariant& val)
 
1519
{
 
1520
    sync();
 
1521
#ifdef QT_DEBUG
 
1522
    qDebug("Q3SqlCursor::setValue(): This will not affect actual database values. Use primeInsert(), primeUpdate() or primeDelete().");
 
1523
#endif
 
1524
    QSqlRecord::setValue(i, val);
 
1525
}
 
1526
 
 
1527
/*! \internal */
 
1528
bool Q3SqlCursor::seek(int i, bool relative)
 
1529
{
 
1530
    bool res = QSqlQuery::seek(i, relative);
 
1531
    sync();
 
1532
    return res;
 
1533
}
 
1534
 
 
1535
/*! \internal */
 
1536
bool Q3SqlCursor::next()
 
1537
{
 
1538
    bool res = QSqlQuery::next();
 
1539
    sync();
 
1540
    return res;
 
1541
}
 
1542
 
 
1543
/*!
 
1544
    \fn Q3SqlCursor::previous()
 
1545
 
 
1546
    \internal
 
1547
*/
 
1548
 
 
1549
/*! \internal */
 
1550
bool Q3SqlCursor::prev()
 
1551
{
 
1552
    bool res = QSqlQuery::previous();
 
1553
    sync();
 
1554
    return res;
 
1555
}
 
1556
 
 
1557
/*! \internal */
 
1558
bool Q3SqlCursor::first()
 
1559
{
 
1560
    bool res = QSqlQuery::first();
 
1561
    sync();
 
1562
    return res;
 
1563
}
 
1564
 
 
1565
/*! \internal */
 
1566
bool Q3SqlCursor::last()
 
1567
{
 
1568
    bool res = QSqlQuery::last();
 
1569
    sync();
 
1570
    return res;
 
1571
}
 
1572
 
 
1573
#endif