KDb

KDbConnection.h
1/* This file is part of the KDE project
2 Copyright (C) 2003-2018 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 KDB_CONNECTION_H
21#define KDB_CONNECTION_H
22
23#include "KDbCursor.h"
24#include "KDbDriver.h"
25#include "KDbPreparedStatement.h"
26#include "KDbTableSchema.h"
27#include "KDbTransaction.h"
28#include "KDbTristate.h"
29
32class KDbConnectionPrivate;
34class KDbDriver;
35class KDbProperties;
36class KDbRecordData;
39class KDbSqlResult;
41class KDbTableSchemaChangeListenerPrivate;
43class KDbVersionInfo;
44
45/*! @short Provides database connection, allowing queries and data modification.
46
47 This class represents a database connection established within a data source.
48 It supports data queries and modification by creating client-side database cursors.
49 Database transactions are supported.
50*/
51class KDB_EXPORT KDbConnection : public KDbResultable
52{
53 Q_DECLARE_TR_FUNCTIONS(KDbConnection)
54public:
55
56 /*! Opened connection is automatically disconnected and removed
57 from driver's connections list.
58 Note for driver developers: you should call destroy()
59 from you KDbConnection's subclass destructor. */
60 ~KDbConnection() override;
61
62 /*! @return parameters that were used to create this connection. */
63 KDbConnectionData data() const;
64
65 /*! @return the driver used for this connection. */
66 KDbDriver* driver() const;
67
68 /*!
69 @brief Connects to driver with given parameters.
70 @return true if successful.
71
72 Note: many database drivers may require connData.databaseName() to be specified
73 because explicit database name is needed to perform connection (e.g. SQLite, PostgreSQL).
74 MySQL does not require database name; KDbConnection::useDatabase() can be called later.
75 */
76 bool connect();
77
78 /*! @return true, if connection is properly established. */
79 bool isConnected() const;
80
81 /*! @return true, both if connection is properly established
82 and any database within this connection is properly used
83 with useDatabase(). */
84 bool isDatabaseUsed() const;
85
86 /*! @return generic options for a single connection.
87 The options are accessible using key/value pairs. This enables extensibility
88 depending on driver's type and version. */
89 KDbConnectionOptions *options();
90
91 /*! Reimplemented, also clears sql string.
92 @sa recentSqlString() */
93 void clearResult();
94
95 /*! @brief Disconnects from driver with given parameters.
96
97 The database (if used) is closed, and any active transactions
98 (if supported) are rolled back, so commit these before disconnecting,
99 if you'd like to save your changes. */
100 bool disconnect();
101
102 /*! @return list of database names for opened connection.
103 If @a also_system_db is true, the system database names are also returned. */
104 QStringList databaseNames(bool also_system_db = false);
105
106 /*! @return true if database @a dbName exists.
107 If @a ignoreErrors is true, error flag of connection
108 won't be modified for any errors (it will quietly return),
109 else (ignoreErrors == false) we can check why the database does
110 not exist using error(), errorNum() and/or errorMsg(). */
111 bool databaseExists(const QString &dbName, bool ignoreErrors = true);
112
113 /*! @brief Creates new database with name @a dbName, using this connection.
114
115 If database with @a dbName already exists, or other error occurred,
116 false is returned.
117 For file-based drivers, @a dbName should be equal to the database
118 filename (the same as specified for KDbConnectionData).
119
120 See docs/kdb_issues.txt document, chapter "Table schema, query schema, etc. storage"
121 for database schema documentation (detailed description of kexi__* 'system' tables).
122
123 @see useDatabase() */
124 bool createDatabase(const QString &dbName);
125
126 /*!
127 @brief Opens an existing database specified by @a dbName.
128
129 If @a kexiCompatible is true (the default) initial checks will be performed
130 to recognize database Kexi-specific format. Set @a kexiCompatible to false
131 if you're using native database (one that have no Kexi System tables).
132 For file-based drivers, @a dbName can be skipped, so the same as specified for
133 KDbConnectionData is used.
134 @return true on success, false on failure.
135 If user has cancelled this action and @a cancelled is not 0, *cancelled is set to true. */
136 bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr,
137 KDbMessageHandler* msgHandler = nullptr);
138
139 /*!
140 @brief Closes currently used database for this connection.
141
142 Any active transactions (if supported) are rolled back,
143 so commit these before closing, if you'd like to save your changes. */
144 bool closeDatabase();
145
146 /*! @brief Get the name of the current database
147
148 @return name of currently used database for this connection or empty string
149 if there is no used database */
150 QString currentDatabase() const;
151
152 /*! @brief Drops database with name @a dbName.
153
154 if dbName is not specified, currently used database name is used
155 (it is closed before dropping).
156 */
157 bool dropDatabase(const QString &dbName = QString());
158
159 /*! @return names of all the @a objectType (see @a ObjectType in KDbGlobal.h)
160 schemas stored in currently used database. KDb::AnyObjectType can be passed
161 as @a objectType to get names of objects of any type.
162 The list ordered is based on object identifiers.
163 Only names that are identifiers (checked using KDb::isIdentifier()) are returned.
164 If @a ok is not 0 then variable pointed by it will be set to the result.
165 On error, the function returns empty list.
166 @see kdbSystemTableNames() tableNames(int,bool*) */
167 QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr);
168
169 /*! @return names of all table schemas stored in currently
170 used database. If @a alsoSystemTables is true,
171 internal KDb system table names (kexi__*) are also returned.
172 The list ordered is based on object identifiers.
173 Only names that are identifiers (checked using KDb::isIdentifier()) are returned.
174 If @a ok is not 0 then variable pointed by it will be set to the result.
175 On error, the function returns empty list.
176 @see kdbSystemTableNames() objectNames(int,bool*) */
177 QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr);
178
179 /*! @return true if table with name @a tableName exists in the database.
180 @return @c false if it does not exist or @c cancelled if error occurred.
181 The lookup is case insensitive.
182 This method can be much faster than tableNames(). */
183 tristate containsTable(const QString &tableName);
184
185 /*! @return list of internal KDb system table names
186 (kexi__*). This does not mean that these tables can be found
187 in currently opened database. Just static list of table
188 names is returned.
189
190 The list contents may depend on KDb library version;
191 opened database can contain fewer 'system' tables than in current
192 KDb implementation, if the current one is newer than the one used
193 to build the database.
194 @todo this will depend on KDb lib version */
195 static QStringList kdbSystemTableNames();
196
197 /*! @return server version information for this connection.
198 If database is not connected (i.e. isConnected() is false) null KDbServerVersionInfo is returned. */
199 KDbServerVersionInfo serverVersion() const;
200
201 /*! @return version information for this connection.
202 If database is not used (i.e. isDatabaseUsed() is false) null KDbVersionInfo is returned.
203 It can be compared to drivers' and KDb library version to maintain
204 backward/upward compatiblility. */
205 KDbVersionInfo databaseVersion() const;
206
207 /*! @return KDbProperties object allowing to read and write global database properties
208 for this connection. */
209 KDbProperties databaseProperties() const;
210
211 /*! @return ids of all table schema names stored in currently
212 used database. These ids can be later used as argument for tableSchema().
213 This is a shortcut for objectIds(KDb::TableObjectType).
214 Internal KDb system tables (kexi__*) are not available here
215 because these have no identifiers assigned (more formally: id=-1).
216 If @a ok is not 0 then variable pointed by it will be set to the result.
217
218 @note The fact that given id is on the returned list does not mean
219 that tableSchema( id ) returns anything. The table definition can be broken,
220 so you have to double check this.
221
222 Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
223 are returned.
224 @see queryIds()
225 */
226 QList<int> tableIds(bool* ok = nullptr);
227
228 /*! @return ids of all database query schemas stored in currently
229 used database. These ids can be later used as argument for querySchema().
230 This is a shortcut for objectIds(KDb::QueryObjectType).
231 If @a ok is not 0 then variable pointed by it will be set to the result.
232
233 @note The fact that given id is on the returned list does not mean
234 that querySchema( id ) returns anything. The query definition can be broken,
235 so you have to double check this.
236
237 Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
238 are returned.
239 @see tableIds()
240 */
241 QList<int> queryIds(bool* ok = nullptr);
242
243 /*! @return names of all schemas of object with @a objectType type
244 that are stored in currently used database.
245 If @a ok is not 0 then variable pointed by it will be set to the result.
246
247 @note The fact that given id is on the returned list does not mean
248 that the definition of the object is valid,
249 so you have to double check this.
250
251 Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
252 are returned.
253 @see tableIds() queryIds() */
254 QList<int> objectIds(int objectType, bool* ok = nullptr);
255
256 /**
257 * @brief Starts a new database transaction
258 *
259 * @return KDbTransaction object. If transaction has been started successfully returned object
260 * points to it, otherwise null transaction is returned.
261 *
262 * For drivers that allow single transaction per connection
263 * (KDbDriver::features() && SingleTransactions) this method can be called once and that
264 * transaction will be default one (setDefaultTransaction() will be called).
265 * For drivers that allow multiple transactions per connection no default transaction is
266 * set automatically in beginTransaction(). setDefaultTransaction() can be called by hand.
267 *
268 * @see setDefaultTransaction(), defaultTransaction().
269 */
270 KDbTransaction beginTransaction();
271
272 /**
273 * @brief Commits specified transaction for this connection
274 *
275 * If @a transaction is not active and default transaction (obtained from defaultTransaction())
276 * exists, the default one will be committed. If neither the default one is not present returns
277 * @c true if IgnoreInactive is set in @a options or @c false if IgnoreInactive is not set in
278 * @a options.
279 *
280 * @return @c false on any error.
281 *
282 * On successful commit, @a transaction object will point to a null transaction.
283 * After commiting a default transaction, there is no default transaction anymore.
284 */
285 bool commitTransaction(KDbTransaction transaction = KDbTransaction(),
287
288 /**
289 * @brief Rolls back specified transaction for this connection
290 *
291 * If @a transaction is not active and default transaction (obtained from defaultTransaction())
292 * exists, the default one will be rolled back. If neither default one is present @c true is
293 * returned if IgnoreInactive is set for @a options or @c false if IgnoreInactive is not set in
294 * @a options.
295 *
296 * @return @c false on any error.
297 *
298 * On successful rollback, @a transaction object will point to a null transaction.
299 * After rollong back a default transaction, there is no default transaction anymore.
300 */
301 bool rollbackTransaction(KDbTransaction trans = KDbTransaction(),
303
304 /**
305 * @brief Returns handle of default transaction for this connection
306 *
307 * Null transaction is returned if there is no such a transaction declared.
308 * If transactions are supported any operation on database (e.g. inserts) that are started
309 * without specifying a transaction context, are be performed in the context of this transaction.
310 * Returned null transaction doesn't mean that there are no transactions started at all.
311 * Default transaction can be defined automatically for certain drivers, see beginTransaction().
312 *
313 * @see KDbDriver::transactionsSupported()
314 */
315 KDbTransaction defaultTransaction() const;
316
317 /**
318 * @brief Sets default transaction
319 *
320 * Default transaction is used as a context for data modifications for this connection when no
321 * specific transaction is provided.
322 */
323 void setDefaultTransaction(const KDbTransaction& trans);
324
325 /**
326 * @brief Returns set of handles of currently active transactions
327 *
328 * @note In multithreading environment some of these transactions can be already inactive after
329 * calling this method. Use KDbTransaction::isActive() to check that. Inactive transaction
330 * handle is useless and can be safely ignored.
331 */
332 QList<KDbTransaction> transactions();
333
334 /*! @return true if "auto commit" option is on.
335
336 When auto commit is on (the default on for any new KDbConnection object), every SQL statement
337 that manipulates data in the database implicitly starts a new transaction. This transaction is
338 automatically committed after successful statement execution or rolled back on error.
339
340 For drivers that do not support transactions (see KDbDriver::features())
341 this method shouldn't be called because it does nothing ans always returns false.
342
343 No internal KDb object should changes this option, although auto commit's
344 behavior depends on database engine's specifics. Engines that support only single
345 transaction per connection (see KDbDriver::SingleTransactions),
346 use this single connection for autocommiting, so if there is already transaction
347 started by the KDb user program (with beginTransaction()), this transaction
348 is committed before any statement that manipulates data. In this situation
349 default transaction is also affected (see defaultTransaction()).
350
351 Only for drivers that support nested transactions (KDbDriver::NestedTransactions),
352 autocommiting works independently from previously started transaction,
353
354 For other drivers set this option off if you need use transaction
355 for grouping more statements together.
356
357 NOTE: nested transactions are not yet implemented in KDb API.
358 */
359 bool autoCommit() const;
360
361 /*! Changes auto commit option. This does not affect currently started transactions.
362 This option can be changed even when connection is not established.
363 @see autoCommit() */
364 bool setAutoCommit(bool on);
365
366 /*! Connection-specific string escaping. Default implementation uses driver's escaping.
367 Use KDbEscapedString::isValid() to check if escaping has been performed successfully.
368 Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true,
369 not just isEmpty().
370 */
371 virtual KDbEscapedString escapeString(const QString& str) const;
372
373 /*! Prepares SELECT query described by a raw statement @a sql.
374 @return opened cursor created for results of this query
375 or @c nullptr if there was any error. Ownership of the returned object is passed
376 to the caller.
377 KDbCursor can have optionally applied @a options (one of more selected from KDbCursor::Options).
378 Preparation means that returned cursor is created but not opened.
379 Open this when you would like to do it with KDbCursor::open().
380
381 Note for driver developers: you should initialize cursor engine-specific
382 resources and return KDbCursor subclass' object
383 (passing @a sql and @a options to its constructor).
384 */
386 KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0;
387
388 /*! @overload
389 Prepares query described by @a query schema. @a params are values of parameters that
390 will be inserted into places marked with [] before execution of the query.
391
392 Note for driver developers: you should initialize cursor engine-specific
393 resources and return KDbCursor subclass' object
394 (passing @a query and @a options to it's constructor).
395 Kexi SQL and driver-specific escaping is performed on table names.
396 */
397 Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, const QList<QVariant> &params,
398 KDbCursor::Options options = KDbCursor::Option::None);
399
400 /*! @overload
401 Prepares query described by @a query schema without parameters.
402 */
404 KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0;
405
406 /*! @overload
407 Statement is build from data provided by @a table schema, it is like "select * from
408 table_name".*/
409 Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbTableSchema *table,
410 KDbCursor::Options options = KDbCursor::Option::None);
411
412 /*! Executes SELECT query described by a raw SQL statement @a sql.
413 @return opened cursor created for results of this query
414 or 0 if there was any error on the cursor creation or opening.
415 Ownership of the returned object is passed to the caller.
416 KDbCursor can have optionally applied @a options.
417 Identifiers in @a sql that are the same as keywords
418 in KDbSQL dialect or the backend's SQL have to be escaped.
419 */
420 Q_REQUIRED_RESULT KDbCursor *executeQuery(const KDbEscapedString &sql,
421 KDbCursor::Options options = KDbCursor::Option::None);
422
423 /*! @overload executeQuery(const KDbEscapedString&, int)
424 @a params are values of parameters that
425 will be inserted into places marked with [] before execution of the query.
426
427 Statement is build from data provided by @a query schema.
428 Kexi SQL and driver-specific escaping is performed on table names. */
429 Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query, const QList<QVariant> &params,
430 KDbCursor::Options options = KDbCursor::Option::None);
431
432 /*! @overload */
433 Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query,
434 KDbCursor::Options options = KDbCursor::Option::None);
435
436 /*! @overload
437 Executes query described by @a query schema without parameters.
438 Statement is build from data provided by @a table schema,
439 it is like "select * from table_name".*/
440 Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbTableSchema *table,
441 KDbCursor::Options options = KDbCursor::Option::None);
442
443 /*! Deletes cursor @a cursor previously created by functions like executeQuery()
444 for this connection.
445 There is an attempt to close the cursor with KDbCursor::close() if it was opened.
446 Anyway, at last cursor is deleted.
447 @return true if cursor is properly closed before deletion. */
448 bool deleteCursor(KDbCursor *cursor);
449
450 /*! @return schema of a table pointed by @a tableId, retrieved from currently
451 used database. The schema is cached inside connection,
452 so retrieval is performed only once, on demand. */
453 KDbTableSchema* tableSchema(int tableId);
454
455 /*! @return schema of a table pointed by @a tableName, retrieved from currently
456 used database. KDb system table schema can be also retrieved.
457 @see tableSchema( int tableId ) */
458 KDbTableSchema* tableSchema(const QString& tableName);
459
460 /*! @return schema of a query pointed by @a queryId, retrieved from currently
461 used database. The schema is cached inside connection,
462 so retrieval is performed only once, on demand. */
463 KDbQuerySchema* querySchema(int queryId);
464
465 /*! @return schema of a query pointed by @a queryName, retrieved from currently
466 used database. @see querySchema( int queryId ) */
467 KDbQuerySchema* querySchema(const QString& queryName);
468
469 /*! Sets @a queryName query obsolete by moving it out of the query sets, so it will not be
470 accessible by querySchema( const QString& queryName ). The existing query object is not
471 destroyed, to avoid problems when it's referenced. In this case,
472 a new query schema will be retrieved directly from the backend.
473
474 For now it's used in KexiQueryDesignerGuiEditor::storeLayout().
475 This solves the problem when user has changed a query schema but already form still uses
476 previously instantiated query schema.
477 @return true if there is such query. Otherwise the method does nothing. */
478 bool setQuerySchemaObsolete(const QString& queryName);
479
480 //! Options for querying records
481 //! @since 3.1
482 enum class QueryRecordOption {
483 AddLimitTo1 = 1, //!< Adds a "LIMIT 1" clause to the query for optimization purposes
484 //!< (it should not include one already)
485 Default = AddLimitTo1
486 };
487 Q_DECLARE_FLAGS(QueryRecordOptions, QueryRecordOption)
488
489 /*! Executes query for a raw statement @a sql and stores first record's data inside @a data.
490 This is a convenient method when we need only first record from query result,
491 or when we know that query result has only one record.
492 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
493 Caller should make sure it is not there in the @a sql already.
494 @return @c true if query was successfully executed and first record has been found,
495 @c false on data retrieving failure, and @c cancelled if there's no single record available. */
496 tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data,
497 QueryRecordOptions options = QueryRecordOption::Default);
498
499 /*! @overload
500 Uses a KDbQuerySchema object. */
501 tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data,
502 QueryRecordOptions options = QueryRecordOption::Default);
503
504 /*! @overload
505 Accepts @a params as parameters that will be inserted into places marked with "[]" before
506 query execution. */
507 tristate querySingleRecord(KDbQuerySchema *query, KDbRecordData *data,
508 const QList<QVariant> &params,
509 QueryRecordOptions options = QueryRecordOption::Default);
510
511 /*! Executes query for a raw statement @a sql and stores first record's field's
512 (number @a column) string value inside @a value.
513 For efficiency it's recommended that a query defined by @a sql
514 should have just one field (SELECT one_field FROM ....).
515 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
516 Caller should make sure it is not there in the @a sql already.
517 @return @c true if query was successfully executed and first record has been found,
518 @c false on data retrieving failure, and @c cancelled if there's no single record available.
519 @see queryStringList() */
520 tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0,
521 QueryRecordOptions options = QueryRecordOption::Default);
522
523 /*! @overload
524 Uses a KDbQuerySchema object. */
525 tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0,
526 QueryRecordOptions options = QueryRecordOption::Default);
527
528 /*! @overload
529 Accepts @a params as parameters that will be inserted into places marked with [] before
530 query execution. */
531 tristate querySingleString(KDbQuerySchema* query, QString* value,
532 const QList<QVariant>& params, int column = 0,
533 QueryRecordOptions options = QueryRecordOption::Default);
534
535 /*! Convenience function: executes query for a raw SQL statement @a sql and stores first
536 record's field's (number @a column) value inside @a number. @see querySingleString().
537 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
538 Caller should make sure it is not there in the @a sql already.
539 @return true if query was successfully executed and first record has been found,
540 false on data retrieving failure, and cancelled if there's no single record available. */
541 tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0,
542 QueryRecordOptions options = QueryRecordOption::Default);
543
544 /*! @overload
545 Uses a KDbQuerySchema object. */
546 tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0,
547 QueryRecordOptions options = QueryRecordOption::Default);
548
549 /*! @overload
550 Accepts @a params as parameters that will be inserted into places marked with "[]" before
551 query execution. */
552 tristate querySingleNumber(KDbQuerySchema* query, int* number,
553 const QList<QVariant>& params, int column = 0,
554 QueryRecordOptions options = QueryRecordOption::Default);
555
556 /*! Executes query for a raw SQL statement @a sql and stores Nth field's string value
557 of every record inside @a list, where N is equal to @a column. The list is initially cleared.
558 For efficiency it's recommended that a query defined by @a sql
559 should have just one field (SELECT one_field FROM ....).
560 @return true if all values were fetched successfuly,
561 false on data retrieving failure. Returning empty list can be still a valid result.
562 On errors, the list is not cleared, it may contain a few retrieved values. */
563 bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0);
564
565 /*! @overload
566 Uses a QuerySchema object. */
567 bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0);
568
569 /*! @overload
570 Accepts @a params as parameters that will be inserted into places marked with "[]" before
571 query execution. */
572 bool queryStringList(KDbQuerySchema* query, QStringList* list,
573 const QList<QVariant>& params, int column = 0);
574
575 /*! @return @c true if there is at least one record has been returned by executing query
576 for a raw SQL statement @a sql or @c false if no such record exists.
577 If @a options includes AddLimitTo1 value, the query is optimized into "SELECT 1 FROM (sql) LIMIT 1"
578 (this is the default). Caller should make sure "SELECT 1" and "LIMIT 1" is not there in the
579 @a sql already.
580 This method does not fetch any records. On error returns @c cancelled. */
581 tristate resultExists(const KDbEscapedString &sql,
582 QueryRecordOptions options = QueryRecordOption::Default);
583
584 /*! @return true if there is at least one record in @a table. */
585 tristate isEmpty(KDbTableSchema* table);
586
587 /**
588 * @brief Return recently used SQL string
589 *
590 * If there was a successful query execution it is equal to result().sql(),
591 * otherwise it is equal to result().errorSql().
592 */
593 virtual KDbEscapedString recentSqlString() const;
594
595 //PROTOTYPE:
596#define A , const QVariant&
597#define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema* tableSchema args)
598#define H_INS_REC_ALL \
599 H_INS_REC(A); \
600 H_INS_REC(A A); \
601 H_INS_REC(A A A); \
602 H_INS_REC(A A A A); \
603 H_INS_REC(A A A A A); \
604 H_INS_REC(A A A A A A); \
605 H_INS_REC(A A A A A A A); \
606 H_INS_REC(A A A A A A A A)
607 H_INS_REC_ALL;
608
609#undef H_INS_REC
610#define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList* fields args)
611
612 H_INS_REC_ALL;
613#undef H_INS_REC_ALL
614#undef H_INS_REC
615#undef A
616
617 QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema *tableSchema,
618 const QList<QVariant> &values);
619
620 QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList *fields, const QList<QVariant> &values);
621
622 //! Options for creating table
623 //! @since 3.1
624 enum class CreateTableOption {
625 Default = 0,
626 DropDestination = 1 //!< Drop destination table if exists
627 };
628 Q_DECLARE_FLAGS(CreateTableOptions, CreateTableOption)
629
630 /**
631 * @brief Creates a new table
632 *
633 * Creates a new table defined by @a tableSchema. @c true is returned on success. In this case
634 * @a tableSchema object is added to KDbConnection's structures and becomes owned the
635 * KDbConnection object, so should not be destroyed by hand.
636 *
637 * If @a options include the DropDestination value and table schema with the same name as @a
638 * tableSchema exists, it is dropped and the original identifier of the dropped schem is
639 * assigned to the @a tableSchema object.
640 *
641 * If @a options do not include the DropDestination value and table schema with the same name
642 * as @a tableSchema exists, @c false is returned.
643 *
644 * Table and column definitions are added to "Kexi system" tables.
645 *
646 * Prior to dropping the method checks if the table for the schema is in use, and if the new
647 * schema defines at least one column.
648 *
649 * Note that on error:
650 * - @a tableSchema is not inserted into KDbConnection's structures, so caller is still owner
651 * of the object,
652 * - existing table schema object is not destroyed (e.g. it is still available for
653 * KDbConnection::tableSchema(const QString&), even if the table was physically dropped.
654 *
655 * @return true on success.
656 */
657 bool createTable(KDbTableSchema *tableSchema,
658 CreateTableOptions options = CreateTableOption::Default);
659
660 /*! Creates a copy of table schema defined by @a tableSchema with data.
661 Name, caption and description will be copied from @a newData.
662 @return a table schema object. It is inserted into the KDbConnection structures
663 and is owned by the KDbConnection object. The created table schema object should not
664 be destroyed by hand afterwards.
665 0 is returned on failure. Table with destination name must not exist.
666 @see createTable() */
667 KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData);
668
669 /*! It is a convenience function, does exactly the same as
670 KDbTableSchema *copyTable(const KDbTableSchema&, const KDbObject&). */
671 KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData);
672
673 /*! Drops a table defined by @a tableSchema (both table object as well as physically).
674 If true is returned, schema information @a tableSchema is destoyed
675 (because it's owned), so don't keep this anymore!
676 No error is raised if the table does not exist physically
677 - its schema is removed even in this case.
678
679 Removes the table and column definitions in kexi__* "system schema" tables.
680 First checks that the table is not a system table.
681
682 @todo Check that a database is currently in use? (c.f. createTable)
683 @todo Update any structure (e.g. query) that depends on this table */
684 tristate dropTable(KDbTableSchema* tableSchema);
685
686 /*! @overload
687 * It is a convenience function.
688 */
689 tristate dropTable(const QString& tableName);
690
691 /*! Alters @a tableSchema using @a newTableSchema in memory and on the db backend.
692 @return true on success, cancelled if altering was cancelled. */
693//! @todo (js): implement real altering
694//! @todo (js): update any structure (e.g. query) that depend on this table!
695 tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema);
696
697 //! Options for altering table name
698 //! @since 3.1
700 Default = 0,
701 DropDestination = 1 //!< Drop destination table if exists
702 };
703 Q_DECLARE_FLAGS(AlterTableNameOptions, AlterTableNameOption)
704
705 /**
706 * @brief Alters name of table
707 *
708 * Alters name of table described by @a tableSchema to @a newName.
709 * If @a options include the DropDestination value and table having name @a newName already
710 * exists, it is physically dropped, removed from connection's list of tables and replaced
711 * by @a tableSchema. In this case identifier of @a tableSchema is set to the dropped table's
712 * identifier. This can be useful if @a tableSchema was created with a temporary name and
713 * identifier. It is for example used in KDbAlterTableHandler.
714 *
715 * If @a options do not include the DropDestination value (the default) and table having name
716 * @a newName already exists, @c false is returned and @c ERR_OBJECT_EXISTS error is set in
717 * the connection object.
718 *
719 * Table name in the schema of @a tableSchema is updated on successful altering.
720 * @return true on success.
721 */
722 bool alterTableName(KDbTableSchema* tableSchema, const QString& newName,
723 AlterTableNameOptions options = AlterTableNameOption::Default);
724
725 /*! Drops a query defined by @a querySchema.
726 If true is returned, schema information @a querySchema is destoyed
727 (because it's owned), so don't keep this anymore!
728 */
729 bool dropQuery(KDbQuerySchema* querySchema);
730
731 /*! It is a convenience function, does exactly the same as
732 bool dropQuery( KDbQuerySchema* querySchema ) */
733 bool dropQuery(const QString& queryName);
734
735 /*! Removes information about object with @a objId
736 from internal "kexi__object" and "kexi__objectdata" tables.
737 @return true on success. */
738 bool removeObject(int objId);
739
740 /*! @return first field from @a fieldlist that has system name,
741 @c nullptr if there are no such field.
742 For checking, KDbDriver::isSystemFieldName() is used, so this check can
743 be driver-dependent. */
744 KDbField* findSystemFieldName(const KDbFieldList& fieldlist);
745
746 /*! @return name of any (e.g. first found) database for this connection.
747 This method does not close or open this connection. The method can be used
748 (it is also internally used, e.g. for database dropping) when we need
749 a database name before we can connect and execute any SQL statement
750 (e.g. DROP DATABASE).
751
752 The method can return nul lstring, but in this situation no automatic (implicit)
753 connections could be made, what is useful by e.g. dropDatabase().
754
755 Note for driver developers: return here a name of database which you are sure
756 is existing.
757 Default implementation returns:
758 - value that previously had been set using setAvailableDatabaseName() for
759 this connection, if it is not empty
760 - else (2nd priority): value of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME
761 if it is not empty.
762
763 See description of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME member.
764 You may want to reimplement this method only when you need to depend on
765 this connection specifics
766 (e.g. you need to check something remotely).
767 */
768 virtual QString anyAvailableDatabaseName();
769
770 /*! Sets @a dbName as name of a database that can be accessible.
771 This is option that e.g. application that make use of KDb library can set
772 to tune connection's behavior when it needs to temporary connect to any database
773 in the server to do some work.
774 You can pass empty dbName - then anyAvailableDatabaseName() will try return
775 KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value
776 instead of the one previously set with setAvailableDatabaseName().
777
778 @see anyAvailableDatabaseName()
779 */
780 void setAvailableDatabaseName(const QString& dbName);
781
782 /*! Because some engines need to have opened any database before
783 executing administrative SQL statements like "create database" or "drop database",
784 this method is used to use appropriate, existing database for this connection.
785 For file-based db drivers this always return true and does not set @a name
786 to any value. For other db drivers: this sets @a name to db name computed
787 using anyAvailableDatabaseName(), and if the name computed is empty, false
788 is returned; if it is not empty, useDatabase() is called.
789 False is returned also when useDatabase() fails.
790 You can call this method from your application's level if you really want to perform
791 tasks that require any used database. In such a case don't forget
792 to closeDatabase() if returned @a name is not empty.
793
794 Note: This method has nothing to do with creating or using temporary databases
795 in such meaning that these database are not persistent
796 */
797 bool useTemporaryDatabaseIfNeeded(QString* name);
798
799 /**
800 * Prepares execution of a new native (raw, backend-specific) SQL query.
801 *
802 * The query is described by a raw statement @a sql which should be is valid and properly
803 * escaped. Access to results can be obtained using
804 * the returned KDbSqlResult object. The object is guarded with a shared pointer to facilitate
805 * transfer of ownership and memory management. A null pointer is returned if preparation of
806 * the query fails. Use KDbConnection::result() immediately after calling prepareSql() to
807 * obtain detailed result information about the preparation.
808 *
809 * The returned object should be deleted before the database connection is closed.
810 * Connection object does not deletes the KDbSqlResult objects. It is also possible and
811 * recommended that caller deletes the KDbSqlResult object as soon as the result is not needed.
812 *
813 * The returned object can be ignored if the query is not supposed to return records (e.g.
814 * manipulates data through INSERT, UPDATE, DELETE, ...) or the caller is not interested in the
815 * records. Thanks to the use of the shared pointer the object will be immediately deleted and
816 * execution will be finalized prior to that. However to execute queries that return no
817 * results, executeSql() is a better choice because of performance and easier reporting to
818 * results.
819 *
820 * @note Only use this method if a non-portable raw query is required.
821 * In other cases use prepareQuery() or executeQuery() and the KDbCursor object.
822 */
823 Q_REQUIRED_RESULT QSharedPointer<KDbSqlResult> prepareSql(const KDbEscapedString& sql);
824
825 /**
826 * Executes a new native (raw, backend-specific) SQL query
827 *
828 * The query is described by a raw statement @a sql which should be is valid and properly
829 * escaped. This method is a convenience version of prepareSql() that immediately starts and
830 * finalizes execution of a raw query in one step and provides a result. Use it for queries
831 * that do not return records, i.e. for queries that manipulate data (INSERT, UPDATE, DELETE,
832 * ...) or if the caller is not interested in the returned records.
833 *
834 * @note Only use this method if a non-portable raw query is required.
835 * In other cases use prepareQuery() or executeQuery() and the KDbCursor object.
836 */
837 bool executeSql(const KDbEscapedString& sql);
838
839 /*! Stores object (id, name, caption, description)
840 described by @a object on the backend. It is expected that entry on the
841 backend already exists, so it's updated. Changes to identifier attribute are not allowed.
842 @return true on success. */
843 bool storeObjectData(KDbObject* object);
844
845 /*! Stores new entry for object (id, name, caption, description)
846 described by @a object on the backend. If object.id() was less than 0,
847 new, unique object identifier is obtained and assigned to @a object (see KDbObject::id()).
848 @return true on success. */
849 bool storeNewObjectData(KDbObject* object);
850
851 /*! Finds object data for object of type @a type and identifier @a id.
852 Added for convenience.
853 If @a type is KDb::AnyObjectType, object type is ignored during the find.
854 @see setupObjectData(const KDbRecordData*, KDbObject*).
855 @return true on success, false on failure and cancelled when such object couldn't be found.
856 @since 3.1
857 */
858 tristate loadObjectData(int type, int id, KDbObject* object);
859
860 /*! Finds object data for object of type @a type and name @a name.
861 If the object is found, resulted schema is stored in @a object and true is returned,
862 otherwise false is returned. */
863 tristate loadObjectData(int type, const QString& name, KDbObject* object);
864
865 /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID
866 and puts it to @a dataString. The can be block indexed with optional @a dataID.
867 @return true on success, false on failure and cancelled when there is no such data block
868 @see storeDataBlock(). */
869 tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString());
870
871 /*! Stores (potentially large) data block @a dataString (e.g. xml form's representation),
872 referenced by objectID. Block will be stored in "kexi__objectdata" table and
873 an optional @a dataID identifier.
874 If there is already such record in the table, it's simply overwritten.
875 @return true on success
876 @see loadDataBlock() removeDataBlock() copyDataBlock(). */
877 bool storeDataBlock(int objectID, const QString &dataString,
878 const QString& dataID = QString());
879
880 /*! Copies (potentially large) data, e.g. form's XML representation,
881 referenced by @a sourceObjectID pointed by optional @a dataID.
882 @return true on success. Does not fail if blocks do not exist.
883 Prior to copying, existing data blocks are removed even if there are no new blocks to copy.
884 Copied data blocks will have @a destObjectID object identifier assigned.
885 Note that if @a dataID is not specified, all data blocks found for the @a sourceObjectID
886 will be copied.
887 @see loadDataBlock() storeDataBlock() removeDataBlock(). */
888 bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString());
889
890 /*! Removes (potentially large) string data (e.g. xml form's representation),
891 referenced by @a objectID, and pointed by optional @a dataID.
892 @return true on success. Does not fail if the block does not exist.
893 Note that if @a dataID is not specified, all data blocks for the @a objectID will be removed.
894 @see loadDataBlock() storeDataBlock() copyDataBlock(). */
895 bool removeDataBlock(int objectID, const QString& dataID = QString());
896
897 /*! Prepare an SQL statement and return a @a KDbPreparedStatement instance. */
899 KDbFieldList* fields, const QStringList& whereFieldNames = QStringList());
900
901 bool isInternalTableSchema(const QString& tableName);
902
903 /**
904 * @brief Returns number of records returned by given SQL statement
905 *
906 * @return number of records that can be retrieved after executing @a sql statement within
907 * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not
908 * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed.
909 * -1 is returned if any error occurred or if @a conn is @c nullptr.
910 *
911 * @since 3.1
912 */
913 //! @todo perhaps use quint64 here?
914 int recordCount(const KDbEscapedString& sql);
915
916 /**
917 * @brief Returns number of records that contains given table
918 *
919 * @return number of records that can be retrieved from @a tableSchema.
920 * To obtain the result the table must be created or retrieved using a KDbConnection object,
921 * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)"
922 * SQL aggregation is used at the backed.
923 * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr.
924 *
925 * @since 3.1
926 */
927 //! @todo perhaps use quint64 here?
928 //! @todo does not work with non-SQL data sources
929 int recordCount(const KDbTableSchema& tableSchema);
930
931 /**
932 * @overload
933 *
934 * Operates on a query schema. @a params are optional values of parameters that will be inserted
935 * into [] placeholders before execution of query that counts the records.
936 * To obtain the result the query must be created or retrieved using a KDbConnection object,
937 * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)"
938 * SQL aggregation is used at the backed.
939 * -1 is returned if error occurred or if querySchema->connection() is @c nullptr.
940 *
941 * @since 3.1
942 */
943 //! @todo perhaps use quint64 here?
944 int recordCount(KDbQuerySchema* querySchema,
945 const QList<QVariant>& params = QList<QVariant>());
946
947 /**
948 * @overload
949 *
950 * Operates on a table or query schema. @a params is a list of optional parameters that
951 * will be inserted into [] placeholders before execution of query that counts the records.
952 *
953 * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned.
954 *
955 * @since 3.1
956 */
957 //! @todo perhaps use quint64 here?
958 int recordCount(KDbTableOrQuerySchema* tableOrQuery,
959 const QList<QVariant>& params = QList<QVariant>());
960
961 //! Identifier escaping function in the associated KDbDriver.
962 /*! Calls the identifier escaping function in this connection to
963 escape table and column names. This should be used when explicitly
964 constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)).
965 It should not be used for other functions (e.g. don't do
966 useDatabase(escapeIdentifier(database))), because the identifier will
967 be escaped when the called function generates, for example, "USE " +
968 escapeIdentifier(database).
969
970 For efficiency, KDb "system" tables (prefixed with kexi__)
971 and columns therein are not escaped - we assume these are valid identifiers for all drivers.
972
973 Use KDbEscapedString::isValid() to check if escaping has been performed successfully.
974 Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true,
975 not just isEmpty().
976 */
977 virtual QString escapeIdentifier(const QString& id) const;
978
979protected:
980 /*! Used by KDbDriver */
981 KDbConnection(KDbDriver *driver, const KDbConnectionData& connData,
982 const KDbConnectionOptions &options);
983
984 /*! Method to be called form KDbConnection's subclass destructor.
985 @see ~KDbConnection() */
986 void destroy();
987
988 /*! For implementation: connects to database.
989 @return true on success. */
990 virtual bool drv_connect() = 0;
991
992 /*! For implementation: disconnects database
993 @return true on success. */
994 virtual bool drv_disconnect() = 0;
995
996 /*! For implementation: Sets @a version to real server's version.
997 Depending on backend type this method is called after
998 (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is true)
999 or before database is used
1000 (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is false),
1001 i.e. for PostgreSQL it is called after.
1002 In any case it is called after successful drv_connect().
1003 @return true on success. */
1004 virtual bool drv_getServerVersion(KDbServerVersionInfo* version) = 0;
1005
1006 /**
1007 * LOW LEVEL METHOD. Obtains a list containing names of all physical
1008 * tables of this connection and returns it.
1009 *
1010 * @a ok must not be @c nullptr.
1011 *
1012 * Default implementation covers functionality of SQL backends. It executes low-level SQL
1013 * defined by KDbDriverBehavior::GET_TABLE_NAMES_SQL string. On failure of execution or if
1014 * KDbDriverBehavior::GET_TABLE_NAMES_SQL is empty, @a ok is set to @c false. On success @a ok
1015 * is set to @c true. Returning empty list is not an error.
1016 *
1017 * If the database driver is not able to offer such a list, do not reimplement this method, it
1018 * will just always return false and users of KDb will need to take this into account.
1019 *
1020 * To reimplement the method, set @a ok to @c true only on successfull obtaining of table names,
1021 * and to @c false otherwise.
1022 *
1023 * This method is used by tableNames() to filter out tables names that have been found in
1024 * project's metadata but lack related physical tables.
1025 *
1026 * @since 3.2
1027 *
1028 * @see tableNames()
1029 */
1030 virtual QStringList drv_getTableNames(bool *ok);
1031
1032 /*! LOW LEVEL METHOD. For implementation: returns true if table
1033 with name @a tableName exists in the database.
1034 @return @c false if it does not exist or @c cancelled if error occurred.
1035 The lookup is case insensitive. */
1036 virtual tristate drv_containsTable(const QString &tableName) = 0;
1037
1038 /**
1039 * Creates table using @a tableSchema information.
1040 *
1041 * @return true on success.
1042 *
1043 * Default implementation builds a statement using createTableStatement() and calls
1044 * executeSql(). Note for driver developers: reimplement this only to perform creation in other
1045 * way.
1046 */
1047 virtual bool drv_createTable(const KDbTableSchema& tableSchema);
1048
1049 /*! Alters table's described @a tableSchema name to @a newName.
1050 This is the default implementation, using "ALTER TABLE <oldname> RENAME TO <newname>",
1051 what's supported by SQLite >= 3.2, PostgreSQL, MySQL.
1052 Backends lacking ALTER TABLE, for example SQLite, reimplement this with by an inefficient
1053 data copying to a new table. In any case, renaming is performed at the backend.
1054 It's good idea to keep the operation within a transaction.
1055 @return true on success. */
1056 virtual bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName);
1057
1058 /*! Copies table data from @a tableSchema to @a destinationTableSchema
1059 Default implementation executes "INSERT INTO .. SELECT * FROM .."
1060 @return true on success. */
1061 virtual bool drv_copyTableData(const KDbTableSchema &tableSchema,
1062 const KDbTableSchema &destinationTableSchema);
1063
1064 /*! Physically drops table named with @a name.
1065 Default impelmentation executes "DROP TABLE.." command,
1066 so you rarely want to change this. */
1067 virtual bool drv_dropTable(const QString& tableName);
1068
1069 /*! @internal drops table @a tableSchema physically, but destroys
1070 @a tableSchema object only if @a alsoRemoveSchema is true.
1071 Used (alsoRemoveSchema==false) on table altering:
1072 if recreating table can fail we're giving up and keeping
1073 the original table schema (even if it is no longer points to any real data). */
1074 tristate dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema);
1075
1076 /*! Setups data for object that owns @a object (e.g. table, query)
1077 opened on 'kexi__objects' table, pointing to a record
1078 corresponding to given object. */
1079 bool setupObjectData(const KDbRecordData& data, KDbObject* object);
1080
1081 /*! @return a new field table schema for a table retrieved from @a data.
1082 Ownership of the returned object is passed to the caller.
1083 Used internally by tableSchema(). */
1084 Q_REQUIRED_RESULT KDbField *setupField(const KDbRecordData &data);
1085
1086 /**
1087 * Prepares query for a raw SQL statement @a sql with possibility of returning records.
1088 *
1089 * It is useful mostly for SELECT queries. While INSERT queries do not return records, the
1090 * KDbSqlResult object offers KDbSqlResult::lastInsertRecordId(). The @sql should be is valid
1091 * and properly escaped. Only use this method if you really need. For low-level access to the
1092 * results (without cursors). The result may be not stored (not buffered) yet. Use
1093 * KDbSqlResult::fetchRecord() to fetch each record. @return Null pointer if there is no proper
1094 * result or error. Ownership of the returned object is passed to the caller.
1095 *
1096 * @see prepareSql
1097 */
1098 virtual KDbSqlResult* drv_prepareSql(const KDbEscapedString &sql) /*Q_REQUIRED_RESULT*/ = 0;
1099
1100 /**
1101 * Executes query for a raw SQL statement @a sql without returning resulting records.
1102 *
1103 * It is useful mostly for INSERT queries but it is possible to execute SELECT queries when
1104 * returned records can be ignored. The @sql should be is valid and properly escaped.
1105 *
1106 * @note Only use this method if you really need.
1107 * @see executeSql
1108 */
1109 virtual bool drv_executeSql(const KDbEscapedString& sql) = 0;
1110
1111 /*! For reimplementation: loads list of databases' names available for this connection
1112 and adds these names to @a list. If your server is not able to offer such a list,
1113 consider reimplementing drv_databaseExists() instead.
1114 The method should return true only if there was no error on getting database names
1115 list from the server.
1116 Default implementation puts empty list into @a list and returns true.
1117 @see databaseNames */
1118 virtual bool drv_getDatabasesList(QStringList* list);
1119
1120 /*! For optional reimplementation: asks server if database @a dbName exists.
1121 This method is used internally in databaseExists(). The default implementation
1122 calls databaseNames and checks if that list contains @a dbName. If you need to
1123 ask the server specifically if a database exists, eg. if you can't retrieve a list
1124 of all available database names, please reimplement this method and do all
1125 needed checks.
1126
1127 See databaseExists() description for details about ignoreErrors argument.
1128 You should use it properly in your implementation.
1129
1130 Note: This method should also work if there is already database used (with useDatabase());
1131 in this situation no changes should be made in current database selection. */
1132 virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true);
1133
1134 /*! For implementation: creates new database using connection */
1135 virtual bool drv_createDatabase(const QString &dbName = QString()) = 0;
1136
1137 /*! For implementation: opens existing database using connection
1138 @return true on success, false on failure; sets @a cancelled to true if this action
1139 has been cancelled. */
1140 virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr,
1141 KDbMessageHandler* msgHandler = nullptr) = 0;
1142
1143 /*! For implementation: closes previously opened database
1144 using connection. */
1145 virtual bool drv_closeDatabase() = 0;
1146
1147 /*! @return true if internal driver's structure is still in opened/connected
1148 state and database is used.
1149 Note for driver developers: Put here every test that you can do using your
1150 internal engine's database API,
1151 eg (a bit schematic): my_connection_struct->isConnected()==true.
1152 Do not check things like KDbConnection::isDatabaseUsed() here or other things
1153 that "KDb already knows" at its level.
1154 If you cannot test anything, just leave default implementation (that returns true).
1155
1156 Result of this method is used as an additional chance to check for isDatabaseUsed().
1157 Do not call this method from your driver's code, it should be used at KDb level only.
1158 */
1159 virtual bool drv_isDatabaseUsed() const {
1160 return true;
1161 }
1162
1163 /*! For implementation: drops database from the server
1164 using connection. After drop, database shouldn't be accessible
1165 anymore. */
1166 virtual bool drv_dropDatabase(const QString &dbName = QString()) = 0;
1167
1168 /*!
1169 Creates table named by @a tableName. Schema object must be on
1170 schema tables' list before calling this method (otherwise false if returned).
1171 Just uses drv_createTable( const KDbTableSchema& tableSchema ).
1172 Used internally, e.g. in createDatabase().
1173 @return true on success
1174 */
1175 virtual bool drv_createTable(const QString& tableName);
1176
1177 /*! Note for driver developers: begins new transaction
1178 and returns handle to it. Default implementation just
1179 executes "BEGIN" sql statement and returns just empty data (KDbTransactionData object).
1180 Ownership of the returned object is passed to the caller.
1181
1182 Drivers that do not support transactions (see KDbDriver::features())
1183 do never call this method.
1184 Reimplement this method if you need to do something more
1185 (e.g. if you driver will support multiple transactions per connection).
1186 Make subclass of KDbTransactionData (declared in KDbTransaction.h)
1187 and return object of this subclass.
1188 @c nullptr should be returned on error.
1189 Do not check anything in connection (isConnected(), etc.) - all is already done.
1190
1191 @todo Add support for nested transactions,
1192 e.g. KDbTransactionData* beginTransaction(KDbTransactionData *parent)
1193 */
1194 Q_REQUIRED_RESULT virtual KDbTransactionData *drv_beginTransaction();
1195
1196 /*! Note for driver developers: begins new transaction
1197 and returns handle to it. Default implementation just
1198 executes "COMMIT" sql statement and returns true on success.
1199
1200 @see drv_beginTransaction()
1201 */
1202 virtual bool drv_commitTransaction(KDbTransactionData* trans);
1203
1204 /*! Note for driver developers: begins new transaction
1205 and returns handle to it. Default implementation just
1206 executes "ROLLBACK" sql statement and returns true on success.
1207
1208 @see drv_beginTransaction()
1209 */
1210 virtual bool drv_rollbackTransaction(KDbTransactionData* trans);
1211
1212
1213 /*! Preprocessing (if any) required by drivers before execution of an
1214 Insert statement.
1215 Reimplement this method in your driver if there are any special processing steps to be
1216 executed before an Insert statement.
1217 @see drv_afterInsert()
1218 */
1219 virtual bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) {
1220 Q_UNUSED(tableName);
1221 Q_UNUSED(fields);
1222 return true;
1223 }
1224
1225 /*! Postprocessing (if any) required by drivers before execution of an
1226 Insert statement.
1227 Reimplement this method in your driver if there are any special processing steps to be
1228 executed after an Insert statement.
1229 @see drv_beforeInsert()
1230 */
1231 virtual bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) {
1232 Q_UNUSED(tableName);
1233 Q_UNUSED(fields);
1234 return true;
1235 }
1236
1237 /*! Preprocessing required by drivers before execution of an
1238 Update statement.
1239 Reimplement this method in your driver if there are any special processing steps to be
1240 executed before an Update statement.
1241 @see drv_afterUpdate()
1242 */
1243 virtual bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) {
1244 Q_UNUSED(tableName);
1245 Q_UNUSED(fields);
1246 return true;
1247 }
1248
1249 /*! Postprocessing required by drivers before execution of an
1250 Insert statement.
1251 Reimplement this method in your driver if there are any special processing steps to be
1252 executed after an Update statement.
1253 @see drv_beforeUpdate()
1254 */
1255 virtual bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) {
1256 Q_UNUSED(tableName);
1257 Q_UNUSED(fields);
1258 return true;
1259 }
1260
1261 /*! Changes autocommiting option for established connection.
1262 @return true on success.
1263
1264 Note for driver developers: reimplement this only if your engine
1265 allows to set special auto commit option (like "SET AUTOCOMMIT=.." in MySQL).
1266 If not, auto commit behavior will be simulated if at least single
1267 transactions per connection are supported by the engine.
1268 Do not set any internal flags for autocommiting -- it is already done inside
1269 setAutoCommit().
1270
1271 Default implementation does nothing with connection, just returns true.
1272
1273 @see drv_beginTransaction(), autoCommit(), setAutoCommit()
1274 */
1275 virtual bool drv_setAutoCommit(bool on);
1276
1277 /*! Prepare an SQL statement and return a @a KDbPreparedStatementInterface-derived object.
1278 Ownership of the returned object is passed to the caller. */
1279 virtual KDbPreparedStatementInterface* prepareStatementInternal() /*Q_REQUIRED_RESULT*/ = 0;
1280
1281 /*! Internal, for handling autocommited transactions:
1282 begins transaction if one is supported.
1283 @return true if new transaction started
1284 successfully or no transactions are supported at all by the driver
1285 or if autocommit option is turned off.
1286 A handle to a newly created transaction (or @c nullptr on error) is passed
1287 to @a tg parameter.
1288
1289 Special case when used database driver has only single transaction support
1290 (KDbDriver::SingleTransactions):
1291 and there is already transaction started, it is committed before
1292 starting a new one, but only if this transaction has been started inside KDbConnection object.
1293 (i.e. by beginAutoCommitTransaction()). Otherwise, a new transaction will not be started,
1294 but true will be returned immediately.
1295 */
1296 bool beginAutoCommitTransaction(KDbTransactionGuard* tg);
1297
1298 /*! Internal, for handling autocommited transactions:
1299 Commits transaction prevoiusly started with beginAutoCommitTransaction().
1300 @return true on success or when no transactions are supported
1301 at all by the driver.
1302
1303 Special case when used database driver has only single transaction support
1304 (KDbDriver::SingleTransactions): if @a trans has been started outside KDbConnection object
1305 (i.e. not by beginAutoCommitTransaction()), the transaction will not be committed.
1306 */
1307 bool commitAutoCommitTransaction(const KDbTransaction& trans);
1308
1309 /*! Internal, for handling autocommited transactions:
1310 Rolls back transaction prevoiusly started with beginAutoCommitTransaction().
1311 @return true on success or when no transactions are supported
1312 at all by the driver.
1313
1314 Special case when used database driver has only single transaction support
1315 (KDbDriver::SingleTransactions): @a trans will not be rolled back
1316 if it has been started outside this KDbConnection object.
1317 */
1318 bool rollbackAutoCommitTransaction(const KDbTransaction& trans);
1319
1320 /*! Helper: checks if connection is established;
1321 if not: error message is set up and false returned */
1322 bool checkConnected();
1323
1324 /*! Helper: checks both if connection is established and database any is used;
1325 if not: error message is set up and false returned */
1326 bool checkIsDatabaseUsed();
1327
1328 /*! Update a record. */
1329 bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false);
1330 /*! Insert a new record. */
1331 bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false);
1332 /*! Delete an existing record. */
1333 bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false);
1334 /*! Delete all existing records. */
1335 bool deleteAllRecords(KDbQuerySchema* query);
1336
1337 /*! Called by KDbTableSchema -- signals destruction to KDbConnection object
1338 To avoid having deleted table object on its list. */
1339 void removeMe(KDbTableSchema *ts);
1340
1341 // -- internal methods follow
1342
1343 /*! @internal
1344 @return true if the cursor @a cursor contains column @a column,
1345 else, sets appropriate error with a message and returns false. */
1346 bool checkIfColumnExists(KDbCursor *cursor, int column);
1347
1348 /*! @internal used by insertRecord() methods. */
1349 QSharedPointer<KDbSqlResult> insertRecordInternal(const QString &tableSchemaName,
1350 KDbFieldList *fields,
1351 const KDbEscapedString &sql);
1352
1353 /*! @internal used by querySingleRecord() methods. */
1354 tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql,
1355 KDbQuerySchema* query, const QList<QVariant>* params,
1356 QueryRecordOptions options);
1357
1358 /*! @internal used by querySingleString() methods. */
1359 tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value,
1360 KDbQuerySchema* query, const QList<QVariant>* params,
1361 int column, QueryRecordOptions options);
1362
1363 /*! @internal used by queryNumberString() methods. */
1364 tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number,
1365 KDbQuerySchema* query, const QList<QVariant>* params,
1366 int column, QueryRecordOptions options);
1367
1368 /*! @internal used by queryStringList() methods. */
1369 bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list,
1370 KDbQuerySchema* query, const QList<QVariant>* params,
1371 int column, bool (*filterFunction)(const QString&));
1372
1373 /*! @internal used by *Internal() methods.
1374 Executes query based on a raw SQL statement @a sql or @a query with optional @a params.
1375 Ownership of the returned object is passed to the caller.*/
1376 Q_REQUIRED_RESULT KDbCursor *executeQueryInternal(const KDbEscapedString &sql,
1377 KDbQuerySchema *query,
1378 const QList<QVariant> *params);
1379
1380 /*! Loads extended schema information for table @a tableSchema,
1381 if present (see ExtendedTableSchemaInformation in Kexi Wiki).
1382 @return true on success */
1383 bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema);
1384
1385 /*! Stores extended schema information for table @a tableSchema,
1386 (see ExtendedTableSchemaInformation in Kexi Wiki).
1387 The action is performed within the current transaction,
1388 so it's up to you to commit.
1389 Used, e.g. by createTable(), within its transaction.
1390 @return true on success */
1391 bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema);
1392
1393 /*! @internal
1394 Stores main field's schema information for field @a field.
1395 Used in table altering code when information in kexi__fields has to be updated.
1396 @return true on success and false on failure. */
1397 bool storeMainFieldSchema(KDbField *field);
1398
1399 //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1400
1401 /*! This is a part of alter table interface implementing lower-level operations
1402 used to perform table schema altering. Used by KDbAlterTableHandler.
1403
1404 Changes value of field property.
1405 @return true on success, false on failure, cancelled if the action has been cancelled.
1406
1407 Note for driver developers: implement this if the driver has to supprot the altering. */
1409 const QString& propertyName, const QVariant& value) {
1410 Q_UNUSED(table); Q_UNUSED(field); Q_UNUSED(propertyName); Q_UNUSED(value);
1411 return cancelled;
1412 }
1413
1414 //! Used by KDbCursor class
1415 void addCursor(KDbCursor* cursor);
1416
1417 //! Used by KDbCursor class
1418 void takeCursor(KDbCursor* cursor);
1419
1420private:
1421 //! Internal, used by storeObjectData(KDbObject*) and storeNewObjectData(KDbObject* object).
1422 bool storeObjectDataInternal(KDbObject* object, bool newObject);
1423
1424 //! @internal
1425 //! @return identifier escaped by driver (if @a escapingType is KDb::DriverEscaping)
1426 //! or by the KDb's built-in escape routine.
1427 QString escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const;
1428
1429 KDbConnectionPrivate* d; //!< @internal d-pointer class.
1430
1431 Q_DISABLE_COPY(KDbConnection)
1432 friend class KDbConnectionPrivate;
1433 friend class KDbAlterTableHandler;
1434 friend class KDbConnectionProxy;
1435 friend class KDbCursor;
1436 friend class KDbDriver;
1437 friend class KDbProperties; //!< for setError()
1438 friend class KDbQuerySchema;
1439 friend class KDbQuerySchemaPrivate;
1440 friend class KDbTableSchemaChangeListenerPrivate;
1441 friend class KDbTableSchema; //!< for removeMe()
1442};
1443
1444Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::QueryRecordOptions)
1445Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::AlterTableNameOptions)
1446Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::CreateTableOptions)
1447
1448#endif
A tool for handling altering database table schema.
Definition KDbAlter.h:110
Database specific connection data, e.g. host, port.
Generic options for a single connection. The options are accessible using key/value pairs....
The KDbConnectionProxy class gives access to protected (low-level) API of KDbConnection.
Provides database connection, allowing queries and data modification.
CreateTableOption
Options for creating table.
virtual KDbCursor * prepareQuery(KDbQuerySchema *query, KDbCursor::Options options=KDbCursor::Option::None)=0
virtual bool drv_closeDatabase()=0
virtual KDbPreparedStatementInterface * prepareStatementInternal()=0
virtual bool drv_getServerVersion(KDbServerVersionInfo *version)=0
virtual bool drv_isDatabaseUsed() const
virtual bool drv_executeSql(const KDbEscapedString &sql)=0
Executes query for a raw SQL statement sql without returning resulting records.
virtual bool drv_useDatabase(const QString &dbName=QString(), bool *cancelled=nullptr, KDbMessageHandler *msgHandler=nullptr)=0
virtual KDbSqlResult * drv_prepareSql(const KDbEscapedString &sql)=0
Prepares query for a raw SQL statement sql with possibility of returning records.
virtual bool drv_disconnect()=0
virtual bool drv_createDatabase(const QString &dbName=QString())=0
virtual KDbCursor * prepareQuery(const KDbEscapedString &sql, KDbCursor::Options options=KDbCursor::Option::None)=0
virtual bool drv_dropDatabase(const QString &dbName=QString())=0
virtual bool drv_connect()=0
AlterTableNameOption
Options for altering table name.
virtual bool drv_beforeInsert(const QString &tableName, KDbFieldList *fields)
virtual bool drv_afterInsert(const QString &tableName, KDbFieldList *fields)
QueryRecordOption
Options for querying records.
virtual bool drv_afterUpdate(const QString &tableName, KDbFieldList *fields)
virtual bool drv_beforeUpdate(const QString &tableName, KDbFieldList *fields)
virtual tristate drv_changeFieldProperty(KDbTableSchema *table, KDbField *field, const QString &propertyName, const QVariant &value)
virtual tristate drv_containsTable(const QString &tableName)=0
Provides database cursor functionality.
Definition KDbCursor.h:69
Database driver's abstraction.
Definition KDbDriver.h:50
Specialized string for escaping.
Meta-data for a field.
Definition KDbField.h:72
Prepared statement interface for backend-dependent implementations.
Prepared database command for optimizing sequences of multiple database actions.
Type
Defines type of the prepared statement.
A set of storable database properties.
KDbQuerySchema provides information about database query.
Structure for storing single record with type information.
provides data for single edited database record
Interface for classes providing a result.
The KDbSqlResult class abstracts result of a raw SQL query preparation by KDbConnection::prepareSql()
An interface allowing to listen for table schema changes.
Internal prototype for storing transaction handle for KDbTransaction object.
KDbTransactionGuard class is a convenience class that simplifies handling transactions.
This class encapsulates a single database transaction.
3-state logical type with three values: true, false and cancelled and convenient operators.
IdentifierEscapingType
Escaping type for identifiers.
Definition KDbGlobal.h:144
@ AnyObjectType
helper
Definition KDbGlobal.h:132
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Mon Nov 18 2024 12:19:07 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.