~smartboyhw/ubuntu/raring/calligra/2.6.0-0ubuntu1

« back to all changes in this revision

Viewing changes to kexi/kexidb/connection.h

  • Committer: Package Import Robot
  • Author(s): Philip Muškovac
  • Date: 2012-10-23 21:09:16 UTC
  • mfrom: (1.1.13)
  • Revision ID: package-import@ubuntu.com-20121023210916-m82w6zxnxhaxz7va
Tags: 1:2.5.90-0ubuntu1
* New upstream alpha release (LP: #1070436)
  - Add libkactivities-dev and libopenimageio-dev to build-depends
  - Add kubuntu_build_calligraactive.diff to build calligraactive by default
  - Add package for calligraauthor and move files that are shared between
    calligrawords and calligraauthor to calligrawords-common
* Document the patches
* Remove numbers from patches so they follow the same naming scheme as
  the rest of our patches.
* calligra-data breaks replaces krita-data (<< 1:2.5.3) (LP: #1071686)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* This file is part of the KDE project
2
 
   Copyright (C) 2003-2012 Jarosław Staniek <staniek@kde.org>
3
 
 
4
 
   This program is free software; you can redistribute it and/or
5
 
   modify it under the terms of the GNU Library General Public
6
 
   License as published by the Free Software Foundation; either
7
 
   version 2 of the License, or (at your option) any later version.
8
 
 
9
 
   This program is distributed in the hope that it will be useful,
10
 
   but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 
   Library General Public License for more details.
13
 
 
14
 
   You should have received a copy of the GNU Library General Public License
15
 
   along with this program; see the file COPYING.  If not, write to
16
 
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17
 
 * Boston, MA 02110-1301, USA.
18
 
*/
19
 
 
20
 
#ifndef KEXIDB_CONNECTION_H
21
 
#define KEXIDB_CONNECTION_H
22
 
 
23
 
#include <QObject>
24
 
#include <QStringList>
25
 
#include <QHash>
26
 
#include <QVector>
27
 
#include <QVariant>
28
 
#include <QPointer>
29
 
 
30
 
#include "object.h"
31
 
#include "connectiondata.h"
32
 
#include "tableschema.h"
33
 
#include "queryschema.h"
34
 
#include "queryschemaparameter.h"
35
 
#include "transaction.h"
36
 
#include "driver.h"
37
 
#include "preparedstatement.h"
38
 
#include "RecordData.h"
39
 
 
40
 
#include <kexiutils/tristate.h>
41
 
 
42
 
namespace KexiDB
43
 
{
44
 
 
45
 
class Cursor;
46
 
class ConnectionPrivate;
47
 
class RowEditBuffer;
48
 
class DatabaseProperties;
49
 
class AlterTableHandler;
50
 
 
51
 
/*! @short Provides database connection, allowing queries and data modification.
52
 
 
53
 
 This class represents a database connection established within a data source.
54
 
 It supports data queries and modification by creating client-side database cursors.
55
 
 Database transactions are supported.
56
 
*/
57
 
class KEXI_DB_EXPORT Connection : public QObject, public KexiDB::Object
58
 
{
59
 
    Q_OBJECT
60
 
 
61
 
public:
62
 
 
63
 
    /*! Opened connection is automatically disconnected and removed
64
 
     from driver's connections list.
65
 
     Note for driver developers: you should call destroy()
66
 
     from you Connection's subclass destructor. */
67
 
    virtual ~Connection();
68
 
 
69
 
    /*! \return parameters that were used to create this connection. */
70
 
    ConnectionData* data() const;
71
 
 
72
 
    /*! \return the driver used for this connection. */
73
 
    inline Driver* driver() const {
74
 
        return m_driver;
75
 
    }
76
 
 
77
 
    /*!
78
 
    \brief Connects to driver with given parameters.
79
 
    \return true if successful. */
80
 
    bool connect();
81
 
 
82
 
    /*! \return true, if connection is properly established. */
83
 
    bool isConnected() const;
84
 
 
85
 
    /*! \return true, both if connection is properly established
86
 
     and any database within this connection is properly used
87
 
     with useDatabase(). */
88
 
    bool isDatabaseUsed() const;
89
 
 
90
 
    /*! \return true for read only connection. Used especially for file-based drivers.
91
 
     Can be reimplemented in a driver to provide real read-only flag of the connection
92
 
     (SQlite3 dirver does this). */
93
 
    virtual bool isReadOnly() const;
94
 
 
95
 
    /*! Reimplemented from Object: also clears sql string.
96
 
     @sa recentSQLString() */
97
 
    virtual void clearError();
98
 
 
99
 
    /*! \brief Disconnects from driver with given parameters.
100
 
 
101
 
     The database (if used) is closed, and any active transactions
102
 
     (if supported) are rolled back, so commit these before disconnecting,
103
 
     if you'd like to save your changes. */
104
 
    bool disconnect();
105
 
 
106
 
    /*! \return list of database names for opened connection.
107
 
     If \a also_system_db is true, the system database names are also returned. */
108
 
    QStringList databaseNames(bool also_system_db = false);
109
 
 
110
 
    /*! \return true if database \a dbName exists.
111
 
     If \a ignoreErrors is true, error flag of connection
112
 
      won't be modified for any errors (it will quietly return),
113
 
      else (ignoreErrors == false) we can check why the database does
114
 
      not exist using error(), errorNum() and/or errorMsg(). */
115
 
    bool databaseExists(const QString &dbName, bool ignoreErrors = true);
116
 
 
117
 
    /*! \brief Creates new database with name \a dbName, using this connection.
118
 
 
119
 
     If database with \a dbName already exists, or other error occurred,
120
 
     false is returned.
121
 
     For file-based drivers, \a dbName should be equal to the database
122
 
     filename (the same as specified for ConnectionData).
123
 
 
124
 
     See doc/dev/kexidb_issues.txt document, chapter "Table schema, query schema, etc. storage"
125
 
     for database schema documentation (detailed description of kexi__* 'system' tables).
126
 
 
127
 
     \sa useDatabase() */
128
 
    bool createDatabase(const QString &dbName);
129
 
 
130
 
    /*!
131
 
    \brief Opens an existing database specified by \a dbName.
132
 
 
133
 
     If \a kexiCompatible is true (the default) initial checks will be performed
134
 
     to recognize database Kexi-specific format. Set \a kexiCompatible to false
135
 
     if you're using native database (one that have no Kexi System tables).
136
 
     For file-based drivers, \a dbName should be equal to filename
137
 
     (the same as specified for ConnectionData).
138
 
     \return true on success, false on failure.
139
 
     If user has cancelled this action and \a cancelled is not 0, *cancelled is set to true. */
140
 
    bool useDatabase(const QString &dbName, bool kexiCompatible = true, bool *cancelled = 0,
141
 
                     MessageHandler* msgHandler = 0);
142
 
 
143
 
    /*!
144
 
    \brief Closes currently used database for this connection.
145
 
 
146
 
     Any active transactions (if supported) are rolled back,
147
 
     so commit these before closing, if you'd like to save your changes. */
148
 
    bool closeDatabase();
149
 
 
150
 
    /*! \brief Get the name of the current database
151
 
 
152
 
    \return name of currently used database for this connection or empty string
153
 
      if there is no used database */
154
 
    QString currentDatabase() const;
155
 
 
156
 
    /*! \brief Drops database with name \a dbName.
157
 
 
158
 
     if dbName is not specified, currently used database name is used
159
 
     (it is closed before dropping).
160
 
    */
161
 
    bool dropDatabase(const QString &dbName = QString());
162
 
 
163
 
    /*! \return names of all the \a objecttype (see \a ObjectType in global.h)
164
 
    schemas stored in currently used database. KexiDB::AnyObjectType can be passed
165
 
    as \a objType to get names of objects of any type.
166
 
    If \a ok is not null then variable pointed by it will be set to the result.
167
 
    On error, the functions can return incomplete list. */
168
 
    QStringList objectNames(int objType = KexiDB::AnyObjectType, bool* ok = 0);
169
 
 
170
 
    /*! \return names of all table schemas stored in currently
171
 
     used database. If \a also_system_tables is true,
172
 
     internal KexiDB system table names (kexi__*) are also returned.
173
 
     \sa kexiDBSystemTableNames() */
174
 
    QStringList tableNames(bool also_system_tables = false);
175
 
 
176
 
    /*! \return list of internal KexiDB system table names
177
 
     (kexi__*). This does not mean that these tables can be found
178
 
     in currently opened database. Just static list of table
179
 
     names is returned.
180
 
 
181
 
     The list contents may depend on KexiDB library version;
182
 
     opened database can contain fewer 'system' tables than in current
183
 
     KexiDB implementation, if the current one is newer than the one used
184
 
     to build the database. */
185
 
    static const QStringList& kexiDBSystemTableNames();
186
 
 
187
 
    /*! \return server version information for this connection.
188
 
     If database is not connected (i.e. isConnected() is false) 0 is returned. */
189
 
    KexiDB::ServerVersionInfo* serverVersion() const;
190
 
 
191
 
    /*! \return version information for this connection.
192
 
     If database is not used (i.e. isDatabaseUsed() is false) 0 is returned.
193
 
     It can be compared to drivers' and KexiDB library version to maintain
194
 
     backward/upward compatiblility. */
195
 
    KexiDB::DatabaseVersionInfo* databaseVersion() const;
196
 
 
197
 
    /*! \return DatabaseProperties object allowing to read and write global database properties
198
 
     for this connection. */
199
 
    DatabaseProperties& databaseProperties();
200
 
 
201
 
    /*! \return ids of all table schema names stored in currently
202
 
     used database. These ids can be later used as argument for tableSchema().
203
 
     This is a shortcut for objectIds(TableObjectType).
204
 
     Internal KexiDB system tables (kexi__*) are not available here
205
 
     because these have no identifiers assigned (more formally: id=-1).
206
 
 
207
 
     Note: the fact that given id is on the returned list does not mean
208
 
     that tableSchema( id ) returns anything. The table definition can be broken,
209
 
     so you have to double check this. */
210
 
    QList<int> tableIds();
211
 
 
212
 
    /*! \return ids of all database query schemas stored in currently
213
 
     used database. These ids can be later used as argument for querySchema().
214
 
     This is a shortcut for objectIds(QueryObjectType).
215
 
 
216
 
     Note: the fact that given id is on the returned list does not mean
217
 
     that querySchema( id ) returns anything. The query definition can be broken,
218
 
     so you have to double check this.
219
 
 
220
 
     @see tableIds()
221
 
     */
222
 
    QList<int> queryIds();
223
 
 
224
 
    /*! \return names of all schemas of object with \a objType type
225
 
     that are stored in currently used database.
226
 
 
227
 
     Note: the fact that given id is on the returned list does not mean
228
 
     that the definition of the object is valid,
229
 
     so you have to double check this.
230
 
 
231
 
     @see queryIds() */
232
 
    QList<int> objectIds(int objType);
233
 
 
234
 
    /*! \brief Creates new transaction handle and starts a new transaction.
235
 
     \return KexiDB::Transaction object if transaction has been started
236
 
     successfully, otherwise null transaction.
237
 
     For drivers that allow single transaction per connection
238
 
     (Driver::features() && SingleTransactions) this method can be called one time,
239
 
     and then this single transaction will be default ( setDefaultTransaction() will
240
 
     be called).
241
 
     For drivers that allow multiple transactions per connection, no default transaction is
242
 
     set automatically in beginTransaction() method, you could do this by hand.
243
 
     \sa setDefaultTransaction(), defaultTransaction().
244
 
    */
245
 
    Transaction beginTransaction();
246
 
 
247
 
    /*! \todo for nested transactions:
248
 
        Tansaction* beginTransaction(transaction *parent_transaction);
249
 
    */
250
 
    /*! Commits transaction \a trans.
251
 
     If there is not \a trans argument passed, and there is default transaction
252
 
     (obtained from defaultTransaction()) defined, this one will be committed.
253
 
     If default is not present, false is returned (when ignore_inactive is
254
 
     false, the default), or true is returned (when ignore_inactive is true).
255
 
 
256
 
     On successful commit, \a trans object will be destroyed.
257
 
     If this was default transaction, there is no default transaction for now.
258
 
    */
259
 
    bool commitTransaction(Transaction trans = Transaction(),
260
 
                           bool ignore_inactive = false);
261
 
 
262
 
    /*! Rollbacks transaction \a trans.
263
 
     If there is not \a trans argument passed, and there is default transaction
264
 
     (obtained from defaultTransaction()) defined, this one will be rolled back.
265
 
     If default is not present, false is returned (when ignore_inactive is
266
 
     false, the default), or true is returned (when ignore_inactive is true).
267
 
 
268
 
     or any error occurred, false is returned.
269
 
 
270
 
     On successful rollback, \a trans object will be destroyed.
271
 
     If this was default transaction, there is no default transaction for now.
272
 
    */
273
 
    bool rollbackTransaction(Transaction trans = Transaction(),
274
 
                             bool ignore_inactive = false);
275
 
 
276
 
    /*! \return handle for default transaction for this connection
277
 
     or null transaction if there is no such a transaction defined.
278
 
     If transactions are supported: Any operation on database (e.g. inserts)
279
 
     that is started without specifying transaction context, will be performed
280
 
     in the context of this transaction.
281
 
 
282
 
     Returned null transaction doesn't mean that there is no transactions
283
 
     started at all.
284
 
     Default transaction can be defined automatically for some drivers --
285
 
     see beginTransaction().
286
 
     \sa KexiDB::Driver::transactionsSupported()
287
 
    */
288
 
    Transaction& defaultTransaction() const;
289
 
 
290
 
    /*! Sets default transaction that will be used as context for operations
291
 
     on data in opened database for this connection. */
292
 
    void setDefaultTransaction(const Transaction& trans);
293
 
 
294
 
    /*! \return set of handles of currently active transactions.
295
 
     Note that in multithreading environment some of these
296
 
     transactions can be already inactive after calling this method.
297
 
     Use Transaction::active() to check that. Inactive transaction
298
 
     handle is useless and can be safely dropped.
299
 
    */
300
 
    const QList<Transaction>& transactions();
301
 
 
302
 
    /*! \return true if "auto commit" option is on.
303
 
 
304
 
     When auto commit is on (the default on for any new Connection object),
305
 
     every sql functional statement (statement that changes
306
 
     data in the database implicitly starts a new transaction.
307
 
     This transaction is automatically committed
308
 
     after successful statement execution or rolled back on error.
309
 
 
310
 
     For drivers that do not support transactions (see Driver::features())
311
 
     this method shouldn't be called because it does nothing ans always returns false.
312
 
 
313
 
     No internal KexiDB object should changes this option, although auto commit's
314
 
     behaviour depends on database engine's specifics. Engines that support only single
315
 
     transaction per connection (see Driver::SingleTransactions),
316
 
     use this single connection for autocommiting, so if there is already transaction
317
 
     started by the KexiDB user program (with beginTransaction()), this transaction
318
 
     is committed before any sql functional statement execution. In this situation
319
 
     default transaction is also affected (see defaultTransaction()).
320
 
 
321
 
     Only for drivers that support nested transactions (Driver::NestedTransactions),
322
 
     autocommiting works independently from previously started transaction,
323
 
 
324
 
     For other drivers set this option off if you need use transaction
325
 
     for grouping more statements together.
326
 
 
327
 
     NOTE: nested transactions are not yet implemented in KexiDB API.
328
 
    */
329
 
    bool autoCommit() const;
330
 
 
331
 
    /*! Changes auto commit option. This does not affect currently started transactions.
332
 
     This option can be changed even when connection is not established.
333
 
     \sa autoCommit() */
334
 
    bool setAutoCommit(bool on);
335
 
 
336
 
    /*! driver-specific string escaping */
337
 
//js: MOVED TO Driver  virtual QString escapeString(const QString& str) const = 0;
338
 
//  virtual QCString escapeString(const QCString& str) const = 0;
339
 
 
340
 
    /*! Prepares SELECT query described by raw \a statement.
341
 
     \return opened cursor created for results of this query
342
 
     or NULL if there was any error. Cursor can have optionally applied \a cursor_options
343
 
     (one of more selected from KexiDB::Cursor::Options).
344
 
     Preparation means that returned cursor is created but not opened.
345
 
     Open this when you would like to do it with Cursor::open().
346
 
 
347
 
     Note for driver developers: you should initialize cursor engine-specific
348
 
     resources and return Cursor subclass' object
349
 
     (passing \a statement and \a cursor_options to it's constructor).
350
 
    */
351
 
    virtual Cursor* prepareQuery(const QString& statement, uint cursor_options = 0) = 0;
352
 
 
353
 
    /*! \overload prepareQuery( const QString& statement = QString(), uint cursor_options = 0)
354
 
     Prepares query described by \a query schema. \a params are values of parameters that
355
 
     will be inserted into places marked with [] before execution of the query.
356
 
 
357
 
     Note for driver developers: you should initialize cursor engine-specific
358
 
     resources and return Cursor subclass' object
359
 
     (passing \a query and \a cursor_options to it's constructor).
360
 
     Kexi SQL and driver-specific escaping is performed on table names.
361
 
    */
362
 
    Cursor* prepareQuery(QuerySchema& query, const QList<QVariant>& params,
363
 
                         uint cursor_options = 0);
364
 
 
365
 
    /*! \overload prepareQuery( QuerySchema& query, const QList<QVariant>& params,
366
 
      uint cursor_options = 0 )
367
 
     Prepares query described by \a query schema without parameters.
368
 
    */
369
 
    virtual Cursor* prepareQuery(QuerySchema& query, uint cursor_options = 0) = 0;
370
 
 
371
 
    /*! \overload prepareQuery( const QString& statement = QString(), uint cursor_options = 0)
372
 
     Statement is build from data provided by \a table schema,
373
 
     it is like "select * from table_name".*/
374
 
    Cursor* prepareQuery(TableSchema& table, uint cursor_options = 0);
375
 
 
376
 
    /*! Executes SELECT query described by \a statement.
377
 
     \return opened cursor created for results of this query
378
 
     or NULL if there was any error on the cursor creation or opening.
379
 
     Cursor can have optionally applied \a cursor_options
380
 
     (one of more selected from KexiDB::Cursor::Options).
381
 
     Identifiers in \a statement that are the same as keywords in Kexi
382
 
     SQL or the backend's SQL need to have been escaped.
383
 
     */
384
 
    Cursor* executeQuery(const QString& statement, uint cursor_options = 0);
385
 
 
386
 
    /*! \overload executeQuery( const QString& statement, uint cursor_options = 0 )
387
 
     \a params are values of parameters that
388
 
     will be inserted into places marked with [] before execution of the query.
389
 
 
390
 
     Statement is build from data provided by \a query schema.
391
 
     Kexi SQL and driver-specific escaping is performed on table names. */
392
 
    Cursor* executeQuery(QuerySchema& query, const QList<QVariant>& params,
393
 
                         uint cursor_options = 0);
394
 
 
395
 
    /*! \overload executeQuery( QuerySchema& query, const QList<QVariant>& params,
396
 
      uint cursor_options = 0 ) */
397
 
    Cursor* executeQuery(QuerySchema& query, uint cursor_options = 0);
398
 
 
399
 
    /*! \overload executeQuery( const QString& statement, uint cursor_options = 0 )
400
 
     Executes query described by \a query schema without parameters.
401
 
     Statement is build from data provided by \a table schema,
402
 
     it is like "select * from table_name".*/
403
 
    Cursor* executeQuery(TableSchema& table, uint cursor_options = 0);
404
 
 
405
 
    /*! Deletes cursor \a cursor previously created by functions like executeQuery()
406
 
     for this connection.
407
 
     There is an attempt to close the cursor with Cursor::close() if it was opened.
408
 
     Anyway, at last cursor is deleted.
409
 
     \return true if cursor is properly closed before deletion. */
410
 
    bool deleteCursor(Cursor *cursor);
411
 
 
412
 
    /*! \return schema of a table pointed by \a tableId, retrieved from currently
413
 
     used database. The schema is cached inside connection,
414
 
     so retrieval is performed only once, on demand. */
415
 
    TableSchema* tableSchema(int tableId);
416
 
 
417
 
    /*! \return schema of a table pointed by \a tableName, retrieved from currently
418
 
     used database. KexiDB system table schema can be also retrieved.
419
 
     \sa tableSchema( int tableId ) */
420
 
    TableSchema* tableSchema(const QString& tableName);
421
 
 
422
 
    /*! \return schema of a query pointed by \a queryId, retrieved from currently
423
 
     used database. The schema is cached inside connection,
424
 
     so retrieval is performed only once, on demand. */
425
 
    QuerySchema* querySchema(int queryId);
426
 
 
427
 
    /*! \return schema of a query pointed by \a queryName, retrieved from currently
428
 
     used database.  \sa querySchema( int queryId ) */
429
 
    QuerySchema* querySchema(const QString& queryName);
430
 
 
431
 
    /*! Sets \a queryName query obsolete by moving it out of the query sets, so it will not be
432
 
     accessible by querySchema( const QString& queryName ). The existing query object is not
433
 
     destroyed, to avoid problems when it's referenced. In this case,
434
 
     a new query schema will be retrieved directly from the backend.
435
 
 
436
 
     For now it's used in KexiQueryDesignerGuiEditor::storeLayout().
437
 
     This solves the problem when user has changed a query schema but already form still uses
438
 
     previously instantiated query schema.
439
 
     \return true if there is such query. Otherwise the method does nothing. */
440
 
    bool setQuerySchemaObsolete(const QString& queryName);
441
 
 
442
 
//js: MOVED TO Driver  QString valueToSQL( const Field::Type ftype, const QVariant& v ) const;
443
 
//  QString valueToSQL( const Field *field, const QVariant& v ) const;
444
 
 
445
 
    /*! Executes \a sql query and stores first record's data inside \a data.
446
 
     This is convenient method when we need only first record from query result,
447
 
     or when we know that query result has only one record.
448
 
     If \a addLimitTo1 is true (the default), adds a LIMIT clause to the query,
449
 
     so \a sql should not include one already.
450
 
     \return true if query was successfully executed and first record has been found,
451
 
     false on data retrieving failure, and cancelled if there's no single record available. */
452
 
    tristate querySingleRecord(const QString& sql, RecordData &data, bool addLimitTo1 = true);
453
 
 
454
 
    /*! Like tristate querySingleRecord(const QString& sql, RecordData &data)
455
 
     but uses QuerySchema object.
456
 
     If \a addLimitTo1 is true (the default), adds a LIMIT clause to the query. */
457
 
    tristate querySingleRecord(QuerySchema& query, RecordData &data, bool addLimitTo1 = true);
458
 
 
459
 
    /*! Executes \a sql query and stores first record's field's (number \a column) string value
460
 
     inside \a value. For efficiency it's recommended that a query defined by \a sql
461
 
     should have just one field (SELECT one_field FROM ....).
462
 
     If \a addLimitTo1 is true (the default), adds a LIMIT clause to the query,
463
 
     so \a sql should not include one already.
464
 
     \return true if query was successfully executed and first record has been found,
465
 
     false on data retrieving failure, and cancelled if there's no single record available.
466
 
     \sa queryStringList() */
467
 
    tristate querySingleString(const QString& sql, QString &value, uint column = 0,
468
 
                               bool addLimitTo1 = true);
469
 
 
470
 
    /*! Convenience function: executes \a sql query and stores first
471
 
     record's field's (number \a column) value inside \a number. \sa querySingleString().
472
 
     Note: "LIMIT 1" is appended to \a sql statement if \a addLimitTo1 is true (the default).
473
 
     \return true if query was successfully executed and first record has been found,
474
 
     false on data retrieving failure, and cancelled if there's no single record available. */
475
 
    tristate querySingleNumber(const QString& sql, int &number, uint column = 0,
476
 
                               bool addLimitTo1 = true);
477
 
 
478
 
    /*! Executes \a sql query and stores Nth field's string value of every record
479
 
     inside \a list, where N is equal to \a column. The list is initially cleared.
480
 
     For efficiency it's recommended that a query defined by \a sql
481
 
     should have just one field (SELECT one_field FROM ....).
482
 
     \return true if all values were fetched successfuly,
483
 
     false on data retrieving failure. Returning empty list can be still a valid result.
484
 
     On errors, the list is not cleared, it may contain a few retrieved values. */
485
 
    bool queryStringList(const QString& sql, QStringList& list, uint column = 0);
486
 
 
487
 
    /*! \return true if there is at least one record returned in \a sql query.
488
 
     Does not fetch any records. \a success will be set to false
489
 
     on query execution errors (true otherwise), so you can see a difference between
490
 
     "no results" and "query execution error" states.
491
 
     Note: real executed query is: "SELECT 1 FROM (\a sql) LIMIT 1"
492
 
     if \a addLimitTo1 is true (the default). */
493
 
    bool resultExists(const QString& sql, bool &success, bool addLimitTo1 = true);
494
 
 
495
 
    /*! \return true if there is at least one record in \a table. */
496
 
    bool isEmpty(TableSchema& table, bool &success);
497
 
 
498
 
//! @todo perhaps use quint64 here?
499
 
    /*! \return number of records in \a sql query.
500
 
     Does not fetch any records. -1 is returned on query execution errors (>0 otherwise).
501
 
     Note: real executed query is: "SELECT COUNT() FROM (\a sql) LIMIT 1"
502
 
     (using querySingleNumber()) */
503
 
    int resultCount(const QString& sql);
504
 
 
505
 
    //PROTOTYPE:
506
 
#define A , const QVariant&
507
 
#define H_INS_REC(args) bool insertRecord(TableSchema &tableSchema args)
508
 
#define H_INS_REC_ALL \
509
 
    H_INS_REC(A); \
510
 
    H_INS_REC(A A); \
511
 
    H_INS_REC(A A A); \
512
 
    H_INS_REC(A A A A); \
513
 
    H_INS_REC(A A A A A); \
514
 
    H_INS_REC(A A A A A A); \
515
 
    H_INS_REC(A A A A A A A); \
516
 
    H_INS_REC(A A A A A A A A)
517
 
    H_INS_REC_ALL;
518
 
 
519
 
#undef H_INS_REC
520
 
#define H_INS_REC(args) bool insertRecord(FieldList& fields args)
521
 
 
522
 
    H_INS_REC_ALL;
523
 
#undef H_INS_REC_ALL
524
 
#undef H_INS_REC
525
 
#undef A
526
 
 
527
 
    bool insertRecord(TableSchema &tableSchema, const QList<QVariant>& values);
528
 
 
529
 
    bool insertRecord(FieldList& fields, const QList<QVariant>& values);
530
 
 
531
 
    /*! Creates table defined by \a tableSchema.
532
 
     Schema information is also added into kexi system tables, for later reuse.
533
 
     \return true on success - \a tableSchema object is then
534
 
     inserted to Connection structures - it is owned by Connection object now,
535
 
     so you shouldn't destroy the tableSchema object by hand
536
 
     (or declare it as local-scope variable).
537
 
 
538
 
     If \a replaceExisting is false (the default) and table with the same name
539
 
     (as tableSchema->name()) exists, false is returned.
540
 
     If \a replaceExisting is true, a table schema with the same name (if exists)
541
 
     is overwritten, then a new table schema gets the same identifier
542
 
     as existing table schema's identifier.
543
 
 
544
 
     Note that on error:
545
 
     - \a tableSchema is not inserted into Connection's structures,
546
 
       so you are still owner of this object
547
 
     - existing table schema object is not destroyed (i.e. it is still available
548
 
       e.g. using Connection::tableSchema(const QString& ), even if the table
549
 
       was physically dropped.
550
 
    */
551
 
    bool createTable(TableSchema* tableSchema, bool replaceExisting = false);
552
 
 
553
 
    /*! Drops a table defined by \a tableSchema (both table object as well as physically).
554
 
     If true is returned, schema information \a tableSchema is destoyed
555
 
     (because it's owned), so don't keep this anymore!
556
 
     No error is raised if the table does not exist physically
557
 
     - its schema is removed even in this case.
558
 
    */
559
 
//! @todo (js): update any structure (e.g. query) that depend on this table!
560
 
    tristate dropTable(TableSchema* tableSchema);
561
 
 
562
 
    /*! It is a convenience function, does exactly the same as
563
 
     bool dropTable( KexiDB::TableSchema* tableSchema ) */
564
 
    tristate dropTable(const QString& table);
565
 
 
566
 
    /*! Alters \a tableSchema using \a newTableSchema in memory and on the db backend.
567
 
     \return true on success, cancelled if altering was cancelled. */
568
 
//! @todo (js): implement real altering
569
 
//! @todo (js): update any structure (e.g. query) that depend on this table!
570
 
    tristate alterTable(TableSchema& tableSchema, TableSchema& newTableSchema);
571
 
 
572
 
    /*! Alters name of table described by \a tableSchema to \a newName.
573
 
     If \a replace is true, destination table is completely dropped and replaced
574
 
     by \a tableSchema, if present. In this case, identifier of
575
 
     \a tableSchema becomes equal to the dropped table's id, what can be useful
576
 
     if \a tableSchema was created with a temporary name and ID (used in AlterTableHandler).
577
 
 
578
 
     If \a replace is false (the default) and destination table is present
579
 
     -- false is returned and ERR_OBJECT_EXISTS error is set.
580
 
     The schema of \a tableSchema is updated on success.
581
 
     \return true on success. */
582
 
    bool alterTableName(TableSchema& tableSchema, const QString& newName, bool replace = false);
583
 
 
584
 
    /*! Drops a query defined by \a querySchema.
585
 
     If true is returned, schema information \a querySchema is destoyed
586
 
     (because it's owned), so don't keep this anymore!
587
 
    */
588
 
    bool dropQuery(QuerySchema* querySchema);
589
 
 
590
 
    /*! It is a convenience function, does exactly the same as
591
 
     bool dropQuery( KexiDB::QuerySchema* querySchema ) */
592
 
    bool dropQuery(const QString& query);
593
 
 
594
 
    /*! Removes information about object with \a objId
595
 
     from internal "kexi__object" and "kexi__objectdata" tables.
596
 
     \return true on success. */
597
 
    bool removeObject(uint objId);
598
 
 
599
 
    /*! \return first field from \a fieldlist that has system name,
600
 
     null if there are no such field.
601
 
     For checking, Driver::isSystemFieldName() is used, so this check can
602
 
     be driver-dependent. */
603
 
    Field* findSystemFieldName(const FieldList& fieldlist);
604
 
 
605
 
    /*! \return name of any (e.g. first found) database for this connection.
606
 
     This method does not close or open this connection. The method can be used
607
 
     (it is also internally used, e.g. for database dropping) when we need
608
 
     a database name before we can connect and execute any SQL statement
609
 
     (e.g. DROP DATABASE).
610
 
 
611
 
     The method can return nul lstring, but in this situation no automatic (implicit)
612
 
     connections could be made, what is useful by e.g. dropDatabase().
613
 
 
614
 
     Note for driver developers: return here a name of database which you are sure
615
 
     is existing.
616
 
     Default implementation returns:
617
 
     - value that previously had been set using setAvailableDatabaseName() for
618
 
       this connection, if it is not empty
619
 
     - else (2nd priority): value of DriverBehaviour::ALWAYS_AVAILABLE_DATABASE_NAME
620
 
     if it is not empty.
621
 
 
622
 
     See decription of DriverBehaviour::ALWAYS_AVAILABLE_DATABASE_NAME member.
623
 
     You may want to reimplement this method only when you need to depend on
624
 
     this connection specifics
625
 
     (e.g. you need to check something remotely).
626
 
    */
627
 
    virtual QString anyAvailableDatabaseName();
628
 
 
629
 
    /*! Sets \a dbName as name of a database that can be accessible.
630
 
     This is option that e.g. application that make use of KexiDB library can set
631
 
     to tune connection's behaviour when it needs to temporary connect to any database
632
 
     in the server to do some work.
633
 
     You can pass empty dbName - then anyAvailableDatabaseName() will try return
634
 
     DriverBehaviour::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value
635
 
     instead of the one previously set with setAvailableDatabaseName().
636
 
 
637
 
     \sa anyAvailableDatabaseName()
638
 
    */
639
 
    void setAvailableDatabaseName(const QString& dbName);
640
 
 
641
 
    /*! Because some engines need to have opened any database before
642
 
     executing administrative sql statements like "create database" or "drop database",
643
 
     this method is used to use appropriate, existing database for this connection.
644
 
     For file-based db drivers this always return true and does not set tmpdbName
645
 
     to any value. For other db drivers: this sets tmpdbName to db name computed
646
 
     using anyAvailableDatabaseName(), and if the name computed is empty, false
647
 
     is returned; if it is not empty, useDatabase() is called.
648
 
     False is returned also when useDatabase() fails.
649
 
     You can call this method from your application's level if you really want to perform
650
 
     tasks that require any used database. In such a case don't forget
651
 
     to closeDatabase() if returned tmpdbName is not empty.
652
 
 
653
 
     Note: This method has nothing to do with creating or using temporary databases
654
 
     in such meaning that these database are not persistent
655
 
    */
656
 
    bool useTemporaryDatabaseIfNeeded(QString &tmpdbName);
657
 
 
658
 
    /*! \return autoincrement field's \a aiFieldName value
659
 
     of last inserted record. This refers \a tableName table.
660
 
 
661
 
     Simply, method internally fetches last inserted record and returns selected
662
 
     field's value. Requirements: field must be of integer type, there must be a
663
 
     record inserted in current database session (whatever this means).
664
 
     On error (quint64)-1 is returned.
665
 
     Last inserted record is identified by magical record identifier, usually called
666
 
     ROWID (PostgreSQL has it as well as SQLite;
667
 
     see DriverBehaviour::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE).
668
 
     ROWID's value will be assigned back to \a ROWID if this pointer is not null.
669
 
    */
670
 
    quint64 lastInsertedAutoIncValue(const QString& aiFieldName, const QString& tableName,
671
 
                                     quint64* ROWID = 0);
672
 
 
673
 
    /*! \overload int lastInsertedAutoIncValue(const QString&, const QString&, quint64*)
674
 
    */
675
 
    quint64 lastInsertedAutoIncValue(const QString& aiFieldName,
676
 
                                     const TableSchema& table, quint64* ROWID = 0);
677
 
 
678
 
    /*! Executes query \a statement, but without returning resulting
679
 
     rows (used mostly for functional queries).
680
 
     Only use this method if you really need. */
681
 
    bool executeSQL(const QString& statement);
682
 
 
683
 
    //! @short options used in selectStatement()
684
 
    class KEXI_DB_EXPORT SelectStatementOptions
685
 
    {
686
 
    public:
687
 
        SelectStatementOptions();
688
 
        ~SelectStatementOptions();
689
 
 
690
 
        //! A mode for escaping identifier, Driver::EscapeDriver|Driver::EscapeAsNecessary by default
691
 
        int identifierEscaping;
692
 
 
693
 
        //! True if ROWID should be also retrieved. False by default.
694
 
        bool alsoRetrieveROWID : 1;
695
 
 
696
 
        /*! True if relations (LEFT OUTER JOIN) for visible lookup columns should be added.
697
 
         True by default. This is set to false when user-visible statement is generated
698
 
         e.g. for the Query Designer. */
699
 
        bool addVisibleLookupColumns : 1;
700
 
    };
701
 
 
702
 
    /*! \return "SELECT ..." statement's string needed for executing query
703
 
     defined by \a querySchema, \a params and \a options. */
704
 
    QString selectStatement(QuerySchema& querySchema,
705
 
                            const QList<QVariant>& params,
706
 
                            const SelectStatementOptions& options = SelectStatementOptions()) const;
707
 
 
708
 
    /*! \overload QString selectStatement( QuerySchema& querySchema,
709
 
      QList<QVariant> params = QList<QVariant>(),
710
 
      const SelectStatementOptions& options = SelectStatementOptions() ) const;
711
 
     \return "SELECT ..." statement's string needed for executing query
712
 
     defined by \a querySchema. */
713
 
    inline QString selectStatement(QuerySchema& querySchema,
714
 
                                   const SelectStatementOptions& options = SelectStatementOptions()) const {
715
 
        return selectStatement(querySchema, QList<QVariant>(), options);
716
 
    }
717
 
 
718
 
    /*! Stores object's schema data (id, name, caption, help text)
719
 
     described by \a sdata on the backend.
720
 
     If \a newObject is true, new entry is created,
721
 
     and (when sdata.id() was <=0), new, unique object identifier
722
 
     is obtained and assigned to \a sdata (see SchemaData::id()).
723
 
 
724
 
     If \a newObject is false, it's expected that entry on the
725
 
     backend already exists, so it's updated (changes to identifier are not allowed).
726
 
     \return true on success. */
727
 
    bool storeObjectSchemaData(SchemaData &sdata, bool newObject);
728
 
 
729
 
    /*! Added for convenience.
730
 
     \sa setupObjectSchemaData( const KexiDB::RecordData &data, SchemaData &sdata ).
731
 
     \return true on success, false on failure and cancelled when such object couldn't */
732
 
    tristate loadObjectSchemaData(int objectID, SchemaData &sdata);
733
 
 
734
 
    /*! Finds object schema data for object of type \a objectType and name \a objectName.
735
 
     If the object is found, resulted schema is stored in \a sdata and true is returned,
736
 
     otherwise false is returned. */
737
 
    tristate loadObjectSchemaData(int objectType, const QString& objectName, SchemaData &sdata);
738
 
 
739
 
    /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID
740
 
     and puts it to \a dataString. The can be block indexed with optional \a dataID.
741
 
     \return true on success, false on failure and cancelled when there is no such data block
742
 
     \sa storeDataBlock(). */
743
 
    tristate loadDataBlock(int objectID, QString &dataString, const QString& dataID);
744
 
 
745
 
    /*! Stores (potentially large) data block \a dataString (e.g. xml form's representation),
746
 
     referenced by objectID. Block will be stored in "kexi__objectdata" table and
747
 
     an optional \a dataID identifier.
748
 
     If there is already such record in the table, it's simply overwritten.
749
 
     \return true on success
750
 
     \sa loadDataBlock(). */
751
 
    bool storeDataBlock(int objectID, const QString &dataString,
752
 
                        const QString& dataID = QString());
753
 
 
754
 
    /*! Removes (potentially large) string data (e.g. xml form's representation),
755
 
     referenced by objectID, and pointed by optional \a dataID.
756
 
     \return true on success. Does not fail if the block does not exist.
757
 
     Note that if \a dataID is not specified, all data blocks for this dialog will be removed.
758
 
     \sa loadDataBlock() storeDataBlock(). */
759
 
    bool removeDataBlock(int objectID, const QString& dataID = QString());
760
 
 
761
 
    class KEXI_DB_EXPORT TableSchemaChangeListenerInterface
762
 
    {
763
 
    public:
764
 
        TableSchemaChangeListenerInterface() {}
765
 
        virtual ~TableSchemaChangeListenerInterface() {}
766
 
 
767
 
        /*! Closes listening object so it will be deleted and thus no longer use
768
 
         a conflicting table schema. */
769
 
        virtual tristate closeListener() = 0;
770
 
 
771
 
        /*! i18n'd string that can be displayed for user to inform about
772
 
         e.g. conflicting listeners. */
773
 
        QString listenerInfoString;
774
 
    };
775
 
//TMP// TODO: will be more generic
776
 
    /** Register \a listener for receiving (listening) information about changes
777
 
     in TableSchema object. Changes could be: altering and removing. */
778
 
    void registerForTableSchemaChanges(TableSchemaChangeListenerInterface& listener,
779
 
                                       TableSchema& schema);
780
 
 
781
 
    void unregisterForTableSchemaChanges(TableSchemaChangeListenerInterface& listener,
782
 
                                         TableSchema &schema);
783
 
 
784
 
    void unregisterForTablesSchemaChanges(TableSchemaChangeListenerInterface& listener);
785
 
 
786
 
    QSet<Connection::TableSchemaChangeListenerInterface*>*
787
 
    tableSchemaChangeListeners(TableSchema& tableSchema) const;
788
 
 
789
 
    tristate closeAllTableSchemaChangeListeners(TableSchema& tableSchema);
790
 
 
791
 
//! @todo move this somewhere to low level class (MIGRATION?)
792
 
    /*! LOW LEVEL METHOD. For reimplementation: returns true if table
793
 
     with name \a tableName exists in the database.
794
 
     \return false if it does not exist or error occurred.
795
 
     The lookup is case insensitive. */
796
 
    virtual bool drv_containsTable(const QString &tableName) = 0;
797
 
 
798
 
    /*! Creates table using \a tableSchema information.
799
 
     \return true on success. Default implementation
800
 
     builds a statement using createTableStatement() and calls drv_executeSQL()
801
 
     Note for driver developers: reimplement this only if you want do to
802
 
     this in other way.
803
 
 
804
 
     Moved to public for KexiMigrate.
805
 
     @todo fix this after refactoring
806
 
     */
807
 
    virtual bool drv_createTable(const TableSchema& tableSchema);
808
 
 
809
 
    /*! Alters table's described \a tableSchema name to \a newName.
810
 
     This is the default implementation, using "ALTER TABLE <oldname> RENAME TO <newname>",
811
 
     what's supported by SQLite >= 3.2, PostgreSQL, MySQL.
812
 
     Backends lacking ALTER TABLE can reimplement this with by an inefficient
813
 
     data copying to a new table. In any case, renaming is performed at the backend.
814
 
     It's good idea to keep the operation within a transaction.
815
 
     \return true on success.
816
 
 
817
 
     Moved to public for KexiProject.
818
 
     @todo fix this after refactoring
819
 
    */
820
 
    virtual bool drv_alterTableName(TableSchema& tableSchema, const QString& newName);
821
 
 
822
 
    /*! Physically drops table named with \a name.
823
 
     Default impelmentation executes "DROP TABLE.." command,
824
 
     so you rarely want to change this.
825
 
 
826
 
      Moved to public for KexiMigrate
827
 
      @todo fix this after refatoring
828
 
    */
829
 
    virtual bool drv_dropTable(const QString& name);
830
 
 
831
 
    /*! Prepare a SQL statement and return a \a PreparedStatement instance. */
832
 
    virtual PreparedStatement::Ptr prepareStatement(PreparedStatement::StatementType type,
833
 
            FieldList& fields) = 0;
834
 
 
835
 
    bool isInternalTableSchema(const QString& tableName);
836
 
 
837
 
    /*! Setups schema data for object that owns sdata (e.g. table, query)
838
 
      using \a cursor opened on 'kexi__objects' table, pointing to a record
839
 
      corresponding to given object.
840
 
 
841
 
      Moved to public for KexiMigrate
842
 
      @todo fix this after refatoring
843
 
    */
844
 
    bool setupObjectSchemaData(const RecordData &data, SchemaData &sdata);
845
 
 
846
 
    /*! \return a new field table schema for a table retrieved from \a data.
847
 
     Used internally by tableSchema().
848
 
 
849
 
      Moved to public for KexiMigrate
850
 
      @todo fix this after refatoring
851
 
    */
852
 
    KexiDB::Field* setupField(const RecordData &data);
853
 
 
854
 
    /*! @internal. Inserts internal table to Connection's structures, so it can be found by name.
855
 
     This method is used for example in KexiProject to insert information about "kexi__blobs"
856
 
     table schema. Use createTable() to physically create table. After createTable()
857
 
     calling insertInternalTable() is not required.
858
 
     Also used internally by Connection::newKexiDBSystemTableSchema(const QString&) */
859
 
    void insertInternalTable(TableSchema& tableSchema);
860
 
 
861
 
protected:
862
 
    /*! Used by Driver */
863
 
    Connection(Driver *driver, ConnectionData &conn_data);
864
 
 
865
 
    /*! Method to be called form Connection's subclass destructor.
866
 
     \sa ~Connection() */
867
 
    void destroy();
868
 
 
869
 
    /*! @internal drops table \a tableSchema physically, but destroys
870
 
     \a tableSchema object only if \a alsoRemoveSchema is true.
871
 
     Used (alsoRemoveSchema==false) on table altering:
872
 
     if recreating table can failed we're giving up and keeping
873
 
     the original table schema (even if it is no longer points to any real data). */
874
 
    tristate dropTable(KexiDB::TableSchema* tableSchema, bool alsoRemoveSchema);
875
 
 
876
 
    /*! For reimplementation: connects to database. \a version should be set to real
877
 
     server's version.
878
 
      \return true on success. */
879
 
    virtual bool drv_connect(KexiDB::ServerVersionInfo& version) = 0;
880
 
 
881
 
    /*! For reimplementation: disconnects database
882
 
      \return true on success. */
883
 
    virtual bool drv_disconnect() = 0;
884
 
 
885
 
    /*! Executes query \a statement, but without returning resulting
886
 
     rows (used mostly for functional queries).
887
 
     Only use this method if you really need. */
888
 
    virtual bool drv_executeSQL(const QString& statement) = 0;
889
 
 
890
 
    /*! For reimplementation: loads list of databases' names available for this connection
891
 
     and adds these names to \a list. If your server is not able to offer such a list,
892
 
     consider reimplementing drv_databaseExists() instead.
893
 
     The method should return true only if there was no error on getting database names
894
 
     list from the server.
895
 
     Default implementation puts empty list into \a list and returns true. */
896
 
    virtual bool drv_getDatabasesList(QStringList &list);
897
 
 
898
 
//! @todo move this somewhere to low level class (MIGRATION?)
899
 
    /*! LOW LEVEL METHOD. For reimplementation: loads low-level list of table names
900
 
     available for this connection. The names are in lower case.
901
 
     The method should return true only if there was no error on getting database names
902
 
     list from the server. */
903
 
    virtual bool drv_getTablesList(QStringList &list) = 0;
904
 
 
905
 
    /*! For optional reimplementation: asks server if database \a dbName exists.
906
 
     This method is used internally in databaseExists(). The default  implementation
907
 
     calls databaseNames and checks if that list contains \a dbName. If you need to
908
 
     ask the server specifically if a database exists, eg. if you can't retrieve a list
909
 
     of all available database names, please reimplement this method and do all
910
 
     needed checks.
911
 
 
912
 
     See databaseExists() description for details about ignoreErrors argument.
913
 
     You should use it properly in your implementation.
914
 
 
915
 
     Note: This method should also work if there is already database used (with useDatabase());
916
 
     in this situation no changes should be made in current database selection. */
917
 
    virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true);
918
 
 
919
 
    /*! For reimplementation: creates new database using connection */
920
 
    virtual bool drv_createDatabase(const QString &dbName = QString()) = 0;
921
 
 
922
 
    /*! For reimplementation: opens existing database using connection
923
 
     \return true on success, false on failure and cancelled if user has cancelled this action. */
924
 
    virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = 0,
925
 
                                 MessageHandler* msgHandler = 0) = 0;
926
 
 
927
 
    /*! For reimplementation: closes previously opened database
928
 
      using connection. */
929
 
    virtual bool drv_closeDatabase() = 0;
930
 
 
931
 
    /*! \return true if internal driver's structure is still in opened/connected
932
 
     state and database is used.
933
 
     Note for driver developers: Put here every test that you can do using your
934
 
     internal engine's database API,
935
 
     eg (a bit schematic):  my_connection_struct->isConnected()==true.
936
 
     Do not check things like Connection::isDatabaseUsed() here or other things
937
 
     that "KexiDB already knows" at its level.
938
 
     If you cannot test anything, just leave default implementation (that returns true).
939
 
 
940
 
     Result of this method is used as an additional chance to check for isDatabaseUsed().
941
 
     Do not call this method from your driver's code, it should be used at KexiDB
942
 
     level only.
943
 
    */
944
 
    virtual bool drv_isDatabaseUsed() const {
945
 
        return true;
946
 
    }
947
 
 
948
 
    /*! For reimplementation: drops database from the server
949
 
      using connection. After drop, database shouldn't be accessible
950
 
      anymore. */
951
 
    virtual bool drv_dropDatabase(const QString &dbName = QString()) = 0;
952
 
 
953
 
    /*! \return "CREATE TABLE ..." statement string needed for \a tableSchema
954
 
     creation in the database.
955
 
 
956
 
     Note: The statement string can be specific for this connection's driver database,
957
 
     and thus not reusable in general.
958
 
    */
959
 
    QString createTableStatement(const TableSchema& tableSchema) const;
960
 
 
961
 
 
962
 
    /*! \return "SELECT ..." statement's string needed for executing query
963
 
     defined by "select * from table_name" where <i>table_name</i> is \a tableSchema's name.
964
 
     This method's variant can be useful when there is no appropriate QuerySchema defined.
965
 
 
966
 
     Note: The statement string can be specific for this connection's driver database,
967
 
     and thus not reusable in general.
968
 
    */
969
 
    QString selectStatement(TableSchema& tableSchema,
970
 
                            const SelectStatementOptions& options = SelectStatementOptions()) const;
971
 
 
972
 
    /*!
973
 
     Creates table named by \a tableSchemaName. Schema object must be on
974
 
     schema tables' list before calling this method (otherwise false if returned).
975
 
     Just uses drv_createTable( const KexiDB::TableSchema& tableSchema ).
976
 
     Used internally, e.g. in createDatabase().
977
 
     \return true on success
978
 
    */
979
 
    virtual bool drv_createTable(const QString& tableSchemaName);
980
 
 
981
 
//  /*! Executes query \a statement and returns resulting rows
982
 
//   (used mostly for SELECT query). */
983
 
//  virtual bool drv_executeQuery( const QString& statement ) = 0;
984
 
 
985
 
    /*! \return unique identifier of last inserted row.
986
 
     Typically this is just primary key value.
987
 
     This identifier could be reused when we want to reference
988
 
     just inserted row.
989
 
     Note for driver developers: contact staniek (at) kde.org
990
 
     if your engine do not offers this information. */
991
 
    virtual quint64 drv_lastInsertRowID() = 0;
992
 
 
993
 
    /*! Note for driver developers: begins new transaction
994
 
     and returns handle to it. Default implementation just
995
 
     executes "BEGIN" sql statement and returns just empty data (TransactionData object).
996
 
 
997
 
     Drivers that do not support transactions (see Driver::features())
998
 
     do never call this method.
999
 
     Reimplement this method if you need to do something more
1000
 
     (e.g. if you driver will support multiple transactions per connection).
1001
 
     Make subclass of TransactionData (declared in transaction.h)
1002
 
     and return object of this subclass.
1003
 
     You should return NULL if any error occurred.
1004
 
     Do not check anything in connection (isConnected(), etc.) - all is already done.
1005
 
    */
1006
 
    virtual TransactionData* drv_beginTransaction();
1007
 
 
1008
 
    /*! Note for driver developers: begins new transaction
1009
 
     and returns handle to it. Default implementation just
1010
 
     executes "COMMIT" sql statement and returns true on success.
1011
 
 
1012
 
     \sa drv_beginTransaction()
1013
 
    */
1014
 
    virtual bool drv_commitTransaction(TransactionData* trans);
1015
 
 
1016
 
    /*! Note for driver developers: begins new transaction
1017
 
     and returns handle to it. Default implementation just
1018
 
     executes "ROLLBACK" sql statement and returns true on success.
1019
 
 
1020
 
     \sa drv_beginTransaction()
1021
 
    */
1022
 
    virtual bool drv_rollbackTransaction(TransactionData* trans);
1023
 
 
1024
 
 
1025
 
    /*! Preprocessing (if any) required by drivers before execution of an
1026
 
        Insert statement.
1027
 
        Reimplement this method in your driver if there are any special processing steps to be
1028
 
        executed before an Insert statement.
1029
 
      \sa drv_afterInsert()
1030
 
    */
1031
 
    virtual bool drv_beforeInsert(const QString& table, FieldList& fields) {
1032
 
        Q_UNUSED(table);
1033
 
        Q_UNUSED(fields);
1034
 
        return true;
1035
 
    }
1036
 
 
1037
 
    /*! Postprocessing (if any) required by drivers before execution of an
1038
 
        Insert statement.
1039
 
        Reimplement this method in your driver if there are any special processing steps to be
1040
 
        executed after an Insert statement.
1041
 
      \sa drv_beforeInsert()
1042
 
    */
1043
 
    virtual bool drv_afterInsert(const QString& table, FieldList& fields) {
1044
 
        Q_UNUSED(table);
1045
 
        Q_UNUSED(fields);
1046
 
        return true;
1047
 
    }
1048
 
 
1049
 
    /*! Preprocessing required by drivers before execution of an
1050
 
        Update statement.
1051
 
        Reimplement this method in your driver if there are any special processing steps to be
1052
 
        executed before an Update statement.
1053
 
    \sa drv_afterUpdate()
1054
 
    */
1055
 
    virtual bool drv_beforeUpdate(const QString& table, FieldList& fields) {
1056
 
        Q_UNUSED(table);
1057
 
        Q_UNUSED(fields);
1058
 
        return true;
1059
 
    }
1060
 
 
1061
 
    /*! Postprocessing required by drivers before execution of an
1062
 
        Insert statement.
1063
 
        Reimplement this method in your driver if there are any special processing steps to be
1064
 
        executed after an Update statement.
1065
 
      \sa drv_beforeUpdate()
1066
 
    */
1067
 
    virtual bool drv_afterUpdate(const QString& table, FieldList& fields) {
1068
 
        Q_UNUSED(table);
1069
 
        Q_UNUSED(fields);
1070
 
        return true;
1071
 
    }
1072
 
 
1073
 
 
1074
 
    /*! Changes autocommiting option for established connection.
1075
 
      \return true on success.
1076
 
 
1077
 
      Note for driver developers: reimplement this only if your engine
1078
 
      allows to set special auto commit option (like "SET AUTOCOMMIT=.." in MySQL).
1079
 
      If not, auto commit behaviour will be simulated if at least single
1080
 
      transactions per connection are supported by the engine.
1081
 
      Do not set any internal flags for autocommiting -- it is already done inside
1082
 
      setAutoCommit().
1083
 
 
1084
 
      Default implementation does nothing with connection, just returns true.
1085
 
 
1086
 
      \sa drv_beginTransaction(), autoCommit(), setAutoCommit()
1087
 
     */
1088
 
    virtual bool drv_setAutoCommit(bool on);
1089
 
 
1090
 
    /*! Internal, for handling autocommited transactions:
1091
 
     begins transaction if one is supported.
1092
 
     \return true if new transaction started
1093
 
     successfully or no transactions are supported at all by the driver
1094
 
     or if autocommit option is turned off.
1095
 
     A handle to a newly created transaction (or null on error) is passed
1096
 
     to \a tg parameter.
1097
 
 
1098
 
     Special case when used database driver has only single transaction support
1099
 
     (Driver::SingleTransactions):
1100
 
     and there is already transaction started, it is committed before
1101
 
     starting a new one, but only if this transaction has been started inside Connection object.
1102
 
     (i.e. by beginAutoCommitTransaction()). Otherwise, a new transaction will not be started,
1103
 
     but true will be returned immediately.
1104
 
    */
1105
 
    bool beginAutoCommitTransaction(TransactionGuard& tg);
1106
 
 
1107
 
    /*! Internal, for handling autocommited transactions:
1108
 
     Commits transaction prevoiusly started with beginAutoCommitTransaction().
1109
 
     \return true on success or when no transactions are supported
1110
 
     at all by the driver.
1111
 
 
1112
 
     Special case when used database driver has only single transaction support
1113
 
     (Driver::SingleTransactions): if \a trans has been started outside Connection object
1114
 
     (i.e. not by beginAutoCommitTransaction()), the transaction will not be committed.
1115
 
    */
1116
 
    bool commitAutoCommitTransaction(const Transaction& trans);
1117
 
 
1118
 
    /*! Internal, for handling autocommited transactions:
1119
 
     Rollbacks transaction prevoiusly started with beginAutoCommitTransaction().
1120
 
     \return true on success or when no transactions are supported
1121
 
     at all by the driver.
1122
 
 
1123
 
     Special case when used database driver has only single transaction support
1124
 
     (Driver::SingleTransactions): \a trans will not be rolled back
1125
 
     if it has been started outside this Connection object.
1126
 
    */
1127
 
    bool rollbackAutoCommitTransaction(const Transaction& trans);
1128
 
 
1129
 
    /*! Creates cursor data and initializes cursor
1130
 
      using \a statement for later data retrieval. */
1131
 
//  virtual CursorData* drv_createCursor( const QString& statement ) = 0;
1132
 
    /*! Closes and deletes cursor data. */
1133
 
//  virtual bool drv_deleteCursor( CursorData *data ) = 0;
1134
 
 
1135
 
    /*! Helper: checks if connection is established;
1136
 
      if not: error message is set up and false returned */
1137
 
    bool checkConnected();
1138
 
 
1139
 
    /*! Helper: checks both if connection is established and database any is used;
1140
 
      if not: error message is set up and false returned */
1141
 
    bool checkIsDatabaseUsed();
1142
 
 
1143
 
    /*! \return a full table schema for a table retrieved using 'kexi__*' system tables.
1144
 
     Used internally by tableSchema() methods. */
1145
 
    TableSchema* setupTableSchema(const RecordData &data);
1146
 
 
1147
 
    /*! \return a full query schema for a query using 'kexi__*' system tables.
1148
 
     Used internally by querySchema() methods. */
1149
 
    QuerySchema* setupQuerySchema(const RecordData &data);
1150
 
 
1151
 
    /*! Update a row. */
1152
 
    bool updateRow(QuerySchema &query, RecordData& data, RowEditBuffer& buf, bool useROWID = false);
1153
 
    /*! Insert a new row. */
1154
 
    bool insertRow(QuerySchema &query, RecordData& data, RowEditBuffer& buf, bool getROWID = false);
1155
 
    /*! Delete an existing row. */
1156
 
    bool deleteRow(QuerySchema &query, RecordData& data, bool useROWID = false);
1157
 
    /*! Delete all existing rows. */
1158
 
    bool deleteAllRows(QuerySchema &query);
1159
 
 
1160
 
    /*! Allocates all needed table KexiDB system objects for kexi__* KexiDB liblary's
1161
 
     system tables schema.
1162
 
     These objects are used internally in this connection
1163
 
     and are added to list of tables (by name,
1164
 
     not by id because these have no ids).
1165
 
    */
1166
 
    bool setupKexiDBSystemSchema();
1167
 
 
1168
 
    /*! used internally by setupKexiDBSystemSchema():
1169
 
     Allocates single table KexiDB system object named \a tsname
1170
 
     and adds this to list of such objects (for later removal on closeDatabase()).
1171
 
    */
1172
 
    TableSchema* newKexiDBSystemTableSchema(const QString& tsname);
1173
 
 
1174
 
    //! Identifier escaping function in the associated Driver.
1175
 
    /*! Calls the identifier escaping function in the associated Driver to
1176
 
     escape table and column names.  This should be used when explicitly
1177
 
     constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)).
1178
 
     It should not be used for other functions (e.g. don't do
1179
 
     useDatabase(escapeIdentifier(database))), because the identifier will
1180
 
     be escaped when the called function generates, for example, "USE " +
1181
 
     escapeIdentifier(database).
1182
 
 
1183
 
     For efficiency, kexi__* system tables and columns therein are not escaped
1184
 
     - we assume these are valid identifiers for all drivers.
1185
 
    */
1186
 
    inline QString escapeIdentifier(const QString& id,
1187
 
                                    int escaping = Driver::EscapeDriver | Driver::EscapeAsNecessary) const {
1188
 
        return m_driver->escapeIdentifier(id, escaping);
1189
 
    }
1190
 
 
1191
 
    /*! Called by TableSchema -- signals destruction to Connection object
1192
 
     To avoid having deleted table object on its list. */
1193
 
    void removeMe(TableSchema *ts);
1194
 
 
1195
 
    /*! @internal
1196
 
     \return true if the cursor \a cursor contains column \a column,
1197
 
     else, sets appropriate error with a message and returns false. */
1198
 
    bool checkIfColumnExists(Cursor *cursor, uint column);
1199
 
 
1200
 
    /*! @internal used by querySingleRecord() methods.
1201
 
     Note: "LIMIT 1" is appended to \a sql statement if \a addLimitTo1 is true (the default). */
1202
 
    tristate querySingleRecordInternal(RecordData &data, const QString* sql,
1203
 
                                       QuerySchema* query, bool addLimitTo1 = true);
1204
 
 
1205
 
    /*! @internal used by Driver::createConnection().
1206
 
     Only works if connection is not yet established. */
1207
 
    void setReadOnly(bool set);
1208
 
 
1209
 
    /*! Loads extended schema information for table \a tableSchema,
1210
 
     if present (see ExtendedTableSchemaInformation in Kexi Wiki).
1211
 
     \return true on success */
1212
 
    bool loadExtendedTableSchemaData(TableSchema& tableSchema);
1213
 
 
1214
 
    /*! Stores extended schema information for table \a tableSchema,
1215
 
     (see ExtendedTableSchemaInformation in Kexi Wiki).
1216
 
     The action is performed within the current transaction,
1217
 
     so it's up to you to commit.
1218
 
     Used, e.g. by createTable(), within its transaction.
1219
 
     \return true on success */
1220
 
    bool storeExtendedTableSchemaData(TableSchema& tableSchema);
1221
 
 
1222
 
    /*! @internal
1223
 
     Stores main field's schema information for field \a field.
1224
 
     Used in table altering code when information in kexi__fields has to be updated.
1225
 
     \return true on success and false on failure. */
1226
 
    bool storeMainFieldSchema(Field *field);
1227
 
 
1228
 
    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1229
 
 
1230
 
    /*! This is a part of alter table interface implementing lower-level operations
1231
 
     used to perform table schema altering. Used by AlterTableHandler.
1232
 
 
1233
 
     Changes value of field property.
1234
 
     \return true on success, false on failure, cancelled if the action has been cancelled.
1235
 
 
1236
 
     Note for driver developers: implement this if the driver has to supprot the altering. */
1237
 
    virtual tristate drv_changeFieldProperty(TableSchema &table, Field& field,
1238
 
            const QString& propertyName, const QVariant& value) {
1239
 
        Q_UNUSED(table); Q_UNUSED(field); Q_UNUSED(propertyName); Q_UNUSED(value);
1240
 
        return cancelled;
1241
 
    }
1242
 
 
1243
 
    //! Used by Cursor class
1244
 
    void addCursor(KexiDB::Cursor& cursor);
1245
 
 
1246
 
    //! Used by Cursor class
1247
 
    void takeCursor(KexiDB::Cursor& cursor);
1248
 
 
1249
 
private:
1250
 
    ConnectionPrivate* d; //!< @internal d-pointer class.
1251
 
    Driver* const m_driver; //!< The driver this \a Connection instance uses.
1252
 
    bool m_destructor_started : 1; //!< helper: true if destructor is started.
1253
 
    bool m_insideCloseDatabase : 1; //!< helper: true while closeDatabase() is executed
1254
 
 
1255
 
    friend class KexiDB::Driver;
1256
 
    friend class KexiDB::Cursor;
1257
 
    friend class KexiDB::TableSchema; //!< for removeMe()
1258
 
    friend class KexiDB::DatabaseProperties; //!< for setError()
1259
 
    friend class ConnectionPrivate;
1260
 
    friend class KexiDB::AlterTableHandler;
1261
 
};
1262
 
 
1263
 
/*! \return "SELECT ..." statement's string needed for executing query
1264
 
    defined by \a querySchema, \a params and \a options. 
1265
 
    \a driver can be provided to generate driver-dependent statement. 
1266
 
    If \a driver is 0, KexiSQL statement is generated. */
1267
 
KEXI_DB_EXPORT QString selectStatement(const KexiDB::Driver *driver,
1268
 
                                       KexiDB::QuerySchema& querySchema,
1269
 
                                       const QList<QVariant>& params,
1270
 
                                       const KexiDB::Connection::SelectStatementOptions& options = KexiDB::Connection::SelectStatementOptions());
1271
 
 
1272
 
/*! \overload QString selectStatement(const KexiDB::Driver *driver, KexiDB::QuerySchema& querySchema, const QList<QVariant>& params, const KexiDB::Connection::SelectStatementOptions& options); */
1273
 
KEXI_DB_EXPORT inline QString selectStatement(const KexiDB::Driver *driver,
1274
 
                                              QuerySchema& querySchema,
1275
 
                                              const KexiDB::Connection::SelectStatementOptions& options = KexiDB::Connection::SelectStatementOptions())
1276
 
{
1277
 
    return KexiDB::selectStatement(driver, querySchema, QList<QVariant>(), options);
1278
 
}
1279
 
 
1280
 
} //namespace KexiDB
1281
 
 
1282
 
#endif