File indexing completed on 2024-04-14 14:53:27

0001 /* This file is part of the KDE project
0002    Copyright (C) 2003-2018 Jarosław Staniek <staniek@kde.org>
0003 
0004    This program is free software; you can redistribute it and/or
0005    modify it under the terms of the GNU Library General Public
0006    License as published by the Free Software Foundation; either
0007    version 2 of the License, or (at your option) any later version.
0008 
0009    This program is distributed in the hope that it will be useful,
0010    but WITHOUT ANY WARRANTY; without even the implied warranty of
0011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0012    Library General Public License for more details.
0013 
0014    You should have received a copy of the GNU Library General Public License
0015    along with this program; see the file COPYING.  If not, write to
0016    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
0017  * Boston, MA 02110-1301, USA.
0018 */
0019 
0020 #ifndef KDB_CONNECTION_H
0021 #define KDB_CONNECTION_H
0022 
0023 #include "KDbCursor.h"
0024 #include "KDbDriver.h"
0025 #include "KDbPreparedStatement.h"
0026 #include "KDbTableSchema.h"
0027 #include "KDbTransaction.h"
0028 #include "KDbTristate.h"
0029 
0030 class KDbConnectionData;
0031 class KDbConnectionOptions;
0032 class KDbConnectionPrivate;
0033 class KDbConnectionProxy;
0034 class KDbDriver;
0035 class KDbProperties;
0036 class KDbRecordData;
0037 class KDbRecordEditBuffer;
0038 class KDbServerVersionInfo;
0039 class KDbSqlResult;
0040 class KDbTableSchemaChangeListener;
0041 class KDbTableSchemaChangeListenerPrivate;
0042 class KDbTransactionGuard;
0043 class KDbVersionInfo;
0044 
0045 /*! @short Provides database connection, allowing queries and data modification.
0046 
0047  This class represents a database connection established within a data source.
0048  It supports data queries and modification by creating client-side database cursors.
0049  Database transactions are supported.
0050 */
0051 class KDB_EXPORT KDbConnection : public KDbResultable
0052 {
0053     Q_DECLARE_TR_FUNCTIONS(KDbConnection)
0054 public:
0055 
0056     /*! Opened connection is automatically disconnected and removed
0057      from driver's connections list.
0058      Note for driver developers: you should call destroy()
0059      from you KDbConnection's subclass destructor. */
0060     ~KDbConnection() override;
0061 
0062     /*! @return parameters that were used to create this connection. */
0063     KDbConnectionData data() const;
0064 
0065     /*! @return the driver used for this connection. */
0066     KDbDriver* driver() const;
0067 
0068     /*!
0069     @brief Connects to driver with given parameters.
0070     @return true if successful.
0071 
0072      Note: many database drivers may require connData.databaseName() to be specified
0073      because explicit database name is needed to perform connection (e.g. SQLite, PostgreSQL).
0074      MySQL does not require database name; KDbConnection::useDatabase() can be called later.
0075     */
0076     bool connect();
0077 
0078     /*! @return true, if connection is properly established. */
0079     bool isConnected() const;
0080 
0081     /*! @return true, both if connection is properly established
0082      and any database within this connection is properly used
0083      with useDatabase(). */
0084     bool isDatabaseUsed() const;
0085 
0086     /*! @return generic options for a single connection.
0087         The options are accessible using key/value pairs. This enables extensibility
0088         depending on driver's type and version. */
0089     KDbConnectionOptions *options();
0090 
0091     /*! Reimplemented, also clears sql string.
0092      @sa recentSqlString() */
0093     void clearResult();
0094 
0095     /*! @brief Disconnects from driver with given parameters.
0096 
0097      The database (if used) is closed, and any active transactions
0098      (if supported) are rolled back, so commit these before disconnecting,
0099      if you'd like to save your changes. */
0100     bool disconnect();
0101 
0102     /*! @return list of database names for opened connection.
0103      If @a also_system_db is true, the system database names are also returned. */
0104     QStringList databaseNames(bool also_system_db = false);
0105 
0106     /*! @return true if database @a dbName exists.
0107      If @a ignoreErrors is true, error flag of connection
0108       won't be modified for any errors (it will quietly return),
0109       else (ignoreErrors == false) we can check why the database does
0110       not exist using error(), errorNum() and/or errorMsg(). */
0111     bool databaseExists(const QString &dbName, bool ignoreErrors = true);
0112 
0113     /*! @brief Creates new database with name @a dbName, using this connection.
0114 
0115      If database with @a dbName already exists, or other error occurred,
0116      false is returned.
0117      For file-based drivers, @a dbName should be equal to the database
0118      filename (the same as specified for KDbConnectionData).
0119 
0120      See docs/kdb_issues.txt document, chapter "Table schema, query schema, etc. storage"
0121      for database schema documentation (detailed description of kexi__* 'system' tables).
0122 
0123      @see useDatabase() */
0124     bool createDatabase(const QString &dbName);
0125 
0126     /*!
0127     @brief Opens an existing database specified by @a dbName.
0128 
0129      If @a kexiCompatible is true (the default) initial checks will be performed
0130      to recognize database Kexi-specific format. Set @a kexiCompatible to false
0131      if you're using native database (one that have no Kexi System tables).
0132      For file-based drivers, @a dbName can be skipped, so the same as specified for
0133      KDbConnectionData is used.
0134      @return true on success, false on failure.
0135      If user has cancelled this action and @a cancelled is not 0, *cancelled is set to true. */
0136     bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr,
0137                      KDbMessageHandler* msgHandler = nullptr);
0138 
0139     /*!
0140     @brief Closes currently used database for this connection.
0141 
0142      Any active transactions (if supported) are rolled back,
0143      so commit these before closing, if you'd like to save your changes. */
0144     bool closeDatabase();
0145 
0146     /*! @brief Get the name of the current database
0147 
0148     @return name of currently used database for this connection or empty string
0149       if there is no used database */
0150     QString currentDatabase() const;
0151 
0152     /*! @brief Drops database with name @a dbName.
0153 
0154      if dbName is not specified, currently used database name is used
0155      (it is closed before dropping).
0156     */
0157     bool dropDatabase(const QString &dbName = QString());
0158 
0159     /*! @return names of all the @a objectType (see @a ObjectType in KDbGlobal.h)
0160     schemas stored in currently used database. KDb::AnyObjectType can be passed
0161     as @a objectType to get names of objects of any type.
0162     The list ordered is based on object identifiers.
0163     Only names that are identifiers (checked using KDb::isIdentifier()) are returned.
0164     If @a ok is not 0 then variable pointed by it will be set to the result.
0165     On error, the function returns empty list.
0166     @see kdbSystemTableNames() tableNames(int,bool*) */
0167     QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr);
0168 
0169     /*! @return names of all table schemas stored in currently
0170      used database. If @a alsoSystemTables is true,
0171      internal KDb system table names (kexi__*) are also returned.
0172      The list ordered is based on object identifiers.
0173      Only names that are identifiers (checked using KDb::isIdentifier()) are returned.
0174      If @a ok is not 0 then variable pointed by it will be set to the result.
0175      On error, the function returns empty list.
0176      @see kdbSystemTableNames() objectNames(int,bool*) */
0177     QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr);
0178 
0179     /*! @return true if table with name @a tableName exists in the database.
0180      @return @c false if it does not exist or @c cancelled if error occurred.
0181      The lookup is case insensitive.
0182      This method can be much faster than tableNames(). */
0183     tristate containsTable(const QString &tableName);
0184 
0185     /*! @return list of internal KDb system table names
0186      (kexi__*). This does not mean that these tables can be found
0187      in currently opened database. Just static list of table
0188      names is returned.
0189 
0190      The list contents may depend on KDb library version;
0191      opened database can contain fewer 'system' tables than in current
0192      KDb implementation, if the current one is newer than the one used
0193      to build the database.
0194      @todo this will depend on KDb lib version */
0195     static QStringList kdbSystemTableNames();
0196 
0197     /*! @return server version information for this connection.
0198      If database is not connected (i.e. isConnected() is false) null KDbServerVersionInfo is returned. */
0199     KDbServerVersionInfo serverVersion() const;
0200 
0201     /*! @return version information for this connection.
0202      If database is not used (i.e. isDatabaseUsed() is false) null KDbVersionInfo is returned.
0203      It can be compared to drivers' and KDb library version to maintain
0204      backward/upward compatiblility. */
0205     KDbVersionInfo databaseVersion() const;
0206 
0207     /*! @return KDbProperties object allowing to read and write global database properties
0208      for this connection. */
0209     KDbProperties databaseProperties() const;
0210 
0211     /*! @return ids of all table schema names stored in currently
0212      used database. These ids can be later used as argument for tableSchema().
0213      This is a shortcut for objectIds(KDb::TableObjectType).
0214      Internal KDb system tables (kexi__*) are not available here
0215      because these have no identifiers assigned (more formally: id=-1).
0216      If @a ok is not 0 then variable pointed by it will be set to the result.
0217 
0218      @note The fact that given id is on the returned list does not mean
0219      that tableSchema( id ) returns anything. The table definition can be broken,
0220      so you have to double check this.
0221 
0222      Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
0223      are returned.
0224      @see queryIds()
0225      */
0226     QList<int> tableIds(bool* ok = nullptr);
0227 
0228     /*! @return ids of all database query schemas stored in currently
0229      used database. These ids can be later used as argument for querySchema().
0230      This is a shortcut for objectIds(KDb::QueryObjectType).
0231      If @a ok is not 0 then variable pointed by it will be set to the result.
0232 
0233      @note The fact that given id is on the returned list does not mean
0234      that querySchema( id ) returns anything. The query definition can be broken,
0235      so you have to double check this.
0236 
0237      Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
0238      are returned.
0239      @see tableIds()
0240      */
0241     QList<int> queryIds(bool* ok = nullptr);
0242 
0243     /*! @return names of all schemas of object with @a objectType type
0244      that are stored in currently used database.
0245      If @a ok is not 0 then variable pointed by it will be set to the result.
0246 
0247      @note The fact that given id is on the returned list does not mean
0248      that the definition of the object is valid,
0249      so you have to double check this.
0250 
0251      Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier())
0252      are returned.
0253      @see tableIds() queryIds() */
0254     QList<int> objectIds(int objectType, bool* ok = nullptr);
0255 
0256     /**
0257      * @brief Starts a new database transaction
0258      *
0259      * @return KDbTransaction object. If transaction has been started successfully returned object
0260      * points to it, otherwise null transaction is returned.
0261      *
0262      * For drivers that allow single transaction per connection
0263      * (KDbDriver::features() && SingleTransactions) this method can be called once and that
0264      * transaction will be default one (setDefaultTransaction() will be called).
0265      * For drivers that allow multiple transactions per connection no default transaction is
0266      * set automatically in beginTransaction(). setDefaultTransaction() can be called by hand.
0267      *
0268      * @see setDefaultTransaction(), defaultTransaction().
0269      */
0270     KDbTransaction beginTransaction();
0271 
0272     /**
0273      * @brief Commits specified transaction for this connection
0274      *
0275      * If @a transaction is not active and default transaction (obtained from defaultTransaction())
0276      * exists, the default one will be committed. If neither the default one is not present returns
0277      * @c true if IgnoreInactive is set in @a options or @c false if IgnoreInactive is not set in
0278      * @a options.
0279      *
0280      * @return @c false on any error.
0281      *
0282      * On successful commit, @a transaction object will point to a null transaction.
0283      * After commiting a default transaction, there is no default transaction anymore.
0284      */
0285     bool commitTransaction(KDbTransaction transaction = KDbTransaction(),
0286                            KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions());
0287 
0288     /**
0289      * @brief Rolls back specified transaction for this connection
0290      *
0291      * If @a transaction is not active and default transaction (obtained from defaultTransaction())
0292      * exists, the default one will be rolled back. If neither default one is present @c true is
0293      * returned if IgnoreInactive is set for @a options or @c false if IgnoreInactive is not set in
0294      * @a options.
0295      *
0296      * @return @c false on any error.
0297      *
0298      * On successful rollback, @a transaction object will point to a null transaction.
0299      * After rollong back a default transaction, there is no default transaction anymore.
0300      */
0301     bool rollbackTransaction(KDbTransaction trans = KDbTransaction(),
0302                              KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions());
0303 
0304     /**
0305      * @brief Returns handle of default transaction for this connection
0306      *
0307      * Null transaction is returned if there is no such a transaction declared.
0308      * If transactions are supported any operation on database (e.g. inserts) that are started
0309      * without specifying a transaction context, are be performed in the context of this transaction.
0310      * Returned null transaction doesn't mean that there are no transactions started at all.
0311      * Default transaction can be defined automatically for certain drivers, see beginTransaction().
0312      *
0313      * @see KDbDriver::transactionsSupported()
0314      */
0315     KDbTransaction defaultTransaction() const;
0316 
0317     /**
0318      * @brief Sets default transaction
0319      *
0320      * Default transaction is used as a context for data modifications for this connection when no
0321      * specific transaction is provided.
0322      */
0323     void setDefaultTransaction(const KDbTransaction& trans);
0324 
0325     /**
0326      * @brief Returns set of handles of currently active transactions
0327      *
0328      * @note In multithreading environment some of these transactions can be already inactive after
0329      * calling this method. Use KDbTransaction::isActive() to check that. Inactive transaction
0330      * handle is useless and can be safely ignored.
0331      */
0332     QList<KDbTransaction> transactions();
0333 
0334     /*! @return true if "auto commit" option is on.
0335 
0336      When auto commit is on (the default on for any new KDbConnection object), every SQL statement
0337      that manipulates data in the database implicitly starts a new transaction. This transaction is
0338      automatically committed after successful statement execution or rolled back on error.
0339 
0340      For drivers that do not support transactions (see KDbDriver::features())
0341      this method shouldn't be called because it does nothing ans always returns false.
0342 
0343      No internal KDb object should changes this option, although auto commit's
0344      behavior depends on database engine's specifics. Engines that support only single
0345      transaction per connection (see KDbDriver::SingleTransactions),
0346      use this single connection for autocommiting, so if there is already transaction
0347      started by the KDb user program (with beginTransaction()), this transaction
0348      is committed before any statement that manipulates data. In this situation
0349      default transaction is also affected (see defaultTransaction()).
0350 
0351      Only for drivers that support nested transactions (KDbDriver::NestedTransactions),
0352      autocommiting works independently from previously started transaction,
0353 
0354      For other drivers set this option off if you need use transaction
0355      for grouping more statements together.
0356 
0357      NOTE: nested transactions are not yet implemented in KDb API.
0358     */
0359     bool autoCommit() const;
0360 
0361     /*! Changes auto commit option. This does not affect currently started transactions.
0362      This option can be changed even when connection is not established.
0363      @see autoCommit() */
0364     bool setAutoCommit(bool on);
0365 
0366     /*! Connection-specific string escaping. Default implementation uses driver's escaping.
0367      Use KDbEscapedString::isValid() to check if escaping has been performed successfully.
0368      Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true,
0369      not just isEmpty().
0370     */
0371     virtual KDbEscapedString escapeString(const QString& str) const;
0372 
0373     /*! Prepares SELECT query described by a raw statement @a sql.
0374      @return opened cursor created for results of this query
0375      or @c nullptr if there was any error. Ownership of the returned object is passed
0376      to the caller.
0377      KDbCursor can have optionally applied @a options (one of more selected from KDbCursor::Options).
0378      Preparation means that returned cursor is created but not opened.
0379      Open this when you would like to do it with KDbCursor::open().
0380 
0381      Note for driver developers: you should initialize cursor engine-specific
0382      resources and return KDbCursor subclass' object
0383      (passing @a sql and @a options to its constructor).
0384     */
0385     virtual KDbCursor* prepareQuery(const KDbEscapedString& sql,
0386                                     KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0;
0387 
0388     /*! @overload
0389      Prepares query described by @a query schema. @a params are values of parameters that
0390      will be inserted into places marked with [] before execution of the query.
0391 
0392      Note for driver developers: you should initialize cursor engine-specific
0393      resources and return KDbCursor subclass' object
0394      (passing @a query and @a options to it's constructor).
0395      Kexi SQL and driver-specific escaping is performed on table names.
0396     */
0397     Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, const QList<QVariant> &params,
0398                                               KDbCursor::Options options = KDbCursor::Option::None);
0399 
0400     /*! @overload
0401      Prepares query described by @a query schema without parameters.
0402     */
0403     virtual KDbCursor* prepareQuery(KDbQuerySchema* query,
0404                                     KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0;
0405 
0406     /*! @overload
0407      Statement is build from data provided by @a table schema, it is like "select * from
0408      table_name".*/
0409     Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbTableSchema *table,
0410                                               KDbCursor::Options options = KDbCursor::Option::None);
0411 
0412     /*! Executes SELECT query described by a raw SQL statement @a sql.
0413      @return opened cursor created for results of this query
0414      or 0 if there was any error on the cursor creation or opening.
0415      Ownership of the returned object is passed to the caller.
0416      KDbCursor can have optionally applied @a options.
0417      Identifiers in @a sql that are the same as keywords
0418      in KDbSQL dialect or the backend's SQL have to be escaped.
0419      */
0420     Q_REQUIRED_RESULT KDbCursor *executeQuery(const KDbEscapedString &sql,
0421                                               KDbCursor::Options options = KDbCursor::Option::None);
0422 
0423     /*! @overload executeQuery(const KDbEscapedString&, int)
0424      @a params are values of parameters that
0425      will be inserted into places marked with [] before execution of the query.
0426 
0427      Statement is build from data provided by @a query schema.
0428      Kexi SQL and driver-specific escaping is performed on table names. */
0429     Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query, const QList<QVariant> &params,
0430                                               KDbCursor::Options options = KDbCursor::Option::None);
0431 
0432     /*! @overload */
0433     Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query,
0434                                               KDbCursor::Options options = KDbCursor::Option::None);
0435 
0436     /*! @overload
0437      Executes query described by @a query schema without parameters.
0438      Statement is build from data provided by @a table schema,
0439      it is like "select * from table_name".*/
0440     Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbTableSchema *table,
0441                                               KDbCursor::Options options = KDbCursor::Option::None);
0442 
0443     /*! Deletes cursor @a cursor previously created by functions like executeQuery()
0444      for this connection.
0445      There is an attempt to close the cursor with KDbCursor::close() if it was opened.
0446      Anyway, at last cursor is deleted.
0447      @return true if cursor is properly closed before deletion. */
0448     bool deleteCursor(KDbCursor *cursor);
0449 
0450     /*! @return schema of a table pointed by @a tableId, retrieved from currently
0451      used database. The schema is cached inside connection,
0452      so retrieval is performed only once, on demand. */
0453     KDbTableSchema* tableSchema(int tableId);
0454 
0455     /*! @return schema of a table pointed by @a tableName, retrieved from currently
0456      used database. KDb system table schema can be also retrieved.
0457      @see tableSchema( int tableId ) */
0458     KDbTableSchema* tableSchema(const QString& tableName);
0459 
0460     /*! @return schema of a query pointed by @a queryId, retrieved from currently
0461      used database. The schema is cached inside connection,
0462      so retrieval is performed only once, on demand. */
0463     KDbQuerySchema* querySchema(int queryId);
0464 
0465     /*! @return schema of a query pointed by @a queryName, retrieved from currently
0466      used database.  @see querySchema( int queryId ) */
0467     KDbQuerySchema* querySchema(const QString& queryName);
0468 
0469     /*! Sets @a queryName query obsolete by moving it out of the query sets, so it will not be
0470      accessible by querySchema( const QString& queryName ). The existing query object is not
0471      destroyed, to avoid problems when it's referenced. In this case,
0472      a new query schema will be retrieved directly from the backend.
0473 
0474      For now it's used in KexiQueryDesignerGuiEditor::storeLayout().
0475      This solves the problem when user has changed a query schema but already form still uses
0476      previously instantiated query schema.
0477      @return true if there is such query. Otherwise the method does nothing. */
0478     bool setQuerySchemaObsolete(const QString& queryName);
0479 
0480     //! Options for querying records
0481     //! @since 3.1
0482     enum class QueryRecordOption {
0483         AddLimitTo1 = 1, //!< Adds a "LIMIT 1" clause to the query for optimization purposes
0484                          //!< (it should not include one already)
0485         Default = AddLimitTo1
0486     };
0487     Q_DECLARE_FLAGS(QueryRecordOptions, QueryRecordOption)
0488 
0489     /*! Executes query for a raw statement @a sql and stores first record's data inside @a data.
0490      This is a convenient method when we need only first record from query result,
0491      or when we know that query result has only one record.
0492      If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
0493      Caller should make sure it is not there in the @a sql already.
0494      @return @c true if query was successfully executed and first record has been found,
0495      @c false on data retrieving failure, and @c cancelled if there's no single record available. */
0496     tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data,
0497                                QueryRecordOptions options = QueryRecordOption::Default);
0498 
0499     /*! @overload
0500      Uses a KDbQuerySchema object. */
0501     tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data,
0502                                QueryRecordOptions options = QueryRecordOption::Default);
0503 
0504     /*! @overload
0505      Accepts @a params as parameters that will be inserted into places marked with "[]" before
0506      query execution. */
0507     tristate querySingleRecord(KDbQuerySchema *query, KDbRecordData *data,
0508                                const QList<QVariant> &params,
0509                                QueryRecordOptions options = QueryRecordOption::Default);
0510 
0511     /*! Executes query for a raw statement @a sql and stores first record's field's
0512      (number @a column) string value inside @a value.
0513      For efficiency it's recommended that a query defined by @a sql
0514      should have just one field (SELECT one_field FROM ....).
0515      If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
0516      Caller should make sure it is not there in the @a sql already.
0517      @return @c true if query was successfully executed and first record has been found,
0518      @c false on data retrieving failure, and @c cancelled if there's no single record available.
0519      @see queryStringList() */
0520     tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0,
0521                                QueryRecordOptions options = QueryRecordOption::Default);
0522 
0523     /*! @overload
0524      Uses a KDbQuerySchema object. */
0525     tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0,
0526                                QueryRecordOptions options = QueryRecordOption::Default);
0527 
0528     /*! @overload
0529      Accepts @a params as parameters that will be inserted into places marked with [] before
0530      query execution. */
0531     tristate querySingleString(KDbQuerySchema* query, QString* value,
0532                                const QList<QVariant>& params, int column = 0,
0533                                QueryRecordOptions options = QueryRecordOption::Default);
0534 
0535     /*! Convenience function: executes query for a raw SQL statement @a sql and stores first
0536      record's field's (number @a column) value inside @a number. @see querySingleString().
0537      If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default).
0538      Caller should make sure it is not there in the @a sql already.
0539      @return true if query was successfully executed and first record has been found,
0540      false on data retrieving failure, and cancelled if there's no single record available. */
0541     tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0,
0542                                QueryRecordOptions options = QueryRecordOption::Default);
0543 
0544     /*! @overload
0545      Uses a KDbQuerySchema object. */
0546      tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0,
0547                                 QueryRecordOptions options = QueryRecordOption::Default);
0548 
0549     /*! @overload
0550      Accepts @a params as parameters that will be inserted into places marked with "[]" before
0551      query execution. */
0552     tristate querySingleNumber(KDbQuerySchema* query, int* number,
0553                                const QList<QVariant>& params, int column = 0,
0554                                QueryRecordOptions options = QueryRecordOption::Default);
0555 
0556     /*! Executes query for a raw SQL statement @a sql and stores Nth field's string value
0557      of every record inside @a list, where N is equal to @a column. The list is initially cleared.
0558      For efficiency it's recommended that a query defined by @a sql
0559      should have just one field (SELECT one_field FROM ....).
0560      @return true if all values were fetched successfuly,
0561      false on data retrieving failure. Returning empty list can be still a valid result.
0562      On errors, the list is not cleared, it may contain a few retrieved values. */
0563     bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0);
0564 
0565     /*! @overload
0566      Uses a QuerySchema object. */
0567     bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0);
0568 
0569     /*! @overload
0570      Accepts @a params as parameters that will be inserted into places marked with "[]" before
0571      query execution. */
0572     bool queryStringList(KDbQuerySchema* query, QStringList* list,
0573                          const QList<QVariant>& params, int column = 0);
0574 
0575     /*! @return @c true if there is at least one record has been returned by executing query
0576      for a raw SQL statement @a sql or @c false if no such record exists.
0577      If @a options includes AddLimitTo1 value, the query is optimized into "SELECT 1 FROM (sql) LIMIT 1"
0578      (this is the default). Caller should make sure "SELECT 1" and "LIMIT 1" is not there in the
0579      @a sql already.
0580      This method does not fetch any records. On error returns @c cancelled. */
0581     tristate resultExists(const KDbEscapedString &sql,
0582                           QueryRecordOptions options = QueryRecordOption::Default);
0583 
0584     /*! @return true if there is at least one record in @a table. */
0585     tristate isEmpty(KDbTableSchema* table);
0586 
0587     /**
0588      * @brief Return recently used SQL string
0589      *
0590      * If there was a successful query execution it is equal to result().sql(),
0591      * otherwise it is equal to result().errorSql().
0592      */
0593     virtual KDbEscapedString recentSqlString() const;
0594 
0595     //PROTOTYPE:
0596 #define A , const QVariant&
0597 #define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema* tableSchema args)
0598 #define H_INS_REC_ALL \
0599     H_INS_REC(A); \
0600     H_INS_REC(A A); \
0601     H_INS_REC(A A A); \
0602     H_INS_REC(A A A A); \
0603     H_INS_REC(A A A A A); \
0604     H_INS_REC(A A A A A A); \
0605     H_INS_REC(A A A A A A A); \
0606     H_INS_REC(A A A A A A A A)
0607     H_INS_REC_ALL;
0608 
0609 #undef H_INS_REC
0610 #define H_INS_REC(args) QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList* fields args)
0611 
0612     H_INS_REC_ALL;
0613 #undef H_INS_REC_ALL
0614 #undef H_INS_REC
0615 #undef A
0616 
0617     QSharedPointer<KDbSqlResult> insertRecord(KDbTableSchema *tableSchema,
0618                                               const QList<QVariant> &values);
0619 
0620     QSharedPointer<KDbSqlResult> insertRecord(KDbFieldList *fields, const QList<QVariant> &values);
0621 
0622     //! Options for creating table
0623     //! @since 3.1
0624     enum class CreateTableOption {
0625         Default = 0,
0626         DropDestination = 1 //!< Drop destination table if exists
0627     };
0628     Q_DECLARE_FLAGS(CreateTableOptions, CreateTableOption)
0629 
0630     /**
0631      * @brief Creates a new table
0632      *
0633      * Creates a new table defined by @a tableSchema. @c true is returned on success. In this case
0634      * @a tableSchema object is added to KDbConnection's structures and becomes owned the
0635      * KDbConnection object, so should not be destroyed by hand.
0636      *
0637      * If @a options include the DropDestination value and table schema with the same name as @a
0638      * tableSchema exists, it is dropped and the original identifier of the dropped schem is
0639      * assigned to the @a tableSchema object.
0640      *
0641      * If @a options do not include the DropDestination value and table schema with the same name
0642      * as @a tableSchema exists, @c false is returned.
0643      *
0644      * Table and column definitions are added to "Kexi system" tables.
0645      *
0646      * Prior to dropping the method checks if the table for the schema is in use, and if the new
0647      * schema defines at least one column.
0648      *
0649      * Note that on error:
0650      * - @a tableSchema is not inserted into KDbConnection's structures, so caller is still owner
0651      *   of the object,
0652      * - existing table schema object is not destroyed (e.g. it is still available for
0653      *   KDbConnection::tableSchema(const QString&), even if the table was physically dropped.
0654      *
0655      * @return true on success.
0656      */
0657     bool createTable(KDbTableSchema *tableSchema,
0658                      CreateTableOptions options = CreateTableOption::Default);
0659 
0660     /*! Creates a copy of table schema defined by @a tableSchema with data.
0661      Name, caption and description will be copied from @a newData.
0662      @return a table schema object. It is inserted into the KDbConnection structures
0663      and is owned by the KDbConnection object. The created table schema object should not
0664      be destroyed by hand afterwards.
0665      0 is returned on failure. Table with destination name must not exist.
0666      @see createTable() */
0667     KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData);
0668 
0669     /*! It is a convenience function, does exactly the same as
0670      KDbTableSchema *copyTable(const KDbTableSchema&, const KDbObject&). */
0671     KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData);
0672 
0673     /*! Drops a table defined by @a tableSchema (both table object as well as physically).
0674      If true is returned, schema information @a tableSchema is destoyed
0675      (because it's owned), so don't keep this anymore!
0676      No error is raised if the table does not exist physically
0677      - its schema is removed even in this case.
0678 
0679      Removes the table and column definitions in kexi__* "system schema" tables.
0680      First checks that the table is not a system table.
0681 
0682      @todo Check that a database is currently in use? (c.f. createTable)
0683      @todo Update any structure (e.g. query) that depends on this table */
0684     tristate dropTable(KDbTableSchema* tableSchema);
0685 
0686     /*! @overload
0687      * It is a convenience function.
0688      */
0689     tristate dropTable(const QString& tableName);
0690 
0691     /*! Alters @a tableSchema using @a newTableSchema in memory and on the db backend.
0692      @return true on success, cancelled if altering was cancelled. */
0693 //! @todo (js): implement real altering
0694 //! @todo (js): update any structure (e.g. query) that depend on this table!
0695     tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema);
0696 
0697     //! Options for altering table name
0698     //! @since 3.1
0699     enum class AlterTableNameOption {
0700         Default = 0,
0701         DropDestination = 1 //!< Drop destination table if exists
0702     };
0703     Q_DECLARE_FLAGS(AlterTableNameOptions, AlterTableNameOption)
0704 
0705     /**
0706      * @brief Alters name of table
0707      *
0708      * Alters name of table described by @a tableSchema to @a newName.
0709      * If @a options include the DropDestination value and table having name @a newName already
0710      * exists, it is physically dropped, removed from connection's list of tables  and replaced
0711      * by @a tableSchema. In this case identifier of @a tableSchema is set to the dropped table's
0712      * identifier. This can be useful if @a tableSchema was created with a temporary name and
0713      * identifier. It is for example used in KDbAlterTableHandler.
0714      *
0715      * If @a options do not include the DropDestination value (the default) and table having name
0716      * @a newName already exists, @c false is returned and @c ERR_OBJECT_EXISTS error is set in
0717      * the connection object.
0718      *
0719      * Table name in the schema of @a tableSchema is updated on successful altering.
0720      * @return true on success.
0721      */
0722     bool alterTableName(KDbTableSchema* tableSchema, const QString& newName,
0723                         AlterTableNameOptions options = AlterTableNameOption::Default);
0724 
0725     /*! Drops a query defined by @a querySchema.
0726      If true is returned, schema information @a querySchema is destoyed
0727      (because it's owned), so don't keep this anymore!
0728     */
0729     bool dropQuery(KDbQuerySchema* querySchema);
0730 
0731     /*! It is a convenience function, does exactly the same as
0732      bool dropQuery( KDbQuerySchema* querySchema ) */
0733     bool dropQuery(const QString& queryName);
0734 
0735     /*! Removes information about object with @a objId
0736      from internal "kexi__object" and "kexi__objectdata" tables.
0737      @return true on success. */
0738     bool removeObject(int objId);
0739 
0740     /*! @return first field from @a fieldlist that has system name,
0741      @c nullptr if there are no such field.
0742      For checking, KDbDriver::isSystemFieldName() is used, so this check can
0743      be driver-dependent. */
0744     KDbField* findSystemFieldName(const KDbFieldList& fieldlist);
0745 
0746     /*! @return name of any (e.g. first found) database for this connection.
0747      This method does not close or open this connection. The method can be used
0748      (it is also internally used, e.g. for database dropping) when we need
0749      a database name before we can connect and execute any SQL statement
0750      (e.g. DROP DATABASE).
0751 
0752      The method can return nul lstring, but in this situation no automatic (implicit)
0753      connections could be made, what is useful by e.g. dropDatabase().
0754 
0755      Note for driver developers: return here a name of database which you are sure
0756      is existing.
0757      Default implementation returns:
0758      - value that previously had been set using setAvailableDatabaseName() for
0759        this connection, if it is not empty
0760      - else (2nd priority): value of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME
0761      if it is not empty.
0762 
0763      See description of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME member.
0764      You may want to reimplement this method only when you need to depend on
0765      this connection specifics
0766      (e.g. you need to check something remotely).
0767     */
0768     virtual QString anyAvailableDatabaseName();
0769 
0770     /*! Sets @a dbName as name of a database that can be accessible.
0771      This is option that e.g. application that make use of KDb library can set
0772      to tune connection's behavior when it needs to temporary connect to any database
0773      in the server to do some work.
0774      You can pass empty dbName - then anyAvailableDatabaseName() will try return
0775      KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value
0776      instead of the one previously set with setAvailableDatabaseName().
0777 
0778      @see anyAvailableDatabaseName()
0779     */
0780     void setAvailableDatabaseName(const QString& dbName);
0781 
0782     /*! Because some engines need to have opened any database before
0783      executing administrative SQL statements like "create database" or "drop database",
0784      this method is used to use appropriate, existing database for this connection.
0785      For file-based db drivers this always return true and does not set @a name
0786      to any value. For other db drivers: this sets @a name to db name computed
0787      using anyAvailableDatabaseName(), and if the name computed is empty, false
0788      is returned; if it is not empty, useDatabase() is called.
0789      False is returned also when useDatabase() fails.
0790      You can call this method from your application's level if you really want to perform
0791      tasks that require any used database. In such a case don't forget
0792      to closeDatabase() if returned @a name is not empty.
0793 
0794      Note: This method has nothing to do with creating or using temporary databases
0795      in such meaning that these database are not persistent
0796     */
0797     bool useTemporaryDatabaseIfNeeded(QString* name);
0798 
0799     /**
0800      * Prepares execution of a new native (raw, backend-specific) SQL query.
0801      *
0802      * The query is described by a raw statement @a sql which should be is valid and properly
0803      * escaped. Access to results can be obtained using
0804      * the returned KDbSqlResult object. The object is guarded with a shared pointer to facilitate
0805      * transfer of ownership and memory management. A null pointer is returned if preparation of
0806      * the query fails. Use KDbConnection::result() immediately after calling prepareSql() to
0807      * obtain detailed result information about the preparation.
0808      *
0809      * The returned object should be deleted before the database connection is closed.
0810      * Connection object does not deletes the KDbSqlResult objects. It is also possible and
0811      * recommended that caller deletes the KDbSqlResult object as soon as the result is not needed.
0812      *
0813      * The returned object can be ignored if the query is not supposed to return records (e.g.
0814      * manipulates data through INSERT, UPDATE, DELETE, ...) or the caller is not interested in the
0815      * records. Thanks to the use of the shared pointer the object will be immediately deleted and
0816      * execution will be finalized prior to that. However to execute queries that return no
0817      * results, executeSql() is a better choice because of performance and easier reporting to
0818      * results.
0819      *
0820      * @note Only use this method if a non-portable raw query is required.
0821      *       In other cases use prepareQuery() or executeQuery() and the KDbCursor object.
0822      */
0823     Q_REQUIRED_RESULT QSharedPointer<KDbSqlResult> prepareSql(const KDbEscapedString& sql);
0824 
0825     /**
0826      * Executes a new native (raw, backend-specific) SQL query
0827      *
0828      * The query is described by a raw statement @a sql which should be is valid and properly
0829      * escaped. This method is a convenience version of prepareSql() that immediately starts and
0830      * finalizes execution of a raw query in one step and provides a result. Use it for queries
0831      * that do not return records, i.e. for queries that manipulate data (INSERT, UPDATE, DELETE,
0832      * ...) or if the caller is not interested in the returned records.
0833      *
0834      * @note Only use this method if a non-portable raw query is required.
0835      *       In other cases use prepareQuery() or executeQuery() and the KDbCursor object.
0836      */
0837     bool executeSql(const KDbEscapedString& sql);
0838 
0839     /*! Stores object (id, name, caption, description)
0840     described by @a object on the backend. It is expected that entry on the
0841     backend already exists, so it's updated. Changes to identifier attribute are not allowed.
0842     @return true on success. */
0843     bool storeObjectData(KDbObject* object);
0844 
0845     /*! Stores new entry for object (id, name, caption, description)
0846     described by @a object on the backend. If object.id() was less than 0,
0847     new, unique object identifier is obtained and assigned to @a object (see KDbObject::id()).
0848     @return true on success. */
0849     bool storeNewObjectData(KDbObject* object);
0850 
0851     /*! Finds object data for object of type @a type and identifier @a id.
0852      Added for convenience.
0853      If @a type is KDb::AnyObjectType, object type is ignored during the find.
0854      @see setupObjectData(const KDbRecordData*, KDbObject*).
0855      @return true on success, false on failure and cancelled when such object couldn't be found.
0856      @since 3.1
0857     */
0858     tristate loadObjectData(int type, int id, KDbObject* object);
0859 
0860     /*! Finds object data for object of type @a type and name @a name.
0861      If the object is found, resulted schema is stored in @a object and true is returned,
0862      otherwise false is returned. */
0863     tristate loadObjectData(int type, const QString& name, KDbObject* object);
0864 
0865     /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID
0866      and puts it to @a dataString. The can be block indexed with optional @a dataID.
0867      @return true on success, false on failure and cancelled when there is no such data block
0868      @see storeDataBlock(). */
0869     tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString());
0870 
0871     /*! Stores (potentially large) data block @a dataString (e.g. xml form's representation),
0872      referenced by objectID. Block will be stored in "kexi__objectdata" table and
0873      an optional @a dataID identifier.
0874      If there is already such record in the table, it's simply overwritten.
0875      @return true on success
0876      @see loadDataBlock() removeDataBlock() copyDataBlock(). */
0877     bool storeDataBlock(int objectID, const QString &dataString,
0878                         const QString& dataID = QString());
0879 
0880     /*! Copies (potentially large) data, e.g. form's XML representation,
0881      referenced by @a sourceObjectID pointed by optional @a dataID.
0882      @return true on success. Does not fail if blocks do not exist.
0883      Prior to copying, existing data blocks are removed even if there are no new blocks to copy.
0884      Copied data blocks will have @a destObjectID object identifier assigned.
0885      Note that if @a dataID is not specified, all data blocks found for the @a sourceObjectID
0886      will be copied.
0887      @see loadDataBlock() storeDataBlock() removeDataBlock(). */
0888     bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString());
0889 
0890     /*! Removes (potentially large) string data (e.g. xml form's representation),
0891      referenced by @a objectID, and pointed by optional @a dataID.
0892      @return true on success. Does not fail if the block does not exist.
0893      Note that if @a dataID is not specified, all data blocks for the @a objectID will be removed.
0894      @see loadDataBlock() storeDataBlock() copyDataBlock(). */
0895     bool removeDataBlock(int objectID, const QString& dataID = QString());
0896 
0897     /*! Prepare an SQL statement and return a @a KDbPreparedStatement instance. */
0898     KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type,
0899         KDbFieldList* fields, const QStringList& whereFieldNames = QStringList());
0900 
0901     bool isInternalTableSchema(const QString& tableName);
0902 
0903     /**
0904      * @brief Returns number of records returned by given SQL statement
0905      *
0906      * @return number of records that can be retrieved after executing @a sql statement within
0907      * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not
0908      * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed.
0909      * -1 is returned if any error occurred or if @a conn is @c nullptr.
0910      *
0911      * @since 3.1
0912      */
0913     //! @todo perhaps use quint64 here?
0914     int recordCount(const KDbEscapedString& sql);
0915 
0916     /**
0917      * @brief Returns number of records that contains given table
0918      *
0919      * @return number of records that can be retrieved from @a tableSchema.
0920      * To obtain the result the table must be created or retrieved using a KDbConnection object,
0921      * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)"
0922      * SQL aggregation is used at the backed.
0923      * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr.
0924      *
0925      * @since 3.1
0926      */
0927     //! @todo perhaps use quint64 here?
0928     //! @todo does not work with non-SQL data sources
0929     int recordCount(const KDbTableSchema& tableSchema);
0930 
0931     /**
0932      * @overload
0933      *
0934      * Operates on a query schema. @a params are optional values of parameters that will be inserted
0935      * into [] placeholders before execution of query that counts the records.
0936      * To obtain the result the query must be created or retrieved using a KDbConnection object,
0937      * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)"
0938      * SQL aggregation is used at the backed.
0939      * -1 is returned if error occurred or if querySchema->connection() is @c nullptr.
0940      *
0941      * @since 3.1
0942      */
0943     //! @todo perhaps use quint64 here?
0944     int recordCount(KDbQuerySchema* querySchema,
0945                                const QList<QVariant>& params = QList<QVariant>());
0946 
0947     /**
0948      * @overload
0949      *
0950      * Operates on a table or query schema. @a params is a list of optional parameters that
0951      * will be inserted into [] placeholders before execution of query that counts the records.
0952      *
0953      * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned.
0954      *
0955      * @since 3.1
0956      */
0957     //! @todo perhaps use quint64 here?
0958     int recordCount(KDbTableOrQuerySchema* tableOrQuery,
0959                                const QList<QVariant>& params = QList<QVariant>());
0960 
0961     //! Identifier escaping function in the associated KDbDriver.
0962     /*! Calls the identifier escaping function in this connection to
0963      escape table and column names.  This should be used when explicitly
0964      constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)).
0965      It should not be used for other functions (e.g. don't do
0966      useDatabase(escapeIdentifier(database))), because the identifier will
0967      be escaped when the called function generates, for example, "USE " +
0968      escapeIdentifier(database).
0969 
0970      For efficiency, KDb "system" tables (prefixed with kexi__)
0971      and columns therein are not escaped - we assume these are valid identifiers for all drivers.
0972 
0973      Use KDbEscapedString::isValid() to check if escaping has been performed successfully.
0974      Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true,
0975      not just isEmpty().
0976     */
0977     virtual QString escapeIdentifier(const QString& id) const;
0978 
0979 protected:
0980     /*! Used by KDbDriver */
0981     KDbConnection(KDbDriver *driver, const KDbConnectionData& connData,
0982                   const KDbConnectionOptions &options);
0983 
0984     /*! Method to be called form KDbConnection's subclass destructor.
0985      @see ~KDbConnection() */
0986     void destroy();
0987 
0988     /*! For implementation: connects to database.
0989       @return true on success. */
0990     virtual bool drv_connect() = 0;
0991 
0992     /*! For implementation: disconnects database
0993       @return true on success. */
0994     virtual bool drv_disconnect() = 0;
0995 
0996     /*! For implementation: Sets @a version to real server's version.
0997      Depending on backend type this method is called after
0998      (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is true)
0999      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. */
1408     virtual tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field,
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 
1420 private:
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 
1444 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::QueryRecordOptions)
1445 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::AlterTableNameOptions)
1446 Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::CreateTableOptions)
1447 
1448 #endif