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 30 class KDbConnectionData; 31 class KDbConnectionOptions; 32 class KDbConnectionPrivate; 33 class KDbConnectionProxy; 34 class KDbDriver; 35 class KDbProperties; 36 class KDbRecordData; 37 class KDbRecordEditBuffer; 38 class KDbServerVersionInfo; 39 class KDbSqlResult; 40 class KDbTableSchemaChangeListener; 41 class KDbTableSchemaChangeListenerPrivate; 42 class KDbTransactionGuard; 43 class 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 */ 51 class KDB_EXPORT KDbConnection : public KDbResultable 52 { 53 Q_DECLARE_TR_FUNCTIONS(KDbConnection) 54 public: 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(), 286 KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); 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(), 302 KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); 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 */ 385 virtual KDbCursor* prepareQuery(const KDbEscapedString& sql, 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 KDbCursor* prepareQuery(KDbQuerySchema* query, const QList<QVariant>& params, 398 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 399 400 /*! @overload 401 Prepares query described by @a query schema without parameters. 402 */ 403 virtual KDbCursor* prepareQuery(KDbQuerySchema* query, 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 table_name".*/ 408 KDbCursor* prepareQuery(KDbTableSchema* table, 409 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 410 411 /*! Executes SELECT query described by a raw SQL statement @a sql. 412 @return opened cursor created for results of this query 413 or 0 if there was any error on the cursor creation or opening. 414 Ownership of the returned object is passed to the caller. 415 KDbCursor can have optionally applied @a options. 416 Identifiers in @a sql that are the same as keywords 417 in KDbSQL dialect or the backend's SQL have to be escaped. 418 */ 419 KDbCursor* executeQuery(const KDbEscapedString& sql, 420 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 421 422 /*! @overload executeQuery(const KDbEscapedString&, int) 423 @a params are values of parameters that 424 will be inserted into places marked with [] before execution of the query. 425 426 Statement is build from data provided by @a query schema. 427 Kexi SQL and driver-specific escaping is performed on table names. */ 428 KDbCursor* executeQuery(KDbQuerySchema* query, const QList<QVariant>& params, 429 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 430 431 /*! @overload */ 432 KDbCursor* executeQuery(KDbQuerySchema* query, 433 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 434 435 /*! @overload 436 Executes query described by @a query schema without parameters. 437 Statement is build from data provided by @a table schema, 438 it is like "select * from table_name".*/ 439 KDbCursor* executeQuery(KDbTableSchema* table, 440 KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; 441 442 /*! Deletes cursor @a cursor previously created by functions like executeQuery() 443 for this connection. 444 There is an attempt to close the cursor with KDbCursor::close() if it was opened. 445 Anyway, at last cursor is deleted. 446 @return true if cursor is properly closed before deletion. */ 447 bool deleteCursor(KDbCursor *cursor); 448 449 /*! @return schema of a table pointed by @a tableId, retrieved from currently 450 used database. The schema is cached inside connection, 451 so retrieval is performed only once, on demand. */ 452 KDbTableSchema* tableSchema(int tableId); 453 454 /*! @return schema of a table pointed by @a tableName, retrieved from currently 455 used database. KDb system table schema can be also retrieved. 456 @see tableSchema( int tableId ) */ 457 KDbTableSchema* tableSchema(const QString& tableName); 458 459 /*! @return schema of a query pointed by @a queryId, retrieved from currently 460 used database. The schema is cached inside connection, 461 so retrieval is performed only once, on demand. */ 462 KDbQuerySchema* querySchema(int queryId); 463 464 /*! @return schema of a query pointed by @a queryName, retrieved from currently 465 used database. @see querySchema( int queryId ) */ 466 KDbQuerySchema* querySchema(const QString& queryName); 467 468 /*! Sets @a queryName query obsolete by moving it out of the query sets, so it will not be 469 accessible by querySchema( const QString& queryName ). The existing query object is not 470 destroyed, to avoid problems when it's referenced. In this case, 471 a new query schema will be retrieved directly from the backend. 472 473 For now it's used in KexiQueryDesignerGuiEditor::storeLayout(). 474 This solves the problem when user has changed a query schema but already form still uses 475 previously instantiated query schema. 476 @return true if there is such query. Otherwise the method does nothing. */ 477 bool setQuerySchemaObsolete(const QString& queryName); 478 479 //! Options for querying records 480 //! @since 3.1 481 enum class QueryRecordOption { 482 AddLimitTo1 = 1, //!< Adds a "LIMIT 1" clause to the query for optimization purposes 483 //!< (it should not include one already) 484 Default = AddLimitTo1 485 }; 486 Q_DECLARE_FLAGS(QueryRecordOptions, QueryRecordOption) 487 488 /*! Executes query for a raw statement @a sql and stores first record's data inside @a data. 489 This is a convenient method when we need only first record from query result, 490 or when we know that query result has only one record. 491 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). 492 Caller should make sure it is not there in the @a sql already. 493 @return @c true if query was successfully executed and first record has been found, 494 @c false on data retrieving failure, and @c cancelled if there's no single record available. */ 495 tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, 496 QueryRecordOptions options = QueryRecordOption::Default); 497 498 /*! @overload 499 Uses a KDbQuerySchema object. */ 500 tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, 501 QueryRecordOptions options = QueryRecordOption::Default); 502 503 /*! @overload 504 Accepts @a params as parameters that will be inserted into places marked with "[]" before 505 query execution. */ 506 tristate querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, 507 const QList<QVariant> ¶ms, 508 QueryRecordOptions options = QueryRecordOption::Default); 509 510 /*! Executes query for a raw statement @a sql and stores first record's field's 511 (number @a column) string value inside @a value. 512 For efficiency it's recommended that a query defined by @a sql 513 should have just one field (SELECT one_field FROM ....). 514 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). 515 Caller should make sure it is not there in the @a sql already. 516 @return @c true if query was successfully executed and first record has been found, 517 @c false on data retrieving failure, and @c cancelled if there's no single record available. 518 @see queryStringList() */ 519 tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, 520 QueryRecordOptions options = QueryRecordOption::Default); 521 522 /*! @overload 523 Uses a KDbQuerySchema object. */ 524 tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, 525 QueryRecordOptions options = QueryRecordOption::Default); 526 527 /*! @overload 528 Accepts @a params as parameters that will be inserted into places marked with [] before 529 query execution. */ 530 tristate querySingleString(KDbQuerySchema* query, QString* value, 531 const QList<QVariant>& params, int column = 0, 532 QueryRecordOptions options = QueryRecordOption::Default); 533 534 /*! Convenience function: executes query for a raw SQL statement @a sql and stores first 535 record's field's (number @a column) value inside @a number. @see querySingleString(). 536 If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). 537 Caller should make sure it is not there in the @a sql already. 538 @return true if query was successfully executed and first record has been found, 539 false on data retrieving failure, and cancelled if there's no single record available. */ 540 tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0, 541 QueryRecordOptions options = QueryRecordOption::Default); 542 543 /*! @overload 544 Uses a KDbQuerySchema object. */ 545 tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, 546 QueryRecordOptions options = QueryRecordOption::Default); 547 548 /*! @overload 549 Accepts @a params as parameters that will be inserted into places marked with "[]" before 550 query execution. */ 551 tristate querySingleNumber(KDbQuerySchema* query, int* number, 552 const QList<QVariant>& params, int column = 0, 553 QueryRecordOptions options = QueryRecordOption::Default); 554 555 /*! Executes query for a raw SQL statement @a sql and stores Nth field's string value 556 of every record inside @a list, where N is equal to @a column. The list is initially cleared. 557 For efficiency it's recommended that a query defined by @a sql 558 should have just one field (SELECT one_field FROM ....). 559 @return true if all values were fetched successfuly, 560 false on data retrieving failure. Returning empty list can be still a valid result. 561 On errors, the list is not cleared, it may contain a few retrieved values. */ 562 bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0); 563 564 /*! @overload 565 Uses a QuerySchema object. */ 566 bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); 567 568 /*! @overload 569 Accepts @a params as parameters that will be inserted into places marked with "[]" before 570 query execution. */ 571 bool queryStringList(KDbQuerySchema* query, QStringList* list, 572 const QList<QVariant>& params, int column = 0); 573 574 /*! @return @c true if there is at least one record has been returned by executing query 575 for a raw SQL statement @a sql or @c false if no such record exists. 576 If @a options includes AddLimitTo1 value, the query is optimized into "SELECT 1 FROM (sql) LIMIT 1" 577 (this is the default). Caller should make sure "SELECT 1" and "LIMIT 1" is not there in the 578 @a sql already. 579 This method does not fetch any records. On error returns @c cancelled. */ 580 tristate resultExists(const KDbEscapedString &sql, 581 QueryRecordOptions options = QueryRecordOption::Default); 582 583 /*! @return true if there is at least one record in @a table. */ 584 tristate isEmpty(KDbTableSchema* table); 585 586 /** 587 * @brief Return recently used SQL string 588 * 589 * If there was a successful query execution it is equal to result().sql(), 590 * otherwise it is equal to result().errorSql(). 591 */ 592 virtual KDbEscapedString recentSqlString() const; 593 594 //PROTOTYPE: 595 #define A , const QVariant& 596 #define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema* tableSchema args) 597 #define H_INS_REC_ALL \ 598 H_INS_REC(A); \ 599 H_INS_REC(A A); \ 600 H_INS_REC(A A A); \ 601 H_INS_REC(A A A A); \ 602 H_INS_REC(A A A A A); \ 603 H_INS_REC(A A A A A A); \ 604 H_INS_REC(A A A A A A A); \ 605 H_INS_REC(A A A A A A A A) 606 H_INS_REC_ALL; 607 608 #undef H_INS_REC 609 #define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList* fields args) 610 611 H_INS_REC_ALL; 612 #undef H_INS_REC_ALL 613 #undef H_INS_REC 614 #undef A 615 616 QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema *tableSchema, 617 const QList<QVariant> &values); 618 619 QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList *fields, const QList<QVariant> &values); 620 621 //! Options for creating table 622 //! @since 3.1 623 enum class CreateTableOption { 624 Default = 0, 625 DropDestination = 1 //!< Drop destination table if exists 626 }; 627 Q_DECLARE_FLAGS(CreateTableOptions, CreateTableOption) 628 629 /** 630 * @brief Creates a new table 631 * 632 * Creates a new table defined by @a tableSchema. @c true is returned on success. In this case 633 * @a tableSchema object is added to KDbConnection's structures and becomes owned the 634 * KDbConnection object, so should not be destroyed by hand. 635 * 636 * If @a options include the DropDestination value and table schema with the same name as @a 637 * tableSchema exists, it is dropped and the original identifier of the dropped schem is 638 * assigned to the @a tableSchema object. 639 * 640 * If @a options do not include the DropDestination value and table schema with the same name 641 * as @a tableSchema exists, @c false is returned. 642 * 643 * Table and column definitions are added to "Kexi system" tables. 644 * 645 * Prior to dropping the method checks if the table for the schema is in use, and if the new 646 * schema defines at least one column. 647 * 648 * Note that on error: 649 * - @a tableSchema is not inserted into KDbConnection's structures, so caller is still owner 650 * of the object, 651 * - existing table schema object is not destroyed (e.g. it is still available for 652 * KDbConnection::tableSchema(const QString&), even if the table was physically dropped. 653 * 654 * @return true on success. 655 */ 656 bool createTable(KDbTableSchema *tableSchema, 657 CreateTableOptions options = CreateTableOption::Default); 658 659 /*! Creates a copy of table schema defined by @a tableSchema with data. 660 Name, caption and description will be copied from @a newData. 661 @return a table schema object. It is inserted into the KDbConnection structures 662 and is owned by the KDbConnection object. The created table schema object should not 663 be destroyed by hand afterwards. 664 0 is returned on failure. Table with destination name must not exist. 665 @see createTable() */ 666 KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData); 667 668 /*! It is a convenience function, does exactly the same as 669 KDbTableSchema *copyTable(const KDbTableSchema&, const KDbObject&). */ 670 KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData); 671 672 /*! Drops a table defined by @a tableSchema (both table object as well as physically). 673 If true is returned, schema information @a tableSchema is destoyed 674 (because it's owned), so don't keep this anymore! 675 No error is raised if the table does not exist physically 676 - its schema is removed even in this case. 677 678 Removes the table and column definitions in kexi__* "system schema" tables. 679 First checks that the table is not a system table. 680 681 @todo Check that a database is currently in use? (c.f. createTable) 682 @todo Update any structure (e.g. query) that depends on this table */ 683 tristate dropTable(KDbTableSchema* tableSchema); 684 685 /*! @overload 686 * It is a convenience function. 687 */ 688 tristate dropTable(const QString& tableName); 689 690 /*! Alters @a tableSchema using @a newTableSchema in memory and on the db backend. 691 @return true on success, cancelled if altering was cancelled. */ 692 //! @todo (js): implement real altering 693 //! @todo (js): update any structure (e.g. query) that depend on this table! 694 tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema); 695 696 //! Options for altering table name 697 //! @since 3.1 698 enum class AlterTableNameOption { 699 Default = 0, 700 DropDestination = 1 //!< Drop destination table if exists 701 }; 702 Q_DECLARE_FLAGS(AlterTableNameOptions, AlterTableNameOption) 703 704 /** 705 * @brief Alters name of table 706 * 707 * Alters name of table described by @a tableSchema to @a newName. 708 * If @a options include the DropDestination value and table having name @a newName already 709 * exists, it is physically dropped, removed from connection's list of tables and replaced 710 * by @a tableSchema. In this case identifier of @a tableSchema is set to the dropped table's 711 * identifier. This can be useful if @a tableSchema was created with a temporary name and 712 * identifier. It is for example used in KDbAlterTableHandler. 713 * 714 * If @a options do not include the DropDestination value (the default) and table having name 715 * @a newName already exists, @c false is returned and @c ERR_OBJECT_EXISTS error is set in 716 * the connection object. 717 * 718 * Table name in the schema of @a tableSchema is updated on successful altering. 719 * @return true on success. 720 */ 721 bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, 722 AlterTableNameOptions options = AlterTableNameOption::Default); 723 724 /*! Drops a query defined by @a querySchema. 725 If true is returned, schema information @a querySchema is destoyed 726 (because it's owned), so don't keep this anymore! 727 */ 728 bool dropQuery(KDbQuerySchema* querySchema); 729 730 /*! It is a convenience function, does exactly the same as 731 bool dropQuery( KDbQuerySchema* querySchema ) */ 732 bool dropQuery(const QString& queryName); 733 734 /*! Removes information about object with @a objId 735 from internal "kexi__object" and "kexi__objectdata" tables. 736 @return true on success. */ 737 bool removeObject(int objId); 738 739 /*! @return first field from @a fieldlist that has system name, 740 @c nullptr if there are no such field. 741 For checking, KDbDriver::isSystemFieldName() is used, so this check can 742 be driver-dependent. */ 743 KDbField* findSystemFieldName(const KDbFieldList& fieldlist); 744 745 /*! @return name of any (e.g. first found) database for this connection. 746 This method does not close or open this connection. The method can be used 747 (it is also internally used, e.g. for database dropping) when we need 748 a database name before we can connect and execute any SQL statement 749 (e.g. DROP DATABASE). 750 751 The method can return nul lstring, but in this situation no automatic (implicit) 752 connections could be made, what is useful by e.g. dropDatabase(). 753 754 Note for driver developers: return here a name of database which you are sure 755 is existing. 756 Default implementation returns: 757 - value that previously had been set using setAvailableDatabaseName() for 758 this connection, if it is not empty 759 - else (2nd priority): value of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME 760 if it is not empty. 761 762 See description of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME member. 763 You may want to reimplement this method only when you need to depend on 764 this connection specifics 765 (e.g. you need to check something remotely). 766 */ 767 virtual QString anyAvailableDatabaseName(); 768 769 /*! Sets @a dbName as name of a database that can be accessible. 770 This is option that e.g. application that make use of KDb library can set 771 to tune connection's behavior when it needs to temporary connect to any database 772 in the server to do some work. 773 You can pass empty dbName - then anyAvailableDatabaseName() will try return 774 KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value 775 instead of the one previously set with setAvailableDatabaseName(). 776 777 @see anyAvailableDatabaseName() 778 */ 779 void setAvailableDatabaseName(const QString& dbName); 780 781 /*! Because some engines need to have opened any database before 782 executing administrative SQL statements like "create database" or "drop database", 783 this method is used to use appropriate, existing database for this connection. 784 For file-based db drivers this always return true and does not set @a name 785 to any value. For other db drivers: this sets @a name to db name computed 786 using anyAvailableDatabaseName(), and if the name computed is empty, false 787 is returned; if it is not empty, useDatabase() is called. 788 False is returned also when useDatabase() fails. 789 You can call this method from your application's level if you really want to perform 790 tasks that require any used database. In such a case don't forget 791 to closeDatabase() if returned @a name is not empty. 792 793 Note: This method has nothing to do with creating or using temporary databases 794 in such meaning that these database are not persistent 795 */ 796 bool useTemporaryDatabaseIfNeeded(QString* name); 797 798 /** 799 * Prepares execution of a new native (raw, backend-specific) SQL query. 800 * 801 * The query is described by a raw statement @a sql which should be is valid and properly 802 * escaped. Access to results can be obtained using 803 * the returned KDbSqlResult object. The object is guarded with a shared pointer to facilitate 804 * transfer of ownership and memory management. A null pointer is returned if preparation of 805 * the query fails. Use KDbConnection::result() immediately after calling prepareSql() to 806 * obtain detailed result information about the preparation. 807 * 808 * The returned object should be deleted before the database connection is closed. 809 * Connection object does not deletes the KDbSqlResult objects. It is also possible and 810 * recommended that caller deletes the KDbSqlResult object as soon as the result is not needed. 811 * 812 * The returned object can be ignored if the query is not supposed to return records (e.g. 813 * manipulates data through INSERT, UPDATE, DELETE, ...) or the caller is not interested in the 814 * records. Thanks to the use of the shared pointer the object will be immediately deleted and 815 * execution will be finalized prior to that. However to execute queries that return no 816 * results, executeSql() is a better choice because of performance and easier reporting to 817 * results. 818 * 819 * @note Only use this method if a non-portable raw query is required. 820 * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. 821 */ 822 QSharedPointer<KDbSqlResult> prepareSql(const KDbEscapedString& sql) Q_REQUIRED_RESULT; 823 824 /** 825 * Executes a new native (raw, backend-specific) SQL query 826 * 827 * The query is described by a raw statement @a sql which should be is valid and properly 828 * escaped. This method is a convenience version of prepareSql() that immediately starts and 829 * finalizes execution of a raw query in one step and provides a result. Use it for queries 830 * that do not return records, i.e. for queries that manipulate data (INSERT, UPDATE, DELETE, 831 * ...) or if the caller is not interested in the returned records. 832 * 833 * @note Only use this method if a non-portable raw query is required. 834 * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. 835 */ 836 bool executeSql(const KDbEscapedString& sql); 837 838 /*! Stores object (id, name, caption, description) 839 described by @a object on the backend. It is expected that entry on the 840 backend already exists, so it's updated. Changes to identifier attribute are not allowed. 841 @return true on success. */ 842 bool storeObjectData(KDbObject* object); 843 844 /*! Stores new entry for object (id, name, caption, description) 845 described by @a object on the backend. If object.id() was less than 0, 846 new, unique object identifier is obtained and assigned to @a object (see KDbObject::id()). 847 @return true on success. */ 848 bool storeNewObjectData(KDbObject* object); 849 850 /*! Finds object data for object of type @a type and identifier @a id. 851 Added for convenience. 852 If @a type is KDb::AnyObjectType, object type is ignored during the find. 853 @see setupObjectData(const KDbRecordData*, KDbObject*). 854 @return true on success, false on failure and cancelled when such object couldn't be found. 855 @since 3.1 856 */ 857 tristate loadObjectData(int type, int id, KDbObject* object); 858 859 /*! Finds object data for object of type @a type and name @a name. 860 If the object is found, resulted schema is stored in @a object and true is returned, 861 otherwise false is returned. */ 862 tristate loadObjectData(int type, const QString& name, KDbObject* object); 863 864 /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID 865 and puts it to @a dataString. The can be block indexed with optional @a dataID. 866 @return true on success, false on failure and cancelled when there is no such data block 867 @see storeDataBlock(). */ 868 tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString()); 869 870 /*! Stores (potentially large) data block @a dataString (e.g. xml form's representation), 871 referenced by objectID. Block will be stored in "kexi__objectdata" table and 872 an optional @a dataID identifier. 873 If there is already such record in the table, it's simply overwritten. 874 @return true on success 875 @see loadDataBlock() removeDataBlock() copyDataBlock(). */ 876 bool storeDataBlock(int objectID, const QString &dataString, 877 const QString& dataID = QString()); 878 879 /*! Copies (potentially large) data, e.g. form's XML representation, 880 referenced by @a sourceObjectID pointed by optional @a dataID. 881 @return true on success. Does not fail if blocks do not exist. 882 Prior to copying, existing data blocks are removed even if there are no new blocks to copy. 883 Copied data blocks will have @a destObjectID object identifier assigned. 884 Note that if @a dataID is not specified, all data blocks found for the @a sourceObjectID 885 will be copied. 886 @see loadDataBlock() storeDataBlock() removeDataBlock(). */ 887 bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString()); 888 889 /*! Removes (potentially large) string data (e.g. xml form's representation), 890 referenced by @a objectID, and pointed by optional @a dataID. 891 @return true on success. Does not fail if the block does not exist. 892 Note that if @a dataID is not specified, all data blocks for the @a objectID will be removed. 893 @see loadDataBlock() storeDataBlock() copyDataBlock(). */ 894 bool removeDataBlock(int objectID, const QString& dataID = QString()); 895 896 /*! Prepare an SQL statement and return a @a KDbPreparedStatement instance. */ 897 KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type, 898 KDbFieldList* fields, const QStringList& whereFieldNames = QStringList()); 899 900 bool isInternalTableSchema(const QString& tableName); 901 902 /** 903 * @brief Returns number of records returned by given SQL statement 904 * 905 * @return number of records that can be retrieved after executing @a sql statement within 906 * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not 907 * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. 908 * -1 is returned if any error occurred or if @a conn is @c nullptr. 909 * 910 * @since 3.1 911 */ 912 //! @todo perhaps use quint64 here? 913 int recordCount(const KDbEscapedString& sql); 914 915 /** 916 * @brief Returns number of records that contains given table 917 * 918 * @return number of records that can be retrieved from @a tableSchema. 919 * To obtain the result the table must be created or retrieved using a KDbConnection object, 920 * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" 921 * SQL aggregation is used at the backed. 922 * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr. 923 * 924 * @since 3.1 925 */ 926 //! @todo perhaps use quint64 here? 927 //! @todo does not work with non-SQL data sources 928 int recordCount(const KDbTableSchema& tableSchema); 929 930 /** 931 * @overload 932 * 933 * Operates on a query schema. @a params are optional values of parameters that will be inserted 934 * into [] placeholders before execution of query that counts the records. 935 * To obtain the result the query must be created or retrieved using a KDbConnection object, 936 * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" 937 * SQL aggregation is used at the backed. 938 * -1 is returned if error occurred or if querySchema->connection() is @c nullptr. 939 * 940 * @since 3.1 941 */ 942 //! @todo perhaps use quint64 here? 943 int recordCount(KDbQuerySchema* querySchema, 944 const QList<QVariant>& params = QList<QVariant>()); 945 946 /** 947 * @overload 948 * 949 * Operates on a table or query schema. @a params is a list of optional parameters that 950 * will be inserted into [] placeholders before execution of query that counts the records. 951 * 952 * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned. 953 * 954 * @since 3.1 955 */ 956 //! @todo perhaps use quint64 here? 957 int recordCount(KDbTableOrQuerySchema* tableOrQuery, 958 const QList<QVariant>& params = QList<QVariant>()); 959 960 //! Identifier escaping function in the associated KDbDriver. 961 /*! Calls the identifier escaping function in this connection to 962 escape table and column names. This should be used when explicitly 963 constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)). 964 It should not be used for other functions (e.g. don't do 965 useDatabase(escapeIdentifier(database))), because the identifier will 966 be escaped when the called function generates, for example, "USE " + 967 escapeIdentifier(database). 968 969 For efficiency, KDb "system" tables (prefixed with kexi__) 970 and columns therein are not escaped - we assume these are valid identifiers for all drivers. 971 972 Use KDbEscapedString::isValid() to check if escaping has been performed successfully. 973 Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true, 974 not just isEmpty(). 975 */ 976 virtual QString escapeIdentifier(const QString& id) const; 977 978 protected: 979 /*! Used by KDbDriver */ 980 KDbConnection(KDbDriver *driver, const KDbConnectionData& connData, 981 const KDbConnectionOptions &options); 982 983 /*! Method to be called form KDbConnection's subclass destructor. 984 @see ~KDbConnection() */ 985 void destroy(); 986 987 /*! For implementation: connects to database. 988 @return true on success. */ 989 virtual bool drv_connect() = 0; 990 991 /*! For implementation: disconnects database 992 @return true on success. */ 993 virtual bool drv_disconnect() = 0; 994 995 /*! For implementation: Sets @a version to real server's version. 996 Depending on backend type this method is called after 997 (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is true) 998 or before database is used 999 (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is false), 1000 i.e. for PostgreSQL it is called after. 1001 In any case it is called after successful drv_connect(). 1002 @return true on success. */ 1003 virtual bool drv_getServerVersion(KDbServerVersionInfo* version) = 0; 1004 1005 /** 1006 * LOW LEVEL METHOD. Obtains a list containing names of all physical 1007 * tables of this connection and returns it. 1008 * 1009 * @a ok must not be @c nullptr. 1010 * 1011 * Default implementation covers functionality of SQL backends. It executes low-level SQL 1012 * defined by KDbDriverBehavior::GET_TABLE_NAMES_SQL string. On failure of execution or if 1013 * KDbDriverBehavior::GET_TABLE_NAMES_SQL is empty, @a ok is set to @c false. On success @a ok 1014 * is set to @c true. Returning empty list is not an error. 1015 * 1016 * If the database driver is not able to offer such a list, do not reimplement this method, it 1017 * will just always return false and users of KDb will need to take this into account. 1018 * 1019 * To reimplement the method, set @a ok to @c true only on successfull obtaining of table names, 1020 * and to @c false otherwise. 1021 * 1022 * This method is used by tableNames() to filter out tables names that have been found in 1023 * project's metadata but lack related physical tables. 1024 * 1025 * @since 3.2 1026 * 1027 * @see tableNames() 1028 */ 1029 virtual QStringList drv_getTableNames(bool *ok); 1030 1031 /*! LOW LEVEL METHOD. For implementation: returns true if table 1032 with name @a tableName exists in the database. 1033 @return @c false if it does not exist or @c cancelled if error occurred. 1034 The lookup is case insensitive. */ 1035 virtual tristate drv_containsTable(const QString &tableName) = 0; 1036 1037 /** 1038 * Creates table using @a tableSchema information. 1039 * 1040 * @return true on success. 1041 * 1042 * Default implementation builds a statement using createTableStatement() and calls 1043 * executeSql(). Note for driver developers: reimplement this only to perform creation in other 1044 * way. 1045 */ 1046 virtual bool drv_createTable(const KDbTableSchema& tableSchema); 1047 1048 /*! Alters table's described @a tableSchema name to @a newName. 1049 This is the default implementation, using "ALTER TABLE <oldname> RENAME TO <newname>", 1050 what's supported by SQLite >= 3.2, PostgreSQL, MySQL. 1051 Backends lacking ALTER TABLE, for example SQLite, reimplement this with by an inefficient 1052 data copying to a new table. In any case, renaming is performed at the backend. 1053 It's good idea to keep the operation within a transaction. 1054 @return true on success. */ 1055 virtual bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName); 1056 1057 /*! Copies table data from @a tableSchema to @a destinationTableSchema 1058 Default implementation executes "INSERT INTO .. SELECT * FROM .." 1059 @return true on success. */ 1060 virtual bool drv_copyTableData(const KDbTableSchema &tableSchema, 1061 const KDbTableSchema &destinationTableSchema); 1062 1063 /*! Physically drops table named with @a name. 1064 Default impelmentation executes "DROP TABLE.." command, 1065 so you rarely want to change this. */ 1066 virtual bool drv_dropTable(const QString& tableName); 1067 1068 /*! @internal drops table @a tableSchema physically, but destroys 1069 @a tableSchema object only if @a alsoRemoveSchema is true. 1070 Used (alsoRemoveSchema==false) on table altering: 1071 if recreating table can fail we're giving up and keeping 1072 the original table schema (even if it is no longer points to any real data). */ 1073 tristate dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema); 1074 1075 /*! Setups data for object that owns @a object (e.g. table, query) 1076 opened on 'kexi__objects' table, pointing to a record 1077 corresponding to given object. */ 1078 bool setupObjectData(const KDbRecordData& data, KDbObject* object); 1079 1080 /*! @return a new field table schema for a table retrieved from @a data. 1081 Ownership of the returned object is passed to the caller. 1082 Used internally by tableSchema(). */ 1083 KDbField* setupField(const KDbRecordData& data) Q_REQUIRED_RESULT; 1084 1085 /** 1086 * Prepares query for a raw SQL statement @a sql with possibility of returning records. 1087 * 1088 * It is useful mostly for SELECT queries. While INSERT queries do not return records, the 1089 * KDbSqlResult object offers KDbSqlResult::lastInsertRecordId(). The @sql should be is valid 1090 * and properly escaped. Only use this method if you really need. For low-level access to the 1091 * results (without cursors). The result may be not stored (not buffered) yet. Use 1092 * KDbSqlResult::fetchRecord() to fetch each record. @return Null pointer if there is no proper 1093 * result or error. Ownership of the returned object is passed to the caller. 1094 * 1095 * @see prepareSql 1096 */ 1097 virtual KDbSqlResult* drv_prepareSql(const KDbEscapedString &sql) /*Q_REQUIRED_RESULT*/ = 0; 1098 1099 /** 1100 * Executes query for a raw SQL statement @a sql without returning resulting records. 1101 * 1102 * It is useful mostly for INSERT queries but it is possible to execute SELECT queries when 1103 * returned records can be ignored. The @sql should be is valid and properly escaped. 1104 * 1105 * @note Only use this method if you really need. 1106 * @see executeSql 1107 */ 1108 virtual bool drv_executeSql(const KDbEscapedString& sql) = 0; 1109 1110 /*! For reimplementation: loads list of databases' names available for this connection 1111 and adds these names to @a list. If your server is not able to offer such a list, 1112 consider reimplementing drv_databaseExists() instead. 1113 The method should return true only if there was no error on getting database names 1114 list from the server. 1115 Default implementation puts empty list into @a list and returns true. 1116 @see databaseNames */ 1117 virtual bool drv_getDatabasesList(QStringList* list); 1118 1119 /*! For optional reimplementation: asks server if database @a dbName exists. 1120 This method is used internally in databaseExists(). The default implementation 1121 calls databaseNames and checks if that list contains @a dbName. If you need to 1122 ask the server specifically if a database exists, eg. if you can't retrieve a list 1123 of all available database names, please reimplement this method and do all 1124 needed checks. 1125 1126 See databaseExists() description for details about ignoreErrors argument. 1127 You should use it properly in your implementation. 1128 1129 Note: This method should also work if there is already database used (with useDatabase()); 1130 in this situation no changes should be made in current database selection. */ 1131 virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true); 1132 1133 /*! For implementation: creates new database using connection */ 1134 virtual bool drv_createDatabase(const QString &dbName = QString()) = 0; 1135 1136 /*! For implementation: opens existing database using connection 1137 @return true on success, false on failure; sets @a cancelled to true if this action 1138 has been cancelled. */ 1139 virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, 1140 KDbMessageHandler* msgHandler = nullptr) = 0; 1141 1142 /*! For implementation: closes previously opened database 1143 using connection. */ 1144 virtual bool drv_closeDatabase() = 0; 1145 1146 /*! @return true if internal driver's structure is still in opened/connected 1147 state and database is used. 1148 Note for driver developers: Put here every test that you can do using your 1149 internal engine's database API, 1150 eg (a bit schematic): my_connection_struct->isConnected()==true. 1151 Do not check things like KDbConnection::isDatabaseUsed() here or other things 1152 that "KDb already knows" at its level. 1153 If you cannot test anything, just leave default implementation (that returns true). 1154 1155 Result of this method is used as an additional chance to check for isDatabaseUsed(). 1156 Do not call this method from your driver's code, it should be used at KDb level only. 1157 */ drv_isDatabaseUsed()1158 virtual bool drv_isDatabaseUsed() const { 1159 return true; 1160 } 1161 1162 /*! For implementation: drops database from the server 1163 using connection. After drop, database shouldn't be accessible 1164 anymore. */ 1165 virtual bool drv_dropDatabase(const QString &dbName = QString()) = 0; 1166 1167 /*! 1168 Creates table named by @a tableName. Schema object must be on 1169 schema tables' list before calling this method (otherwise false if returned). 1170 Just uses drv_createTable( const KDbTableSchema& tableSchema ). 1171 Used internally, e.g. in createDatabase(). 1172 @return true on success 1173 */ 1174 virtual bool drv_createTable(const QString& tableName); 1175 1176 /*! Note for driver developers: begins new transaction 1177 and returns handle to it. Default implementation just 1178 executes "BEGIN" sql statement and returns just empty data (KDbTransactionData object). 1179 Ownership of the returned object is passed to the caller. 1180 1181 Drivers that do not support transactions (see KDbDriver::features()) 1182 do never call this method. 1183 Reimplement this method if you need to do something more 1184 (e.g. if you driver will support multiple transactions per connection). 1185 Make subclass of KDbTransactionData (declared in KDbTransaction.h) 1186 and return object of this subclass. 1187 @c nullptr should be returned on error. 1188 Do not check anything in connection (isConnected(), etc.) - all is already done. 1189 1190 @todo Add support for nested transactions, 1191 e.g. KDbTransactionData* beginTransaction(KDbTransactionData *parent) 1192 */ 1193 virtual KDbTransactionData* drv_beginTransaction() Q_REQUIRED_RESULT; 1194 1195 /*! Note for driver developers: begins new transaction 1196 and returns handle to it. Default implementation just 1197 executes "COMMIT" sql statement and returns true on success. 1198 1199 @see drv_beginTransaction() 1200 */ 1201 virtual bool drv_commitTransaction(KDbTransactionData* trans); 1202 1203 /*! Note for driver developers: begins new transaction 1204 and returns handle to it. Default implementation just 1205 executes "ROLLBACK" sql statement and returns true on success. 1206 1207 @see drv_beginTransaction() 1208 */ 1209 virtual bool drv_rollbackTransaction(KDbTransactionData* trans); 1210 1211 1212 /*! Preprocessing (if any) required by drivers before execution of an 1213 Insert statement. 1214 Reimplement this method in your driver if there are any special processing steps to be 1215 executed before an Insert statement. 1216 @see drv_afterInsert() 1217 */ drv_beforeInsert(const QString & tableName,KDbFieldList * fields)1218 virtual bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) { 1219 Q_UNUSED(tableName); 1220 Q_UNUSED(fields); 1221 return true; 1222 } 1223 1224 /*! Postprocessing (if any) required by drivers before execution of an 1225 Insert statement. 1226 Reimplement this method in your driver if there are any special processing steps to be 1227 executed after an Insert statement. 1228 @see drv_beforeInsert() 1229 */ drv_afterInsert(const QString & tableName,KDbFieldList * fields)1230 virtual bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) { 1231 Q_UNUSED(tableName); 1232 Q_UNUSED(fields); 1233 return true; 1234 } 1235 1236 /*! Preprocessing required by drivers before execution of an 1237 Update statement. 1238 Reimplement this method in your driver if there are any special processing steps to be 1239 executed before an Update statement. 1240 @see drv_afterUpdate() 1241 */ drv_beforeUpdate(const QString & tableName,KDbFieldList * fields)1242 virtual bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) { 1243 Q_UNUSED(tableName); 1244 Q_UNUSED(fields); 1245 return true; 1246 } 1247 1248 /*! Postprocessing required by drivers before execution of an 1249 Insert statement. 1250 Reimplement this method in your driver if there are any special processing steps to be 1251 executed after an Update statement. 1252 @see drv_beforeUpdate() 1253 */ drv_afterUpdate(const QString & tableName,KDbFieldList * fields)1254 virtual bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) { 1255 Q_UNUSED(tableName); 1256 Q_UNUSED(fields); 1257 return true; 1258 } 1259 1260 /*! Changes autocommiting option for established connection. 1261 @return true on success. 1262 1263 Note for driver developers: reimplement this only if your engine 1264 allows to set special auto commit option (like "SET AUTOCOMMIT=.." in MySQL). 1265 If not, auto commit behavior will be simulated if at least single 1266 transactions per connection are supported by the engine. 1267 Do not set any internal flags for autocommiting -- it is already done inside 1268 setAutoCommit(). 1269 1270 Default implementation does nothing with connection, just returns true. 1271 1272 @see drv_beginTransaction(), autoCommit(), setAutoCommit() 1273 */ 1274 virtual bool drv_setAutoCommit(bool on); 1275 1276 /*! Prepare an SQL statement and return a @a KDbPreparedStatementInterface-derived object. 1277 Ownership of the returned object is passed to the caller. */ 1278 virtual KDbPreparedStatementInterface* prepareStatementInternal() /*Q_REQUIRED_RESULT*/ = 0; 1279 1280 /*! Internal, for handling autocommited transactions: 1281 begins transaction if one is supported. 1282 @return true if new transaction started 1283 successfully or no transactions are supported at all by the driver 1284 or if autocommit option is turned off. 1285 A handle to a newly created transaction (or @c nullptr on error) is passed 1286 to @a tg parameter. 1287 1288 Special case when used database driver has only single transaction support 1289 (KDbDriver::SingleTransactions): 1290 and there is already transaction started, it is committed before 1291 starting a new one, but only if this transaction has been started inside KDbConnection object. 1292 (i.e. by beginAutoCommitTransaction()). Otherwise, a new transaction will not be started, 1293 but true will be returned immediately. 1294 */ 1295 bool beginAutoCommitTransaction(KDbTransactionGuard* tg); 1296 1297 /*! Internal, for handling autocommited transactions: 1298 Commits transaction prevoiusly started with beginAutoCommitTransaction(). 1299 @return true on success or when no transactions are supported 1300 at all by the driver. 1301 1302 Special case when used database driver has only single transaction support 1303 (KDbDriver::SingleTransactions): if @a trans has been started outside KDbConnection object 1304 (i.e. not by beginAutoCommitTransaction()), the transaction will not be committed. 1305 */ 1306 bool commitAutoCommitTransaction(const KDbTransaction& trans); 1307 1308 /*! Internal, for handling autocommited transactions: 1309 Rolls back transaction prevoiusly started with beginAutoCommitTransaction(). 1310 @return true on success or when no transactions are supported 1311 at all by the driver. 1312 1313 Special case when used database driver has only single transaction support 1314 (KDbDriver::SingleTransactions): @a trans will not be rolled back 1315 if it has been started outside this KDbConnection object. 1316 */ 1317 bool rollbackAutoCommitTransaction(const KDbTransaction& trans); 1318 1319 /*! Helper: checks if connection is established; 1320 if not: error message is set up and false returned */ 1321 bool checkConnected(); 1322 1323 /*! Helper: checks both if connection is established and database any is used; 1324 if not: error message is set up and false returned */ 1325 bool checkIsDatabaseUsed(); 1326 1327 /*! Update a record. */ 1328 bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); 1329 /*! Insert a new record. */ 1330 bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false); 1331 /*! Delete an existing record. */ 1332 bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false); 1333 /*! Delete all existing records. */ 1334 bool deleteAllRecords(KDbQuerySchema* query); 1335 1336 /*! Called by KDbTableSchema -- signals destruction to KDbConnection object 1337 To avoid having deleted table object on its list. */ 1338 void removeMe(KDbTableSchema *ts); 1339 1340 // -- internal methods follow 1341 1342 /*! @internal 1343 @return true if the cursor @a cursor contains column @a column, 1344 else, sets appropriate error with a message and returns false. */ 1345 bool checkIfColumnExists(KDbCursor *cursor, int column); 1346 1347 /*! @internal used by insertRecord() methods. */ 1348 QSharedPointer<KDbSqlResult> insertRecordInternal(const QString &tableSchemaName, 1349 KDbFieldList *fields, 1350 const KDbEscapedString &sql); 1351 1352 /*! @internal used by querySingleRecord() methods. */ 1353 tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, 1354 KDbQuerySchema* query, const QList<QVariant>* params, 1355 QueryRecordOptions options); 1356 1357 /*! @internal used by querySingleString() methods. */ 1358 tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, 1359 KDbQuerySchema* query, const QList<QVariant>* params, 1360 int column, QueryRecordOptions options); 1361 1362 /*! @internal used by queryNumberString() methods. */ 1363 tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, 1364 KDbQuerySchema* query, const QList<QVariant>* params, 1365 int column, QueryRecordOptions options); 1366 1367 /*! @internal used by queryStringList() methods. */ 1368 bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list, 1369 KDbQuerySchema* query, const QList<QVariant>* params, 1370 int column, bool (*filterFunction)(const QString&)); 1371 1372 /*! @internal used by *Internal() methods. 1373 Executes query based on a raw SQL statement @a sql or @a query with optional @a params. 1374 Ownership of the returned object is passed to the caller.*/ 1375 KDbCursor* executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, 1376 const QList<QVariant>* params) Q_REQUIRED_RESULT; 1377 1378 /*! Loads extended schema information for table @a tableSchema, 1379 if present (see ExtendedTableSchemaInformation in Kexi Wiki). 1380 @return true on success */ 1381 bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema); 1382 1383 /*! Stores extended schema information for table @a tableSchema, 1384 (see ExtendedTableSchemaInformation in Kexi Wiki). 1385 The action is performed within the current transaction, 1386 so it's up to you to commit. 1387 Used, e.g. by createTable(), within its transaction. 1388 @return true on success */ 1389 bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema); 1390 1391 /*! @internal 1392 Stores main field's schema information for field @a field. 1393 Used in table altering code when information in kexi__fields has to be updated. 1394 @return true on success and false on failure. */ 1395 bool storeMainFieldSchema(KDbField *field); 1396 1397 //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1398 1399 /*! This is a part of alter table interface implementing lower-level operations 1400 used to perform table schema altering. Used by KDbAlterTableHandler. 1401 1402 Changes value of field property. 1403 @return true on success, false on failure, cancelled if the action has been cancelled. 1404 1405 Note for driver developers: implement this if the driver has to supprot the altering. */ drv_changeFieldProperty(KDbTableSchema * table,KDbField * field,const QString & propertyName,const QVariant & value)1406 virtual tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field, 1407 const QString& propertyName, const QVariant& value) { 1408 Q_UNUSED(table); Q_UNUSED(field); Q_UNUSED(propertyName); Q_UNUSED(value); 1409 return cancelled; 1410 } 1411 1412 //! Used by KDbCursor class 1413 void addCursor(KDbCursor* cursor); 1414 1415 //! Used by KDbCursor class 1416 void takeCursor(KDbCursor* cursor); 1417 1418 private: 1419 //! Internal, used by storeObjectData(KDbObject*) and storeNewObjectData(KDbObject* object). 1420 bool storeObjectDataInternal(KDbObject* object, bool newObject); 1421 1422 //! @internal 1423 //! @return identifier escaped by driver (if @a escapingType is KDb::DriverEscaping) 1424 //! or by the KDb's built-in escape routine. 1425 QString escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const; 1426 1427 KDbConnectionPrivate* d; //!< @internal d-pointer class. 1428 1429 Q_DISABLE_COPY(KDbConnection) 1430 friend class KDbConnectionPrivate; 1431 friend class KDbAlterTableHandler; 1432 friend class KDbConnectionProxy; 1433 friend class KDbCursor; 1434 friend class KDbDriver; 1435 friend class KDbProperties; //!< for setError() 1436 friend class KDbQuerySchema; 1437 friend class KDbQuerySchemaPrivate; 1438 friend class KDbTableSchemaChangeListenerPrivate; 1439 friend class KDbTableSchema; //!< for removeMe() 1440 }; 1441 1442 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::QueryRecordOptions) 1443 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::AlterTableNameOptions) 1444 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::CreateTableOptions) 1445 1446 #endif 1447