source: trunk/src/sql/qsqlcursor.cpp@ 196

Last change on this file since 196 was 196, checked in by rudi, 14 years ago

Add SQL module (currently it isn't build by default, however it's needed for QtDesigner)

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