source: trunk/src/sql/qsqldriver.cpp

Last change on this file 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: 13.5 KB
Line 
1/****************************************************************************
2**
3** Implementation of QSqlDriver 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 "qsqldriver.h"
38
39#ifndef QT_NO_SQL
40
41#include "qdatetime.h"
42#include "qsqlextension_p.h"
43
44// database states
45#define DBState_Open 0x0001
46#define DBState_OpenError 0x0002
47
48// ### This needs to go in 4.0!
49QPtrDict<QSqlDriverExtension> *qSqlDriverExtDict();
50QPtrDict<QSqlOpenExtension> *qSqlOpenExtDict();
51
52/*!
53 \class QSqlDriver qsqldriver.h
54 \brief The QSqlDriver class is an abstract base class for accessing
55 SQL databases.
56
57 \ingroup database
58 \module sql
59
60 This class should not be used directly. Use QSqlDatabase instead.
61*/
62
63/*!
64 Default constructor. Creates a new driver with parent \a parent,
65 called \a name.
66
67*/
68
69QSqlDriver::QSqlDriver( QObject * parent, const char * name )
70: QObject(parent, name),
71 dbState(0),
72 error()
73{
74}
75
76/*!
77 Destroys the object and frees any allocated resources.
78*/
79
80QSqlDriver::~QSqlDriver()
81{
82}
83
84/*!
85 \fn bool QSqlDriver::open( const QString& db, const QString& user,
86 const QString& password, const QString& host, int port )
87
88 Derived classes must reimplement this abstract virtual function in
89 order to open a database connection on database \a db, using user
90 name \a user, password \a password, host \a host and port \a port.
91
92 The function \e must return TRUE on success and FALSE on failure.
93
94 \sa setOpen()
95
96*/
97
98/*!
99 \fn bool QSqlDriver::close()
100
101 Derived classes must reimplement this abstract virtual function in
102 order to close the database connection. Return TRUE on success,
103 FALSE on failure.
104
105 \sa setOpen()
106
107*/
108
109/*!
110 \fn QSqlQuery QSqlDriver::createQuery() const
111
112 Creates an empty SQL result on the database. Derived classes must
113 reimplement this function and return a QSqlQuery object
114 appropriate for their database to the caller.
115
116*/
117
118//void QSqlDriver::destroyResult( QSqlResult* r ) const
119//{
120// if ( r )
121// delete r;
122//}
123
124/*!
125 Returns TRUE if the database connection is open; otherwise returns
126 FALSE.
127*/
128
129bool QSqlDriver::isOpen() const
130{
131 if ( !qSqlDriverExtDict()->isEmpty() ) {
132 QSqlDriverExtension *ext = qSqlDriverExtDict()->find( (QSqlDriver *) this );
133 if ( ext )
134 return ext->isOpen();
135 }
136
137 return ((dbState & DBState_Open) == DBState_Open);
138}
139
140/*!
141 Returns TRUE if the there was an error opening the database
142 connection; otherwise returns FALSE.
143*/
144
145bool QSqlDriver::isOpenError() const
146{
147 return ((dbState & DBState_OpenError) == DBState_OpenError);
148}
149
150/*!
151 \enum QSqlDriver::DriverFeature
152
153 This enum contains a list of features a driver may support. Use
154 hasFeature() to query whether a feature is supported or not.
155
156 \value Transactions whether the driver supports SQL transactions
157 \value QuerySize whether the database is capable of reporting the size
158 of a query. Note that some databases do not support returning the size
159 (i.e. number of rows returned) of a query, in which case
160 QSqlQuery::size() will return -1
161 \value BLOB whether the driver supports Binary Large Object fields
162 \value Unicode whether the driver supports Unicode strings if the
163 database server does
164 \value PreparedQueries whether the driver supports prepared query execution
165 \value NamedPlaceholders whether the driver supports usage of named placeholders
166 \value PositionalPlaceholders whether the driver supports usage of positional placeholders
167
168 More information about supported features can be found in the
169 \link sql-driver.html Qt SQL driver\endlink documentation.
170
171 \sa hasFeature()
172*/
173
174/*!
175 \fn bool QSqlDriver::hasFeature( DriverFeature f ) const
176
177 Returns TRUE if the driver supports feature \a f; otherwise
178 returns FALSE.
179
180 Note that some databases need to be open() before this can be
181 determined.
182
183 \sa DriverFeature
184*/
185
186/*!
187 Protected function which sets the open state of the database to \a
188 o. Derived classes can use this function to report the status of
189 open().
190
191 \sa open(), setOpenError()
192*/
193
194void QSqlDriver::setOpen( bool o )
195{
196 if ( o )
197 dbState |= DBState_Open;
198 else
199 dbState &= ~DBState_Open;
200}
201
202/*!
203 Protected function which sets the open error state of the database
204 to \a e. Derived classes can use this function to report the
205 status of open(). Note that if \a e is TRUE the open state of the
206 database is set to closed (i.e. isOpen() returns FALSE).
207
208 \sa open(), setOpenError()
209*/
210
211void QSqlDriver::setOpenError( bool e )
212{
213 if ( e ) {
214 dbState |= DBState_OpenError;
215 dbState &= ~DBState_Open;
216 }
217 else
218 dbState &= ~DBState_OpenError;
219}
220
221/*!
222 Protected function which derived classes can reimplement to begin
223 a transaction. If successful, return TRUE, otherwise return FALSE.
224 The default implementation returns FALSE.
225
226 \sa commitTransaction(), rollbackTransaction()
227*/
228
229bool QSqlDriver::beginTransaction()
230{
231 return FALSE;
232}
233
234/*!
235 Protected function which derived classes can reimplement to commit
236 a transaction. If successful, return TRUE, otherwise return FALSE.
237 The default implementation returns FALSE.
238
239 \sa beginTransaction(), rollbackTransaction()
240*/
241
242bool QSqlDriver::commitTransaction()
243{
244 return FALSE;
245}
246
247/*!
248 Protected function which derived classes can reimplement to
249 rollback a transaction. If successful, return TRUE, otherwise
250 return FALSE. The default implementation returns FALSE.
251
252 \sa beginTransaction(), commitTransaction()
253*/
254
255bool QSqlDriver::rollbackTransaction()
256{
257 return FALSE;
258}
259
260/*!
261 Protected function which allows derived classes to set the value
262 of the last error, \a e, that occurred on the database.
263
264 \sa lastError()
265*/
266
267void QSqlDriver::setLastError( const QSqlError& e )
268{
269 error = e;
270}
271
272/*!
273 Returns a QSqlError object which contains information about the
274 last error that occurred on the database.
275*/
276
277QSqlError QSqlDriver::lastError() const
278{
279 return error;
280}
281
282/*!
283 Returns a list of tables in the database. The default
284 implementation returns an empty list.
285
286 The \a tableType argument describes what types of tables
287 should be returned. Due to binary compatibility, the string
288 contains the value of the enum QSql::TableTypes as text.
289 An empty string should be treated as QSql::Tables for
290 downward compatibility.
291
292 \sa QSql::TableType
293*/
294
295QStringList QSqlDriver::tables( const QString& ) const
296{
297 return QStringList();
298}
299
300/*!
301 Returns the primary index for table \a tableName. Returns an empty
302 QSqlIndex if the table doesn't have a primary index. The default
303 implementation returns an empty index.
304*/
305
306QSqlIndex QSqlDriver::primaryIndex( const QString& ) const
307{
308 return QSqlIndex();
309}
310
311
312/*!
313 Returns a QSqlRecord populated with the names of the fields in
314 table \a tableName. If no such table exists, an empty record is
315 returned. The default implementation returns an empty record.
316*/
317
318QSqlRecord QSqlDriver::record( const QString& ) const
319{
320 return QSqlRecord();
321}
322
323/*!
324 \overload
325
326 Returns a QSqlRecord populated with the names of the fields in the
327 SQL \a query. The default implementation returns an empty record.
328*/
329
330QSqlRecord QSqlDriver::record( const QSqlQuery& ) const
331{
332 return QSqlRecord();
333}
334
335/*!
336 Returns a QSqlRecordInfo object with meta data about the table \a
337 tablename.
338*/
339QSqlRecordInfo QSqlDriver::recordInfo( const QString& tablename ) const
340{
341 return QSqlRecordInfo( record( tablename ) );
342}
343
344/*!
345 \overload
346
347 Returns a QSqlRecordInfo object with meta data for the QSqlQuery
348 \a query. Note that this overloaded function may return less
349 information than the recordInfo() function which takes the name of
350 a table as parameter.
351*/
352QSqlRecordInfo QSqlDriver::recordInfo( const QSqlQuery& query ) const
353{
354 return QSqlRecordInfo( record( query ) );
355}
356
357
358/*!
359 Returns a string representation of the NULL value for the
360 database. This is used, for example, when constructing INSERT and
361 UPDATE statements. The default implementation returns the string
362 "NULL".
363*/
364
365QString QSqlDriver::nullText() const
366{
367 return "NULL";
368}
369
370/*!
371 Returns a string representation of the \a field value for the
372 database. This is used, for example, when constructing INSERT and
373 UPDATE statements.
374
375 The default implementation returns the value formatted as a string
376 according to the following rules:
377
378 \list
379
380 \i If \a field is NULL, nullText() is returned.
381
382 \i If \a field is character data, the value is returned enclosed
383 in single quotation marks, which is appropriate for many SQL
384 databases. Any embedded single-quote characters are escaped
385 (replaced with two single-quote characters). If \a trimStrings is
386 TRUE (the default is FALSE), all trailing whitespace is trimmed
387 from the field.
388
389 \i If \a field is date/time data, the value is formatted in ISO
390 format and enclosed in single quotation marks. If the date/time
391 data is invalid, nullText() is returned.
392
393 \i If \a field is bytearray data, and the driver can edit binary
394 fields, the value is formatted as a hexadecimal string.
395
396 \i For any other field type toString() will be called on its value
397 and the result returned.
398
399 \endlist
400
401 \sa QVariant::toString().
402
403*/
404QString QSqlDriver::formatValue( const QSqlField* field, bool trimStrings ) const
405{
406 QString r;
407 if ( field->isNull() )
408 r = nullText();
409 else {
410 switch ( field->type() ) {
411 case QVariant::Int:
412 case QVariant::UInt:
413 if ( field->value().type() == QVariant::Bool )
414 r = field->value().toBool() ? "1" : "0";
415 else
416 r = field->value().toString();
417 break;
418 case QVariant::Date:
419 if ( field->value().toDate().isValid() )
420 r = "'" + field->value().toDate().toString( Qt::ISODate ) + "'";
421 else
422 r = nullText();
423 break;
424 case QVariant::Time:
425 if ( field->value().toTime().isValid() )
426 r = "'" + field->value().toTime().toString( Qt::ISODate ) + "'";
427 else
428 r = nullText();
429 break;
430 case QVariant::DateTime:
431 if ( field->value().toDateTime().isValid() )
432 r = "'" +
433 field->value().toDateTime().toString( Qt::ISODate ) + "'";
434 else
435 r = nullText();
436 break;
437 case QVariant::String:
438 case QVariant::CString: {
439 QString result = field->value().toString();
440 if ( trimStrings ) {
441 int end = result.length() - 1;
442 while ( end && result[end].isSpace() ) /* skip white space from end */
443 end--;
444 result.truncate( end );
445 }
446 /* escape the "'" character */
447 result.replace( QChar( '\'' ), "''" );
448 r = "'" + result + "'";
449 break;
450 }
451 case QVariant::Bool:
452 if ( field->value().toBool() )
453 r = "1";
454 else
455 r = "0";
456 break;
457 case QVariant::ByteArray : {
458 if ( hasFeature( BLOB ) ) {
459 QByteArray ba = field->value().toByteArray();
460 QString res;
461 static const char hexchars[] = "0123456789abcdef";
462 for ( uint i = 0; i < ba.size(); ++i ) {
463 uchar s = (uchar) ba[(int)i];
464 res += hexchars[s >> 4];
465 res += hexchars[s & 0x0f];
466 }
467 r = "'" + res + "'";
468 break;
469 }
470 }
471 default:
472 r = field->value().toString();
473 break;
474 }
475 }
476 return r;
477}
478
479/*!
480 \overload
481
482 Open a database connection on database \a db, using user name \a
483 user, password \a password, host \a host, port \a port and
484 connection options \a connOpts.
485
486 Returns TRUE on success and FALSE on failure.
487
488 \sa setOpen()
489*/
490bool QSqlDriver::open( const QString& db,
491 const QString& user,
492 const QString& password,
493 const QString& host,
494 int port,
495 const QString& connOpts )
496{
497 if ( !qSqlOpenExtDict()->isEmpty() ) {
498 QSqlOpenExtension *ext = qSqlOpenExtDict()->find( (QSqlDriver *) this );
499 if ( ext )
500 return ext->open( db, user, password, host, port, connOpts );
501 }
502 return open( db, user, password, host, port );
503}
504
505#endif // QT_NO_SQL
Note: See TracBrowser for help on using the repository browser.