diff --git a/autotests/KDbTestUtils.h b/autotests/KDbTestUtils.h index 9094f177..4c3bf2fc 100644 --- a/autotests/KDbTestUtils.h +++ b/autotests/KDbTestUtils.h @@ -1,213 +1,213 @@ /* This file is part of the KDE project Copyright (C) 2015-2019 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_TESTUTILS_H #define KDB_TESTUTILS_H #include "kdbtestutils_export.h" #include #include #include #include #include #include class KDbNativeStatementBuilder; Q_DECLARE_METATYPE(KDbField::TypeGroup) Q_DECLARE_METATYPE(KDbField::Type) Q_DECLARE_METATYPE(KDb::Signedness) Q_DECLARE_METATYPE(QList) Q_DECLARE_METATYPE(KDb::BLOBEscapingType) //! @internal for KDB_VERIFY template const T* KDB_POINTER_WRAPPER(const T &t) { return &t; } //! @internal for KDB_VERIFY template const T* KDB_POINTER_WRAPPER(const T *t) { return t; } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(T *t) { return t; } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(const QPointer &t) { return t.data(); } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(const QScopedPointer &t) { return t.data(); } namespace QTest { KDBTESTUTILS_EXPORT bool qCompare(const KDbEscapedString &val1, const KDbEscapedString &val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const KDbEscapedString &val1, const char *val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const char *val1, const KDbEscapedString &val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const KDbEscapedString &val1, const QString &val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const QString &val1, const KDbEscapedString &val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const QStringList &val1, const QStringList &val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const QByteArray &val1, const char *val2, const char *actual, const char *expected, const char *file, int line); KDBTESTUTILS_EXPORT bool qCompare(const QString &val1, const char *val2, const char *actual, const char *expected, const char *file, int line); } //! Calls @a call and verifies status of @a resultable //! On error displays the status on debug and does the same as QVERIFY with @a errorMessage #define KDB_VERIFY(resultable, call, errorMessage) \ do { \ bool KDB_VERIFY_ok = (call); \ const KDbResultable *KDB_VERIFY_resultablePtr = KDB_POINTER_WRAPPER(resultable); \ if (KDB_VERIFY_resultablePtr->result().isError()) { \ qDebug() << KDB_VERIFY_resultablePtr->result(); \ } \ if (!QTest::qVerify(KDB_VERIFY_ok && !KDB_VERIFY_resultablePtr->result().isError(), # call, (errorMessage), __FILE__, __LINE__)) {\ return; \ } \ } \ while (false) //! Calls @a call and verifies status of @a resultable //! On error displays the status on debug and does the same as QVERIFY with @a errorMessage #define KDB_EXPECT_FAIL(resultable, call, expectedErrorCode, errorMessage) \ do { \ bool KDB_VERIFY_ok = (call); \ const KDbResultable *KDB_VERIFY_resultablePtr = KDB_POINTER_WRAPPER(resultable); \ if (KDB_VERIFY_resultablePtr->result().isError()) { \ qDebug() << KDB_VERIFY_resultablePtr->result(); \ } \ QVERIFY(KDB_VERIFY_resultablePtr->result().isError()); \ if (!QTest::qVerify(!KDB_VERIFY_ok, # call, (errorMessage), __FILE__, __LINE__)) {\ return; \ } \ if (!QTest::qCompare(KDB_VERIFY_resultablePtr->result().code(), expectedErrorCode, # call, # expectedErrorCode, __FILE__, __LINE__)) {\ return; \ } \ } \ while (false) //! Declares method @a name that returns false on test failure, it can be called as utility function. //! Also declared internal method name ## Internal which performs the actual test. //! This way users of this method can call QVERIFY(utils.()); #define KDBTEST_METHOD_DECL(name, argsDecl, args) \ public: \ - bool name argsDecl Q_REQUIRED_RESULT { name ## Internal args ; return !QTest::currentTestFailed(); } \ + Q_REQUIRED_RESULT bool name argsDecl { name ## Internal args ; return !QTest::currentTestFailed(); } \ private Q_SLOTS: \ void name ## Internal argsDecl //! Test utilities that provide basic database features class KDBTESTUTILS_EXPORT KDbTestUtils : public QObject { Q_OBJECT public: KDbTestUtils(); ~KDbTestUtils(); KDbDriverManager manager; QPointer driver; /** * Returns associated connection */ KDbConnection* connection(); /** * Returns builder for generating KDb SQL statements */ KDbNativeStatementBuilder* kdbBuilder(); /** * Returns builder for generating driver-native SQL statements */ KDbNativeStatementBuilder* driverBuilder(); KDBTEST_METHOD_DECL(testDriverManager, (), ()); KDBTEST_METHOD_DECL(testSqliteDriver, (), ()); //! Connects to a database //! @since 3.2 KDBTEST_METHOD_DECL(testConnect, (const KDbConnectionData &cdata, const KDbConnectionOptions &options = KDbConnectionOptions()), (cdata, options)); KDBTEST_METHOD_DECL(testUse, (), ()); //! Convenience method that performs testConnect and testUse in one go //! @since 3.2 KDBTEST_METHOD_DECL(testConnectAndUse, (const KDbConnectionData &cdata, const KDbConnectionOptions &options = KDbConnectionOptions()), (cdata, options)); //! Overload of testConnectAndUse for file-based databases //! @since 3.2 KDBTEST_METHOD_DECL(testConnectAndUse, (const QString &path, const KDbConnectionOptions &options = KDbConnectionOptions()), (path, options)); //! Creates database with name @a dbName //! Does not use the database. //! @todo don't hardcode SQLite here //! @note dbName should not include ".kexi" extension or path KDBTEST_METHOD_DECL(testCreateDb, (const QString &dbName), (dbName)); //! Creates database with name @a dbName, then uses it and creates test tables //! The database stays used. //! @note dbName should not include ".kexi" extension or path KDBTEST_METHOD_DECL(testCreateDbWithTables, (const QString &dbName), (dbName)); KDBTEST_METHOD_DECL(testProperties, (), ()); KDBTEST_METHOD_DECL(testCreateTables, (), ()); KDBTEST_METHOD_DECL(testDisconnect, (), ()); KDBTEST_METHOD_DECL(testDropDb, (), ()); KDBTEST_METHOD_DECL(testDisconnectAndDropDb, (), ()); protected: void testDisconnectPrivate(); void testDriver(const QString &driverId, bool fileBased, const QStringList &expectedMimeTypes, const QStringList &possiblyInvalidMimeTypes); void testDriverManagerInternal(bool forceEmpty); private: Q_DISABLE_COPY(KDbTestUtils) class Private; Private * const d; }; #endif diff --git a/src/KDbConnection.h b/src/KDbConnection.h index 48008fae..a6968cf8 100644 --- a/src/KDbConnection.h +++ b/src/KDbConnection.h @@ -1,1446 +1,1448 @@ /* This file is part of the KDE project Copyright (C) 2003-2018 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTION_H #define KDB_CONNECTION_H #include "KDbCursor.h" #include "KDbDriver.h" #include "KDbPreparedStatement.h" #include "KDbTableSchema.h" #include "KDbTransaction.h" #include "KDbTristate.h" class KDbConnectionData; class KDbConnectionOptions; class KDbConnectionPrivate; class KDbConnectionProxy; class KDbDriver; class KDbProperties; class KDbRecordData; class KDbRecordEditBuffer; class KDbServerVersionInfo; class KDbSqlResult; class KDbTableSchemaChangeListener; class KDbTableSchemaChangeListenerPrivate; class KDbTransactionGuard; class KDbVersionInfo; /*! @short Provides database connection, allowing queries and data modification. This class represents a database connection established within a data source. It supports data queries and modification by creating client-side database cursors. Database transactions are supported. */ class KDB_EXPORT KDbConnection : public KDbResultable { Q_DECLARE_TR_FUNCTIONS(KDbConnection) public: /*! Opened connection is automatically disconnected and removed from driver's connections list. Note for driver developers: you should call destroy() from you KDbConnection's subclass destructor. */ ~KDbConnection() override; /*! @return parameters that were used to create this connection. */ KDbConnectionData data() const; /*! @return the driver used for this connection. */ KDbDriver* driver() const; /*! @brief Connects to driver with given parameters. @return true if successful. Note: many database drivers may require connData.databaseName() to be specified because explicit database name is needed to perform connection (e.g. SQLite, PostgreSQL). MySQL does not require database name; KDbConnection::useDatabase() can be called later. */ bool connect(); /*! @return true, if connection is properly established. */ bool isConnected() const; /*! @return true, both if connection is properly established and any database within this connection is properly used with useDatabase(). */ bool isDatabaseUsed() const; /*! @return generic options for a single connection. The options are accessible using key/value pairs. This enables extensibility depending on driver's type and version. */ KDbConnectionOptions *options(); /*! Reimplemented, also clears sql string. @sa recentSqlString() */ void clearResult(); /*! @brief Disconnects from driver with given parameters. The database (if used) is closed, and any active transactions (if supported) are rolled back, so commit these before disconnecting, if you'd like to save your changes. */ bool disconnect(); /*! @return list of database names for opened connection. If @a also_system_db is true, the system database names are also returned. */ QStringList databaseNames(bool also_system_db = false); /*! @return true if database @a dbName exists. If @a ignoreErrors is true, error flag of connection won't be modified for any errors (it will quietly return), else (ignoreErrors == false) we can check why the database does not exist using error(), errorNum() and/or errorMsg(). */ bool databaseExists(const QString &dbName, bool ignoreErrors = true); /*! @brief Creates new database with name @a dbName, using this connection. If database with @a dbName already exists, or other error occurred, false is returned. For file-based drivers, @a dbName should be equal to the database filename (the same as specified for KDbConnectionData). See docs/kdb_issues.txt document, chapter "Table schema, query schema, etc. storage" for database schema documentation (detailed description of kexi__* 'system' tables). @see useDatabase() */ bool createDatabase(const QString &dbName); /*! @brief Opens an existing database specified by @a dbName. If @a kexiCompatible is true (the default) initial checks will be performed to recognize database Kexi-specific format. Set @a kexiCompatible to false if you're using native database (one that have no Kexi System tables). For file-based drivers, @a dbName can be skipped, so the same as specified for KDbConnectionData is used. @return true on success, false on failure. If user has cancelled this action and @a cancelled is not 0, *cancelled is set to true. */ bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr); /*! @brief Closes currently used database for this connection. Any active transactions (if supported) are rolled back, so commit these before closing, if you'd like to save your changes. */ bool closeDatabase(); /*! @brief Get the name of the current database @return name of currently used database for this connection or empty string if there is no used database */ QString currentDatabase() const; /*! @brief Drops database with name @a dbName. if dbName is not specified, currently used database name is used (it is closed before dropping). */ bool dropDatabase(const QString &dbName = QString()); /*! @return names of all the @a objectType (see @a ObjectType in KDbGlobal.h) schemas stored in currently used database. KDb::AnyObjectType can be passed as @a objectType to get names of objects of any type. The list ordered is based on object identifiers. Only names that are identifiers (checked using KDb::isIdentifier()) are returned. If @a ok is not 0 then variable pointed by it will be set to the result. On error, the function returns empty list. @see kdbSystemTableNames() tableNames(int,bool*) */ QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr); /*! @return names of all table schemas stored in currently used database. If @a alsoSystemTables is true, internal KDb system table names (kexi__*) are also returned. The list ordered is based on object identifiers. Only names that are identifiers (checked using KDb::isIdentifier()) are returned. If @a ok is not 0 then variable pointed by it will be set to the result. On error, the function returns empty list. @see kdbSystemTableNames() objectNames(int,bool*) */ QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr); /*! @return true if table with name @a tableName exists in the database. @return @c false if it does not exist or @c cancelled if error occurred. The lookup is case insensitive. This method can be much faster than tableNames(). */ tristate containsTable(const QString &tableName); /*! @return list of internal KDb system table names (kexi__*). This does not mean that these tables can be found in currently opened database. Just static list of table names is returned. The list contents may depend on KDb library version; opened database can contain fewer 'system' tables than in current KDb implementation, if the current one is newer than the one used to build the database. @todo this will depend on KDb lib version */ static QStringList kdbSystemTableNames(); /*! @return server version information for this connection. If database is not connected (i.e. isConnected() is false) null KDbServerVersionInfo is returned. */ KDbServerVersionInfo serverVersion() const; /*! @return version information for this connection. If database is not used (i.e. isDatabaseUsed() is false) null KDbVersionInfo is returned. It can be compared to drivers' and KDb library version to maintain backward/upward compatiblility. */ KDbVersionInfo databaseVersion() const; /*! @return KDbProperties object allowing to read and write global database properties for this connection. */ KDbProperties databaseProperties() const; /*! @return ids of all table schema names stored in currently used database. These ids can be later used as argument for tableSchema(). This is a shortcut for objectIds(KDb::TableObjectType). Internal KDb system tables (kexi__*) are not available here because these have no identifiers assigned (more formally: id=-1). If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that tableSchema( id ) returns anything. The table definition can be broken, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see queryIds() */ QList tableIds(bool* ok = nullptr); /*! @return ids of all database query schemas stored in currently used database. These ids can be later used as argument for querySchema(). This is a shortcut for objectIds(KDb::QueryObjectType). If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that querySchema( id ) returns anything. The query definition can be broken, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see tableIds() */ QList queryIds(bool* ok = nullptr); /*! @return names of all schemas of object with @a objectType type that are stored in currently used database. If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that the definition of the object is valid, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see tableIds() queryIds() */ QList objectIds(int objectType, bool* ok = nullptr); /** * @brief Starts a new database transaction * * @return KDbTransaction object. If transaction has been started successfully returned object * points to it, otherwise null transaction is returned. * * For drivers that allow single transaction per connection * (KDbDriver::features() && SingleTransactions) this method can be called once and that * transaction will be default one (setDefaultTransaction() will be called). * For drivers that allow multiple transactions per connection no default transaction is * set automatically in beginTransaction(). setDefaultTransaction() can be called by hand. * * @see setDefaultTransaction(), defaultTransaction(). */ KDbTransaction beginTransaction(); /** * @brief Commits specified transaction for this connection * * If @a transaction is not active and default transaction (obtained from defaultTransaction()) * exists, the default one will be committed. If neither the default one is not present returns * @c true if IgnoreInactive is set in @a options or @c false if IgnoreInactive is not set in * @a options. * * @return @c false on any error. * * On successful commit, @a transaction object will point to a null transaction. * After commiting a default transaction, there is no default transaction anymore. */ bool commitTransaction(KDbTransaction transaction = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); /** * @brief Rolls back specified transaction for this connection * * If @a transaction is not active and default transaction (obtained from defaultTransaction()) * exists, the default one will be rolled back. If neither default one is present @c true is * returned if IgnoreInactive is set for @a options or @c false if IgnoreInactive is not set in * @a options. * * @return @c false on any error. * * On successful rollback, @a transaction object will point to a null transaction. * After rollong back a default transaction, there is no default transaction anymore. */ bool rollbackTransaction(KDbTransaction trans = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); /** * @brief Returns handle of default transaction for this connection * * Null transaction is returned if there is no such a transaction declared. * If transactions are supported any operation on database (e.g. inserts) that are started * without specifying a transaction context, are be performed in the context of this transaction. * Returned null transaction doesn't mean that there are no transactions started at all. * Default transaction can be defined automatically for certain drivers, see beginTransaction(). * * @see KDbDriver::transactionsSupported() */ KDbTransaction defaultTransaction() const; /** * @brief Sets default transaction * * Default transaction is used as a context for data modifications for this connection when no * specific transaction is provided. */ void setDefaultTransaction(const KDbTransaction& trans); /** * @brief Returns set of handles of currently active transactions * * @note In multithreading environment some of these transactions can be already inactive after * calling this method. Use KDbTransaction::isActive() to check that. Inactive transaction * handle is useless and can be safely ignored. */ QList transactions(); /*! @return true if "auto commit" option is on. When auto commit is on (the default on for any new KDbConnection object), every SQL statement that manipulates data in the database implicitly starts a new transaction. This transaction is automatically committed after successful statement execution or rolled back on error. For drivers that do not support transactions (see KDbDriver::features()) this method shouldn't be called because it does nothing ans always returns false. No internal KDb object should changes this option, although auto commit's behavior depends on database engine's specifics. Engines that support only single transaction per connection (see KDbDriver::SingleTransactions), use this single connection for autocommiting, so if there is already transaction started by the KDb user program (with beginTransaction()), this transaction is committed before any statement that manipulates data. In this situation default transaction is also affected (see defaultTransaction()). Only for drivers that support nested transactions (KDbDriver::NestedTransactions), autocommiting works independently from previously started transaction, For other drivers set this option off if you need use transaction for grouping more statements together. NOTE: nested transactions are not yet implemented in KDb API. */ bool autoCommit() const; /*! Changes auto commit option. This does not affect currently started transactions. This option can be changed even when connection is not established. @see autoCommit() */ bool setAutoCommit(bool on); /*! Connection-specific string escaping. Default implementation uses driver's escaping. Use KDbEscapedString::isValid() to check if escaping has been performed successfully. Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true, not just isEmpty(). */ virtual KDbEscapedString escapeString(const QString& str) const; /*! Prepares SELECT query described by a raw statement @a sql. @return opened cursor created for results of this query or @c nullptr if there was any error. Ownership of the returned object is passed to the caller. KDbCursor can have optionally applied @a options (one of more selected from KDbCursor::Options). Preparation means that returned cursor is created but not opened. Open this when you would like to do it with KDbCursor::open(). Note for driver developers: you should initialize cursor engine-specific resources and return KDbCursor subclass' object (passing @a sql and @a options to its constructor). */ virtual KDbCursor* prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0; /*! @overload Prepares query described by @a query schema. @a params are values of parameters that will be inserted into places marked with [] before execution of the query. Note for driver developers: you should initialize cursor engine-specific resources and return KDbCursor subclass' object (passing @a query and @a options to it's constructor). Kexi SQL and driver-specific escaping is performed on table names. */ - KDbCursor* prepareQuery(KDbQuerySchema* query, const QList& params, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, const QList ¶ms, + KDbCursor::Options options = KDbCursor::Option::None); /*! @overload Prepares query described by @a query schema without parameters. */ virtual KDbCursor* prepareQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0; /*! @overload - Statement is build from data provided by @a table schema, it is like "select * from table_name".*/ - KDbCursor* prepareQuery(KDbTableSchema* table, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Statement is build from data provided by @a table schema, it is like "select * from + table_name".*/ + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbTableSchema *table, + KDbCursor::Options options = KDbCursor::Option::None); /*! Executes SELECT query described by a raw SQL statement @a sql. @return opened cursor created for results of this query or 0 if there was any error on the cursor creation or opening. Ownership of the returned object is passed to the caller. KDbCursor can have optionally applied @a options. Identifiers in @a sql that are the same as keywords in KDbSQL dialect or the backend's SQL have to be escaped. */ - KDbCursor* executeQuery(const KDbEscapedString& sql, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *executeQuery(const KDbEscapedString &sql, + KDbCursor::Options options = KDbCursor::Option::None); /*! @overload executeQuery(const KDbEscapedString&, int) @a params are values of parameters that will be inserted into places marked with [] before execution of the query. Statement is build from data provided by @a query schema. Kexi SQL and driver-specific escaping is performed on table names. */ - KDbCursor* executeQuery(KDbQuerySchema* query, const QList& params, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query, const QList ¶ms, + KDbCursor::Options options = KDbCursor::Option::None); /*! @overload */ - KDbCursor* executeQuery(KDbQuerySchema* query, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbQuerySchema *query, + KDbCursor::Options options = KDbCursor::Option::None); /*! @overload Executes query described by @a query schema without parameters. Statement is build from data provided by @a table schema, it is like "select * from table_name".*/ - KDbCursor* executeQuery(KDbTableSchema* table, - KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *executeQuery(KDbTableSchema *table, + KDbCursor::Options options = KDbCursor::Option::None); /*! Deletes cursor @a cursor previously created by functions like executeQuery() for this connection. There is an attempt to close the cursor with KDbCursor::close() if it was opened. Anyway, at last cursor is deleted. @return true if cursor is properly closed before deletion. */ bool deleteCursor(KDbCursor *cursor); /*! @return schema of a table pointed by @a tableId, retrieved from currently used database. The schema is cached inside connection, so retrieval is performed only once, on demand. */ KDbTableSchema* tableSchema(int tableId); /*! @return schema of a table pointed by @a tableName, retrieved from currently used database. KDb system table schema can be also retrieved. @see tableSchema( int tableId ) */ KDbTableSchema* tableSchema(const QString& tableName); /*! @return schema of a query pointed by @a queryId, retrieved from currently used database. The schema is cached inside connection, so retrieval is performed only once, on demand. */ KDbQuerySchema* querySchema(int queryId); /*! @return schema of a query pointed by @a queryName, retrieved from currently used database. @see querySchema( int queryId ) */ KDbQuerySchema* querySchema(const QString& queryName); /*! Sets @a queryName query obsolete by moving it out of the query sets, so it will not be accessible by querySchema( const QString& queryName ). The existing query object is not destroyed, to avoid problems when it's referenced. In this case, a new query schema will be retrieved directly from the backend. For now it's used in KexiQueryDesignerGuiEditor::storeLayout(). This solves the problem when user has changed a query schema but already form still uses previously instantiated query schema. @return true if there is such query. Otherwise the method does nothing. */ bool setQuerySchemaObsolete(const QString& queryName); //! Options for querying records //! @since 3.1 enum class QueryRecordOption { AddLimitTo1 = 1, //!< Adds a "LIMIT 1" clause to the query for optimization purposes //!< (it should not include one already) Default = AddLimitTo1 }; Q_DECLARE_FLAGS(QueryRecordOptions, QueryRecordOption) /*! Executes query for a raw statement @a sql and stores first record's data inside @a data. This is a convenient method when we need only first record from query result, or when we know that query result has only one record. If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return @c true if query was successfully executed and first record has been found, @c false on data retrieving failure, and @c cancelled if there's no single record available. */ tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ tristate querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, const QList ¶ms, QueryRecordOptions options = QueryRecordOption::Default); /*! Executes query for a raw statement @a sql and stores first record's field's (number @a column) string value inside @a value. For efficiency it's recommended that a query defined by @a sql should have just one field (SELECT one_field FROM ....). If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return @c true if query was successfully executed and first record has been found, @c false on data retrieving failure, and @c cancelled if there's no single record available. @see queryStringList() */ tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with [] before query execution. */ tristate querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! Convenience function: executes query for a raw SQL statement @a sql and stores first record's field's (number @a column) value inside @a number. @see querySingleString(). If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return true if query was successfully executed and first record has been found, false on data retrieving failure, and cancelled if there's no single record available. */ tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ tristate querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! Executes query for a raw SQL statement @a sql and stores Nth field's string value of every record inside @a list, where N is equal to @a column. The list is initially cleared. For efficiency it's recommended that a query defined by @a sql should have just one field (SELECT one_field FROM ....). @return true if all values were fetched successfuly, false on data retrieving failure. Returning empty list can be still a valid result. On errors, the list is not cleared, it may contain a few retrieved values. */ bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0); /*! @overload Uses a QuerySchema object. */ bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ bool queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column = 0); /*! @return @c true if there is at least one record has been returned by executing query for a raw SQL statement @a sql or @c false if no such record exists. If @a options includes AddLimitTo1 value, the query is optimized into "SELECT 1 FROM (sql) LIMIT 1" (this is the default). Caller should make sure "SELECT 1" and "LIMIT 1" is not there in the @a sql already. This method does not fetch any records. On error returns @c cancelled. */ tristate resultExists(const KDbEscapedString &sql, QueryRecordOptions options = QueryRecordOption::Default); /*! @return true if there is at least one record in @a table. */ tristate isEmpty(KDbTableSchema* table); /** * @brief Return recently used SQL string * * If there was a successful query execution it is equal to result().sql(), * otherwise it is equal to result().errorSql(). */ virtual KDbEscapedString recentSqlString() const; //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args) QSharedPointer insertRecord(KDbTableSchema* tableSchema args) #define H_INS_REC_ALL \ H_INS_REC(A); \ H_INS_REC(A A); \ H_INS_REC(A A A); \ H_INS_REC(A A A A); \ H_INS_REC(A A A A A); \ H_INS_REC(A A A A A A); \ H_INS_REC(A A A A A A A); \ H_INS_REC(A A A A A A A A) H_INS_REC_ALL; #undef H_INS_REC #define H_INS_REC(args) QSharedPointer insertRecord(KDbFieldList* fields args) H_INS_REC_ALL; #undef H_INS_REC_ALL #undef H_INS_REC #undef A QSharedPointer insertRecord(KDbTableSchema *tableSchema, const QList &values); QSharedPointer insertRecord(KDbFieldList *fields, const QList &values); //! Options for creating table //! @since 3.1 enum class CreateTableOption { Default = 0, DropDestination = 1 //!< Drop destination table if exists }; Q_DECLARE_FLAGS(CreateTableOptions, CreateTableOption) /** * @brief Creates a new table * * Creates a new table defined by @a tableSchema. @c true is returned on success. In this case * @a tableSchema object is added to KDbConnection's structures and becomes owned the * KDbConnection object, so should not be destroyed by hand. * * If @a options include the DropDestination value and table schema with the same name as @a * tableSchema exists, it is dropped and the original identifier of the dropped schem is * assigned to the @a tableSchema object. * * If @a options do not include the DropDestination value and table schema with the same name * as @a tableSchema exists, @c false is returned. * * Table and column definitions are added to "Kexi system" tables. * * Prior to dropping the method checks if the table for the schema is in use, and if the new * schema defines at least one column. * * Note that on error: * - @a tableSchema is not inserted into KDbConnection's structures, so caller is still owner * of the object, * - existing table schema object is not destroyed (e.g. it is still available for * KDbConnection::tableSchema(const QString&), even if the table was physically dropped. * * @return true on success. */ bool createTable(KDbTableSchema *tableSchema, CreateTableOptions options = CreateTableOption::Default); /*! Creates a copy of table schema defined by @a tableSchema with data. Name, caption and description will be copied from @a newData. @return a table schema object. It is inserted into the KDbConnection structures and is owned by the KDbConnection object. The created table schema object should not be destroyed by hand afterwards. 0 is returned on failure. Table with destination name must not exist. @see createTable() */ KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData); /*! It is a convenience function, does exactly the same as KDbTableSchema *copyTable(const KDbTableSchema&, const KDbObject&). */ KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData); /*! Drops a table defined by @a tableSchema (both table object as well as physically). If true is returned, schema information @a tableSchema is destoyed (because it's owned), so don't keep this anymore! No error is raised if the table does not exist physically - its schema is removed even in this case. Removes the table and column definitions in kexi__* "system schema" tables. First checks that the table is not a system table. @todo Check that a database is currently in use? (c.f. createTable) @todo Update any structure (e.g. query) that depends on this table */ tristate dropTable(KDbTableSchema* tableSchema); /*! @overload * It is a convenience function. */ tristate dropTable(const QString& tableName); /*! Alters @a tableSchema using @a newTableSchema in memory and on the db backend. @return true on success, cancelled if altering was cancelled. */ //! @todo (js): implement real altering //! @todo (js): update any structure (e.g. query) that depend on this table! tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema); //! Options for altering table name //! @since 3.1 enum class AlterTableNameOption { Default = 0, DropDestination = 1 //!< Drop destination table if exists }; Q_DECLARE_FLAGS(AlterTableNameOptions, AlterTableNameOption) /** * @brief Alters name of table * * Alters name of table described by @a tableSchema to @a newName. * If @a options include the DropDestination value and table having name @a newName already * exists, it is physically dropped, removed from connection's list of tables and replaced * by @a tableSchema. In this case identifier of @a tableSchema is set to the dropped table's * identifier. This can be useful if @a tableSchema was created with a temporary name and * identifier. It is for example used in KDbAlterTableHandler. * * If @a options do not include the DropDestination value (the default) and table having name * @a newName already exists, @c false is returned and @c ERR_OBJECT_EXISTS error is set in * the connection object. * * Table name in the schema of @a tableSchema is updated on successful altering. * @return true on success. */ bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, AlterTableNameOptions options = AlterTableNameOption::Default); /*! Drops a query defined by @a querySchema. If true is returned, schema information @a querySchema is destoyed (because it's owned), so don't keep this anymore! */ bool dropQuery(KDbQuerySchema* querySchema); /*! It is a convenience function, does exactly the same as bool dropQuery( KDbQuerySchema* querySchema ) */ bool dropQuery(const QString& queryName); /*! Removes information about object with @a objId from internal "kexi__object" and "kexi__objectdata" tables. @return true on success. */ bool removeObject(int objId); /*! @return first field from @a fieldlist that has system name, @c nullptr if there are no such field. For checking, KDbDriver::isSystemFieldName() is used, so this check can be driver-dependent. */ KDbField* findSystemFieldName(const KDbFieldList& fieldlist); /*! @return name of any (e.g. first found) database for this connection. This method does not close or open this connection. The method can be used (it is also internally used, e.g. for database dropping) when we need a database name before we can connect and execute any SQL statement (e.g. DROP DATABASE). The method can return nul lstring, but in this situation no automatic (implicit) connections could be made, what is useful by e.g. dropDatabase(). Note for driver developers: return here a name of database which you are sure is existing. Default implementation returns: - value that previously had been set using setAvailableDatabaseName() for this connection, if it is not empty - else (2nd priority): value of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME if it is not empty. See description of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME member. You may want to reimplement this method only when you need to depend on this connection specifics (e.g. you need to check something remotely). */ virtual QString anyAvailableDatabaseName(); /*! Sets @a dbName as name of a database that can be accessible. This is option that e.g. application that make use of KDb library can set to tune connection's behavior when it needs to temporary connect to any database in the server to do some work. You can pass empty dbName - then anyAvailableDatabaseName() will try return KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value instead of the one previously set with setAvailableDatabaseName(). @see anyAvailableDatabaseName() */ void setAvailableDatabaseName(const QString& dbName); /*! Because some engines need to have opened any database before executing administrative SQL statements like "create database" or "drop database", this method is used to use appropriate, existing database for this connection. For file-based db drivers this always return true and does not set @a name to any value. For other db drivers: this sets @a name to db name computed using anyAvailableDatabaseName(), and if the name computed is empty, false is returned; if it is not empty, useDatabase() is called. False is returned also when useDatabase() fails. You can call this method from your application's level if you really want to perform tasks that require any used database. In such a case don't forget to closeDatabase() if returned @a name is not empty. Note: This method has nothing to do with creating or using temporary databases in such meaning that these database are not persistent */ bool useTemporaryDatabaseIfNeeded(QString* name); /** * Prepares execution of a new native (raw, backend-specific) SQL query. * * The query is described by a raw statement @a sql which should be is valid and properly * escaped. Access to results can be obtained using * the returned KDbSqlResult object. The object is guarded with a shared pointer to facilitate * transfer of ownership and memory management. A null pointer is returned if preparation of * the query fails. Use KDbConnection::result() immediately after calling prepareSql() to * obtain detailed result information about the preparation. * * The returned object should be deleted before the database connection is closed. * Connection object does not deletes the KDbSqlResult objects. It is also possible and * recommended that caller deletes the KDbSqlResult object as soon as the result is not needed. * * The returned object can be ignored if the query is not supposed to return records (e.g. * manipulates data through INSERT, UPDATE, DELETE, ...) or the caller is not interested in the * records. Thanks to the use of the shared pointer the object will be immediately deleted and * execution will be finalized prior to that. However to execute queries that return no * results, executeSql() is a better choice because of performance and easier reporting to * results. * * @note Only use this method if a non-portable raw query is required. * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. */ - QSharedPointer prepareSql(const KDbEscapedString& sql) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT QSharedPointer prepareSql(const KDbEscapedString& sql); /** * Executes a new native (raw, backend-specific) SQL query * * The query is described by a raw statement @a sql which should be is valid and properly * escaped. This method is a convenience version of prepareSql() that immediately starts and * finalizes execution of a raw query in one step and provides a result. Use it for queries * that do not return records, i.e. for queries that manipulate data (INSERT, UPDATE, DELETE, * ...) or if the caller is not interested in the returned records. * * @note Only use this method if a non-portable raw query is required. * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. */ bool executeSql(const KDbEscapedString& sql); /*! Stores object (id, name, caption, description) described by @a object on the backend. It is expected that entry on the backend already exists, so it's updated. Changes to identifier attribute are not allowed. @return true on success. */ bool storeObjectData(KDbObject* object); /*! Stores new entry for object (id, name, caption, description) described by @a object on the backend. If object.id() was less than 0, new, unique object identifier is obtained and assigned to @a object (see KDbObject::id()). @return true on success. */ bool storeNewObjectData(KDbObject* object); /*! Finds object data for object of type @a type and identifier @a id. Added for convenience. If @a type is KDb::AnyObjectType, object type is ignored during the find. @see setupObjectData(const KDbRecordData*, KDbObject*). @return true on success, false on failure and cancelled when such object couldn't be found. @since 3.1 */ tristate loadObjectData(int type, int id, KDbObject* object); /*! Finds object data for object of type @a type and name @a name. If the object is found, resulted schema is stored in @a object and true is returned, otherwise false is returned. */ tristate loadObjectData(int type, const QString& name, KDbObject* object); /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID and puts it to @a dataString. The can be block indexed with optional @a dataID. @return true on success, false on failure and cancelled when there is no such data block @see storeDataBlock(). */ tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString()); /*! Stores (potentially large) data block @a dataString (e.g. xml form's representation), referenced by objectID. Block will be stored in "kexi__objectdata" table and an optional @a dataID identifier. If there is already such record in the table, it's simply overwritten. @return true on success @see loadDataBlock() removeDataBlock() copyDataBlock(). */ bool storeDataBlock(int objectID, const QString &dataString, const QString& dataID = QString()); /*! Copies (potentially large) data, e.g. form's XML representation, referenced by @a sourceObjectID pointed by optional @a dataID. @return true on success. Does not fail if blocks do not exist. Prior to copying, existing data blocks are removed even if there are no new blocks to copy. Copied data blocks will have @a destObjectID object identifier assigned. Note that if @a dataID is not specified, all data blocks found for the @a sourceObjectID will be copied. @see loadDataBlock() storeDataBlock() removeDataBlock(). */ bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString()); /*! Removes (potentially large) string data (e.g. xml form's representation), referenced by @a objectID, and pointed by optional @a dataID. @return true on success. Does not fail if the block does not exist. Note that if @a dataID is not specified, all data blocks for the @a objectID will be removed. @see loadDataBlock() storeDataBlock() copyDataBlock(). */ bool removeDataBlock(int objectID, const QString& dataID = QString()); /*! Prepare an SQL statement and return a @a KDbPreparedStatement instance. */ KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames = QStringList()); bool isInternalTableSchema(const QString& tableName); /** * @brief Returns number of records returned by given SQL statement * * @return number of records that can be retrieved after executing @a sql statement within * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. * -1 is returned if any error occurred or if @a conn is @c nullptr. * * @since 3.1 */ //! @todo perhaps use quint64 here? int recordCount(const KDbEscapedString& sql); /** * @brief Returns number of records that contains given table * * @return number of records that can be retrieved from @a tableSchema. * To obtain the result the table must be created or retrieved using a KDbConnection object, * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" * SQL aggregation is used at the backed. * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr. * * @since 3.1 */ //! @todo perhaps use quint64 here? //! @todo does not work with non-SQL data sources int recordCount(const KDbTableSchema& tableSchema); /** * @overload * * Operates on a query schema. @a params are optional values of parameters that will be inserted * into [] placeholders before execution of query that counts the records. * To obtain the result the query must be created or retrieved using a KDbConnection object, * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" * SQL aggregation is used at the backed. * -1 is returned if error occurred or if querySchema->connection() is @c nullptr. * * @since 3.1 */ //! @todo perhaps use quint64 here? int recordCount(KDbQuerySchema* querySchema, const QList& params = QList()); /** * @overload * * Operates on a table or query schema. @a params is a list of optional parameters that * will be inserted into [] placeholders before execution of query that counts the records. * * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned. * * @since 3.1 */ //! @todo perhaps use quint64 here? int recordCount(KDbTableOrQuerySchema* tableOrQuery, const QList& params = QList()); //! Identifier escaping function in the associated KDbDriver. /*! Calls the identifier escaping function in this connection to escape table and column names. This should be used when explicitly constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)). It should not be used for other functions (e.g. don't do useDatabase(escapeIdentifier(database))), because the identifier will be escaped when the called function generates, for example, "USE " + escapeIdentifier(database). For efficiency, KDb "system" tables (prefixed with kexi__) and columns therein are not escaped - we assume these are valid identifiers for all drivers. Use KDbEscapedString::isValid() to check if escaping has been performed successfully. Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true, not just isEmpty(). */ virtual QString escapeIdentifier(const QString& id) const; protected: /*! Used by KDbDriver */ KDbConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); /*! Method to be called form KDbConnection's subclass destructor. @see ~KDbConnection() */ void destroy(); /*! For implementation: connects to database. @return true on success. */ virtual bool drv_connect() = 0; /*! For implementation: disconnects database @return true on success. */ virtual bool drv_disconnect() = 0; /*! For implementation: Sets @a version to real server's version. Depending on backend type this method is called after (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is true) or before database is used (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is false), i.e. for PostgreSQL it is called after. In any case it is called after successful drv_connect(). @return true on success. */ virtual bool drv_getServerVersion(KDbServerVersionInfo* version) = 0; /** * LOW LEVEL METHOD. Obtains a list containing names of all physical * tables of this connection and returns it. * * @a ok must not be @c nullptr. * * Default implementation covers functionality of SQL backends. It executes low-level SQL * defined by KDbDriverBehavior::GET_TABLE_NAMES_SQL string. On failure of execution or if * KDbDriverBehavior::GET_TABLE_NAMES_SQL is empty, @a ok is set to @c false. On success @a ok * is set to @c true. Returning empty list is not an error. * * If the database driver is not able to offer such a list, do not reimplement this method, it * will just always return false and users of KDb will need to take this into account. * * To reimplement the method, set @a ok to @c true only on successfull obtaining of table names, * and to @c false otherwise. * * This method is used by tableNames() to filter out tables names that have been found in * project's metadata but lack related physical tables. * * @since 3.2 * * @see tableNames() */ virtual QStringList drv_getTableNames(bool *ok); /*! LOW LEVEL METHOD. For implementation: returns true if table with name @a tableName exists in the database. @return @c false if it does not exist or @c cancelled if error occurred. The lookup is case insensitive. */ virtual tristate drv_containsTable(const QString &tableName) = 0; /** * Creates table using @a tableSchema information. * * @return true on success. * * Default implementation builds a statement using createTableStatement() and calls * executeSql(). Note for driver developers: reimplement this only to perform creation in other * way. */ virtual bool drv_createTable(const KDbTableSchema& tableSchema); /*! Alters table's described @a tableSchema name to @a newName. This is the default implementation, using "ALTER TABLE RENAME TO ", what's supported by SQLite >= 3.2, PostgreSQL, MySQL. Backends lacking ALTER TABLE, for example SQLite, reimplement this with by an inefficient data copying to a new table. In any case, renaming is performed at the backend. It's good idea to keep the operation within a transaction. @return true on success. */ virtual bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName); /*! Copies table data from @a tableSchema to @a destinationTableSchema Default implementation executes "INSERT INTO .. SELECT * FROM .." @return true on success. */ virtual bool drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema); /*! Physically drops table named with @a name. Default impelmentation executes "DROP TABLE.." command, so you rarely want to change this. */ virtual bool drv_dropTable(const QString& tableName); /*! @internal drops table @a tableSchema physically, but destroys @a tableSchema object only if @a alsoRemoveSchema is true. Used (alsoRemoveSchema==false) on table altering: if recreating table can fail we're giving up and keeping the original table schema (even if it is no longer points to any real data). */ tristate dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema); /*! Setups data for object that owns @a object (e.g. table, query) opened on 'kexi__objects' table, pointing to a record corresponding to given object. */ bool setupObjectData(const KDbRecordData& data, KDbObject* object); /*! @return a new field table schema for a table retrieved from @a data. Ownership of the returned object is passed to the caller. Used internally by tableSchema(). */ - KDbField* setupField(const KDbRecordData& data) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbField *setupField(const KDbRecordData &data); /** * Prepares query for a raw SQL statement @a sql with possibility of returning records. * * It is useful mostly for SELECT queries. While INSERT queries do not return records, the * KDbSqlResult object offers KDbSqlResult::lastInsertRecordId(). The @sql should be is valid * and properly escaped. Only use this method if you really need. For low-level access to the * results (without cursors). The result may be not stored (not buffered) yet. Use * KDbSqlResult::fetchRecord() to fetch each record. @return Null pointer if there is no proper * result or error. Ownership of the returned object is passed to the caller. * * @see prepareSql */ virtual KDbSqlResult* drv_prepareSql(const KDbEscapedString &sql) /*Q_REQUIRED_RESULT*/ = 0; /** * Executes query for a raw SQL statement @a sql without returning resulting records. * * It is useful mostly for INSERT queries but it is possible to execute SELECT queries when * returned records can be ignored. The @sql should be is valid and properly escaped. * * @note Only use this method if you really need. * @see executeSql */ virtual bool drv_executeSql(const KDbEscapedString& sql) = 0; /*! For reimplementation: loads list of databases' names available for this connection and adds these names to @a list. If your server is not able to offer such a list, consider reimplementing drv_databaseExists() instead. The method should return true only if there was no error on getting database names list from the server. Default implementation puts empty list into @a list and returns true. @see databaseNames */ virtual bool drv_getDatabasesList(QStringList* list); /*! For optional reimplementation: asks server if database @a dbName exists. This method is used internally in databaseExists(). The default implementation calls databaseNames and checks if that list contains @a dbName. If you need to ask the server specifically if a database exists, eg. if you can't retrieve a list of all available database names, please reimplement this method and do all needed checks. See databaseExists() description for details about ignoreErrors argument. You should use it properly in your implementation. Note: This method should also work if there is already database used (with useDatabase()); in this situation no changes should be made in current database selection. */ virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true); /*! For implementation: creates new database using connection */ virtual bool drv_createDatabase(const QString &dbName = QString()) = 0; /*! For implementation: opens existing database using connection @return true on success, false on failure; sets @a cancelled to true if this action has been cancelled. */ virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) = 0; /*! For implementation: closes previously opened database using connection. */ virtual bool drv_closeDatabase() = 0; /*! @return true if internal driver's structure is still in opened/connected state and database is used. Note for driver developers: Put here every test that you can do using your internal engine's database API, eg (a bit schematic): my_connection_struct->isConnected()==true. Do not check things like KDbConnection::isDatabaseUsed() here or other things that "KDb already knows" at its level. If you cannot test anything, just leave default implementation (that returns true). Result of this method is used as an additional chance to check for isDatabaseUsed(). Do not call this method from your driver's code, it should be used at KDb level only. */ virtual bool drv_isDatabaseUsed() const { return true; } /*! For implementation: drops database from the server using connection. After drop, database shouldn't be accessible anymore. */ virtual bool drv_dropDatabase(const QString &dbName = QString()) = 0; /*! Creates table named by @a tableName. Schema object must be on schema tables' list before calling this method (otherwise false if returned). Just uses drv_createTable( const KDbTableSchema& tableSchema ). Used internally, e.g. in createDatabase(). @return true on success */ virtual bool drv_createTable(const QString& tableName); /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "BEGIN" sql statement and returns just empty data (KDbTransactionData object). Ownership of the returned object is passed to the caller. Drivers that do not support transactions (see KDbDriver::features()) do never call this method. Reimplement this method if you need to do something more (e.g. if you driver will support multiple transactions per connection). Make subclass of KDbTransactionData (declared in KDbTransaction.h) and return object of this subclass. @c nullptr should be returned on error. Do not check anything in connection (isConnected(), etc.) - all is already done. @todo Add support for nested transactions, e.g. KDbTransactionData* beginTransaction(KDbTransactionData *parent) */ - virtual KDbTransactionData* drv_beginTransaction() Q_REQUIRED_RESULT; + virtual Q_REQUIRED_RESULT KDbTransactionData *drv_beginTransaction(); /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "COMMIT" sql statement and returns true on success. @see drv_beginTransaction() */ virtual bool drv_commitTransaction(KDbTransactionData* trans); /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "ROLLBACK" sql statement and returns true on success. @see drv_beginTransaction() */ virtual bool drv_rollbackTransaction(KDbTransactionData* trans); /*! Preprocessing (if any) required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed before an Insert statement. @see drv_afterInsert() */ virtual bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Postprocessing (if any) required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed after an Insert statement. @see drv_beforeInsert() */ virtual bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Preprocessing required by drivers before execution of an Update statement. Reimplement this method in your driver if there are any special processing steps to be executed before an Update statement. @see drv_afterUpdate() */ virtual bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Postprocessing required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed after an Update statement. @see drv_beforeUpdate() */ virtual bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Changes autocommiting option for established connection. @return true on success. Note for driver developers: reimplement this only if your engine allows to set special auto commit option (like "SET AUTOCOMMIT=.." in MySQL). If not, auto commit behavior will be simulated if at least single transactions per connection are supported by the engine. Do not set any internal flags for autocommiting -- it is already done inside setAutoCommit(). Default implementation does nothing with connection, just returns true. @see drv_beginTransaction(), autoCommit(), setAutoCommit() */ virtual bool drv_setAutoCommit(bool on); /*! Prepare an SQL statement and return a @a KDbPreparedStatementInterface-derived object. Ownership of the returned object is passed to the caller. */ virtual KDbPreparedStatementInterface* prepareStatementInternal() /*Q_REQUIRED_RESULT*/ = 0; /*! Internal, for handling autocommited transactions: begins transaction if one is supported. @return true if new transaction started successfully or no transactions are supported at all by the driver or if autocommit option is turned off. A handle to a newly created transaction (or @c nullptr on error) is passed to @a tg parameter. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): and there is already transaction started, it is committed before starting a new one, but only if this transaction has been started inside KDbConnection object. (i.e. by beginAutoCommitTransaction()). Otherwise, a new transaction will not be started, but true will be returned immediately. */ bool beginAutoCommitTransaction(KDbTransactionGuard* tg); /*! Internal, for handling autocommited transactions: Commits transaction prevoiusly started with beginAutoCommitTransaction(). @return true on success or when no transactions are supported at all by the driver. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): if @a trans has been started outside KDbConnection object (i.e. not by beginAutoCommitTransaction()), the transaction will not be committed. */ bool commitAutoCommitTransaction(const KDbTransaction& trans); /*! Internal, for handling autocommited transactions: Rolls back transaction prevoiusly started with beginAutoCommitTransaction(). @return true on success or when no transactions are supported at all by the driver. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): @a trans will not be rolled back if it has been started outside this KDbConnection object. */ bool rollbackAutoCommitTransaction(const KDbTransaction& trans); /*! Helper: checks if connection is established; if not: error message is set up and false returned */ bool checkConnected(); /*! Helper: checks both if connection is established and database any is used; if not: error message is set up and false returned */ bool checkIsDatabaseUsed(); /*! Update a record. */ bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); /*! Insert a new record. */ bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false); /*! Delete an existing record. */ bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false); /*! Delete all existing records. */ bool deleteAllRecords(KDbQuerySchema* query); /*! Called by KDbTableSchema -- signals destruction to KDbConnection object To avoid having deleted table object on its list. */ void removeMe(KDbTableSchema *ts); // -- internal methods follow /*! @internal @return true if the cursor @a cursor contains column @a column, else, sets appropriate error with a message and returns false. */ bool checkIfColumnExists(KDbCursor *cursor, int column); /*! @internal used by insertRecord() methods. */ QSharedPointer insertRecordInternal(const QString &tableSchemaName, KDbFieldList *fields, const KDbEscapedString &sql); /*! @internal used by querySingleRecord() methods. */ tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, QueryRecordOptions options); /*! @internal used by querySingleString() methods. */ tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); /*! @internal used by queryNumberString() methods. */ tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); /*! @internal used by queryStringList() methods. */ bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list, KDbQuerySchema* query, const QList* params, int column, bool (*filterFunction)(const QString&)); /*! @internal used by *Internal() methods. Executes query based on a raw SQL statement @a sql or @a query with optional @a params. Ownership of the returned object is passed to the caller.*/ - KDbCursor* executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, - const QList* params) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *executeQueryInternal(const KDbEscapedString &sql, + KDbQuerySchema *query, + const QList *params); /*! Loads extended schema information for table @a tableSchema, if present (see ExtendedTableSchemaInformation in Kexi Wiki). @return true on success */ bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema); /*! Stores extended schema information for table @a tableSchema, (see ExtendedTableSchemaInformation in Kexi Wiki). The action is performed within the current transaction, so it's up to you to commit. Used, e.g. by createTable(), within its transaction. @return true on success */ bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema); /*! @internal Stores main field's schema information for field @a field. Used in table altering code when information in kexi__fields has to be updated. @return true on success and false on failure. */ bool storeMainFieldSchema(KDbField *field); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! This is a part of alter table interface implementing lower-level operations used to perform table schema altering. Used by KDbAlterTableHandler. Changes value of field property. @return true on success, false on failure, cancelled if the action has been cancelled. Note for driver developers: implement this if the driver has to supprot the altering. */ virtual tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field, const QString& propertyName, const QVariant& value) { Q_UNUSED(table); Q_UNUSED(field); Q_UNUSED(propertyName); Q_UNUSED(value); return cancelled; } //! Used by KDbCursor class void addCursor(KDbCursor* cursor); //! Used by KDbCursor class void takeCursor(KDbCursor* cursor); private: //! Internal, used by storeObjectData(KDbObject*) and storeNewObjectData(KDbObject* object). bool storeObjectDataInternal(KDbObject* object, bool newObject); //! @internal //! @return identifier escaped by driver (if @a escapingType is KDb::DriverEscaping) //! or by the KDb's built-in escape routine. QString escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const; KDbConnectionPrivate* d; //!< @internal d-pointer class. Q_DISABLE_COPY(KDbConnection) friend class KDbConnectionPrivate; friend class KDbAlterTableHandler; friend class KDbConnectionProxy; friend class KDbCursor; friend class KDbDriver; friend class KDbProperties; //!< for setError() friend class KDbQuerySchema; friend class KDbQuerySchemaPrivate; friend class KDbTableSchemaChangeListenerPrivate; friend class KDbTableSchema; //!< for removeMe() }; Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::QueryRecordOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::AlterTableNameOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::CreateTableOptions) #endif diff --git a/src/KDbConnectionProxy.h b/src/KDbConnectionProxy.h index ec0d3541..b50aad7d 100644 --- a/src/KDbConnectionProxy.h +++ b/src/KDbConnectionProxy.h @@ -1,409 +1,409 @@ /* This file is part of the KDE project Copyright (C) 2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTIONPROXY_H #define KDB_CONNECTIONPROXY_H #include //! The KDbConnectionProxy class gives access to protected (low-level) API of KDbConnection /** * The connection object specified in constructor of the proxy is called a parent connection. * All inherited methods of the KDbConnection API call equivalent methods of the parent * connection. The KDbConnectionProxy class also provides non-virtual methods that are * equivalent to KDbConnection ones. These KDbConnection's equivalent methods are called * by the proxy too. * * Example use of this class is Kexi's database database migration plugins when the source * database is only accessibly using low-level routines. */ class KDB_EXPORT KDbConnectionProxy : protected KDbConnection { public: //! Creates a proxy object for parent @a connection. //! @a connection must not be @c nullptr. //! It is owned by this proxy unless setConnectionIsOwned(false) is called. explicit KDbConnectionProxy(KDbConnection *connection); //! Deletes this proxy. Owned connection is closed and destroyed. ~KDbConnectionProxy() override; //! @return parent connection for this proxy KDbConnection *parentConnection(); //! @overload KDbConnection *parentConnection() const KDbConnection *parentConnection() const; //! Control owhership of parent connection that is assigned to this proxy. //! Owned connection is closed and destroyed upon destruction of the KDbConnectionProxy //! object. void setParentConnectionIsOwned(bool set); KDbConnectionData data() const; KDbDriver* driver() const; bool connect(); bool isConnected() const; bool isDatabaseUsed() const; KDbConnectionOptions *options(); void clearResult(); KDbResult result() const; KDbResultable resultable() const; bool disconnect(); QStringList databaseNames(bool also_system_db = false); bool databaseExists(const QString &dbName, bool ignoreErrors = true); bool createDatabase(const QString &dbName); bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr); bool closeDatabase(); QString currentDatabase() const; bool dropDatabase(const QString &dbName = QString()); QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr); QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr); tristate containsTable(const QString &tableName); KDbServerVersionInfo serverVersion() const; KDbVersionInfo databaseVersion() const; KDbProperties databaseProperties() const; QList tableIds(bool* ok = nullptr); QList queryIds(bool* ok = nullptr); QList objectIds(int objectType, bool* ok = nullptr); KDbTransaction beginTransaction(); bool commitTransaction(KDbTransaction trans = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); bool rollbackTransaction(KDbTransaction trans = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); KDbTransaction defaultTransaction() const; void setDefaultTransaction(const KDbTransaction& trans); QList transactions(); bool autoCommit() const; bool setAutoCommit(bool on); KDbEscapedString escapeString(const QString& str) const override; KDbCursor *prepareQuery(const KDbEscapedString &sql, KDbCursor::Options options = KDbCursor::Option::None) override; KDbCursor *prepareQuery(KDbQuerySchema *query, KDbCursor::Options options = KDbCursor::Option::None) override; KDbCursor *prepareQuery(KDbTableSchema *table, KDbCursor::Options options = KDbCursor::Option::None); KDbCursor *executeQuery(const KDbEscapedString &sql, KDbCursor::Options options = KDbCursor::Option::None); KDbCursor* executeQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options = KDbCursor::Option::None); KDbCursor* executeQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None); KDbCursor* executeQuery(KDbTableSchema* table, KDbCursor::Options options = KDbCursor::Option::None); bool deleteCursor(KDbCursor *cursor); KDbTableSchema* tableSchema(int tableId); KDbTableSchema* tableSchema(const QString& tableName); KDbQuerySchema* querySchema(int queryId); KDbQuerySchema* querySchema(const QString& queryName); bool setQuerySchemaObsolete(const QString& queryName); tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); tristate querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0); bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); bool queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column = 0); tristate resultExists(const KDbEscapedString &sql, QueryRecordOptions options = QueryRecordOption::Default); tristate isEmpty(KDbTableSchema* table); KDbEscapedString recentSqlString() const override; //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args) bool insertRecord(KDbTableSchema* tableSchema args) #define H_INS_REC_ALL \ H_INS_REC(A); \ H_INS_REC(A A); \ H_INS_REC(A A A); \ H_INS_REC(A A A A); \ H_INS_REC(A A A A A); \ H_INS_REC(A A A A A A); \ H_INS_REC(A A A A A A A); \ H_INS_REC(A A A A A A A A) H_INS_REC_ALL; #undef H_INS_REC #define H_INS_REC(args) bool insertRecord(KDbFieldList* fields args) H_INS_REC_ALL; #undef H_INS_REC_ALL #undef H_INS_REC #undef A bool insertRecord(KDbTableSchema* tableSchema, const QList& values); bool insertRecord(KDbFieldList* fields, const QList& values); bool createTable(KDbTableSchema *tableSchema, CreateTableOptions options = CreateTableOption::Default); KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData); KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData); tristate dropTable(KDbTableSchema* tableSchema); tristate dropTable(const QString& tableName); tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema); bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, AlterTableNameOptions options = AlterTableNameOption::Default); bool dropQuery(KDbQuerySchema* querySchema); bool dropQuery(const QString& queryName); bool removeObject(int objId); KDbField* findSystemFieldName(const KDbFieldList& fieldlist); QString anyAvailableDatabaseName() override; void setAvailableDatabaseName(const QString& dbName); bool useTemporaryDatabaseIfNeeded(QString* name); - QSharedPointer prepareSql(const KDbEscapedString& sql) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT QSharedPointer prepareSql(const KDbEscapedString& sql); bool executeSql(const KDbEscapedString& sql); bool storeObjectData(KDbObject* object); bool storeNewObjectData(KDbObject* object); //! @since 3.1 tristate loadObjectData(int type, int id, KDbObject* object); tristate loadObjectData(int type, const QString& name, KDbObject* object); tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString()); bool storeDataBlock(int objectID, const QString &dataString, const QString& dataID = QString()); bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString()); bool removeDataBlock(int objectID, const QString& dataID = QString()); KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames = QStringList()); bool isInternalTableSchema(const QString& tableName); QString escapeIdentifier(const QString& id) const override; bool drv_connect() override; bool drv_disconnect() override; bool drv_getServerVersion(KDbServerVersionInfo* version) override; /** * @since 3.2 */ QStringList drv_getTableNames(bool *ok) override; tristate drv_containsTable(const QString &tableName) override; bool drv_createTable(const KDbTableSchema& tableSchema) override; bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) override; bool drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) override; bool drv_dropTable(const QString& tableName) override; tristate dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema); bool setupObjectData(const KDbRecordData& data, KDbObject* object); KDbField* setupField(const KDbRecordData& data); - KDbSqlResult* drv_prepareSql(const KDbEscapedString& sql) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbSqlResult *drv_prepareSql(const KDbEscapedString &sql) override; bool drv_executeSql(const KDbEscapedString& sql) override; bool drv_getDatabasesList(QStringList* list) override; bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true) override; bool drv_createDatabase(const QString &dbName = QString()) override; bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) override; bool drv_closeDatabase() override; bool drv_isDatabaseUsed() const override; bool drv_dropDatabase(const QString &dbName = QString()) override; bool drv_createTable(const QString& tableName) override; KDbTransactionData* drv_beginTransaction() override; bool drv_commitTransaction(KDbTransactionData* trans) override; bool drv_rollbackTransaction(KDbTransactionData* trans) override; bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) override; bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) override; bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) override; bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) override; bool drv_setAutoCommit(bool on) override; KDbPreparedStatementInterface* prepareStatementInternal() override; bool beginAutoCommitTransaction(KDbTransactionGuard* tg); bool commitAutoCommitTransaction(const KDbTransaction& trans); bool rollbackAutoCommitTransaction(const KDbTransaction& trans); bool checkConnected(); bool checkIsDatabaseUsed(); bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false); bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false); bool deleteAllRecords(KDbQuerySchema* query); bool checkIfColumnExists(KDbCursor *cursor, int column); tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, QueryRecordOptions options); tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list, KDbQuerySchema* query, const QList* params, int column, bool (*filterFunction)(const QString&)); KDbCursor* executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params); bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema); bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema); bool storeMainFieldSchema(KDbField *field); private: Q_DISABLE_COPY(KDbConnectionProxy) class Private; Private * const d; }; #endif diff --git a/src/KDbConnection_p.h b/src/KDbConnection_p.h index df52d3d1..ec1e7df1 100644 --- a/src/KDbConnection_p.h +++ b/src/KDbConnection_p.h @@ -1,213 +1,213 @@ /* This file is part of the KDE project Copyright (C) 2005 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTION_P_H #define KDB_CONNECTION_P_H #include "KDbConnectionData.h" #include "KDbConnection.h" #include "KDbConnectionOptions.h" #include "kdb_export.h" #include "KDbParser.h" #include "KDbProperties.h" #include "KDbQuerySchema_p.h" #include "KDbVersionInfo.h" //! Interface for accessing connection's internal result, for use by drivers. class KDB_EXPORT KDbConnectionInternal { public: explicit KDbConnectionInternal(KDbConnection *conn); KDbConnection* const connection; private: Q_DISABLE_COPY(KDbConnectionInternal) }; class KDbConnectionPrivate { Q_DECLARE_TR_FUNCTIONS(KDbConnectionPrivate) public: KDbConnectionPrivate(KDbConnection* const conn, KDbDriver *drv, const KDbConnectionData& _connData, const KDbConnectionOptions &_options); ~KDbConnectionPrivate(); void deleteAllCursors(); void errorInvalidDBContents(const QString& details); QString strItIsASystemObject() const; inline KDbParser *parser() { return m_parser ? m_parser : (m_parser = new KDbParser(conn)); } inline KDbTableSchema* table(const QString& name) const { return m_tablesByName.value(name); } inline KDbTableSchema* table(int id) const { return m_tables.value(id); } //! used just for removing system KDbTableSchema objects on db close. inline QSet internalKDbTables() const { return m_internalKDbTables; } /*! Allocates all needed table KDb system objects for kexi__* KDb library's system tables schema. These objects are used internally in this connection and are added to list of tables (by name, not by id because these have no ids). */ void setupKDbSystemSchema(); void insertTable(KDbTableSchema* tableSchema); /*! Removes table schema having identifier @a id from internal structures and destroys it. Does not make any change at the backend. */ void removeTable(int id); void takeTable(KDbTableSchema* tableSchema); void renameTable(KDbTableSchema* tableSchema, const QString& newName); void changeTableId(KDbTableSchema* tableSchema, int newId); void clearTables(); inline KDbQuerySchema* query(const QString& name) const { return m_queriesByName.value(name); } inline KDbQuerySchema* query(int id) const { return m_queries.value(id); } void insertQuery(KDbQuerySchema* query); /*! Removes @a querySchema from internal structures and destroys it. Does not make any change at the backend. */ void removeQuery(KDbQuerySchema* querySchema); void setQueryObsolete(KDbQuerySchema* query); void clearQueries(); /*! @return a full table schema for a table retrieved using 'kexi__*' system tables. Connection keeps ownership of the returned object. Used internally by tableSchema() methods. On failure deletes @a table and returns @c nullptr. */ - KDbTableSchema* setupTableSchema(KDbTableSchema *table) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbTableSchema *setupTableSchema(KDbTableSchema *table); /*! @return a full query schema for a query using 'kexi__*' system tables. Connection keeps ownership of the returned object. Used internally by querySchema() methods. On failure deletes @a query and returns @c nullptr. */ - KDbQuerySchema* setupQuerySchema(KDbQuerySchema *query) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbQuerySchema *setupQuerySchema(KDbQuerySchema *query); //! @return cached fields expanded information for @a query KDbQuerySchemaFieldsExpanded *fieldsExpanded(const KDbQuerySchema *query); //! Inserts cached fields expanded information for @a query void insertFieldsExpanded(const KDbQuerySchema *query, KDbQuerySchemaFieldsExpanded *cache); //! Removes cached fields expanded information for @a query void removeFieldsExpanded(const KDbQuerySchema *query); KDbConnection* const conn; //!< The @a KDbConnection instance this @a KDbConnectionPrivate belongs to. KDbConnectionData connData; //!< the @a KDbConnectionData used within that connection. //! True for read only connection. Used especially for file-based drivers. KDbConnectionOptions options; //!< The driver this @a KDbConnection instance uses. KDbDriver * const driver; /*! Default transaction handle. If transactions are supported: Any operation on database (e.g. inserts) that is started without specifying transaction context, will be performed in the context of this transaction. */ KDbTransaction default_trans; QList transactions; QHash* > tableSchemaChangeListeners; QHash* > queryTableSchemaChangeListeners; //! Used in KDbConnection::setQuerySchemaObsolete( const QString& queryName ) //! to collect obsolete queries. THese are deleted on connection deleting. QSet obsoleteQueries; //! server version information for this connection. KDbServerVersionInfo serverVersion; //! Database version information for this connection. KDbVersionInfo databaseVersion; KDbParser *m_parser = nullptr; //! cursors created for this connection QSet cursors; //! Database properties KDbProperties dbProperties; QString availableDatabaseName; //!< used by anyAvailableDatabaseName() QString usedDatabase; //!< database name that is opened now (the currentDatabase() name) //! true if rollbackTransaction() and commitTransaction() shouldn't remove //! the transaction object from 'transactions' list; used by closeDatabase() bool dontRemoveTransactions = false; //! used to avoid endless recursion between useDatabase() and databaseExists() //! when useTemporaryDatabaseIfNeeded() works bool skipDatabaseExistsCheckInUseDatabase = false; /*! Used when single transactions are only supported (KDbDriver::SingleTransactions). True value means default KDbTransaction has been started inside connection object (by beginAutoCommitTransaction()), otherwise default transaction has been started outside of the object (e.g. before createTable()), so we shouldn't autocommit the transaction in commitAutoCommitTransaction(). Also, beginAutoCommitTransaction() doesn't restarts transaction if default_trans_started_inside is false. Such behavior allows user to execute a sequence of actions like CREATE TABLE...; INSERT DATA...; within a single transaction and commit it or rollback by hand. */ bool defaultTransactionStartedInside = false; bool isConnected = false; bool autoCommit = true; bool insideCloseDatabase = false; //!< helper: true while closeDatabase() is executed private: //! Table schemas retrieved on demand with tableSchema() QHash m_tables; QHash m_tablesByName; //! used just for removing system KDbTableSchema objects on db close. QSet m_internalKDbTables; //! Query schemas retrieved on demand with querySchema() QHash m_queries; QHash m_queriesByName; KDbUtils::AutodeletedHash m_fieldsExpandedCache; Q_DISABLE_COPY(KDbConnectionPrivate) }; #endif diff --git a/src/KDbFieldList.h b/src/KDbFieldList.h index bea6445c..a7c18ea3 100644 --- a/src/KDbFieldList.h +++ b/src/KDbFieldList.h @@ -1,197 +1,197 @@ /* This file is part of the KDE project Copyright (C) 2003-2010 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_FIELDLIST_H #define KDB_FIELDLIST_H #include #include #include "KDbGlobal.h" #include "KDbField.h" #include "KDbEscapedString.h" class KDbConnection; /*! Helper class that stores list of fields. */ class KDB_EXPORT KDbFieldList { public: /*! Creates empty list of fields. If @a owner is true, the list will be owner of any added field, what means that these field will be removed on the list destruction. Otherwise, the list just points any field that was added. @see isOwner() */ explicit KDbFieldList(bool owner = false); /*! Copy constructor. If @a deepCopyFields is true, all fields are deeply copied, else only pointer are copied. Reimplemented in KDbQuerySchema constructor. */ explicit KDbFieldList(const KDbFieldList& fl, bool deepCopyFields = true); /*! Destroys the list. If the list owns fields (see constructor), these are also deleted. */ virtual ~KDbFieldList(); /*! @return number of fields in the list. */ int fieldCount() const; /*! @return true if the list is empty. */ bool isEmpty() const; /*! Adds @a field at the and of field list. */ bool addField(KDbField *field); /*! Inserts @a field into a specified @a index position. @c false is returned if @a field is @c nullptr or @a index is invalid. Note: You can reimplement this method but you should still call this implementation in your subclass. */ virtual bool insertField(int index, KDbField *field); /*! Removes field from the field list and deletes it. Use with care. Note: You can reimplement this method but you should still call this implementation in your subclass. @return false if this field does not belong to this list. */ virtual bool removeField(KDbField *field); /*! Moves fiels @a field from its current position to new position @a newIndex. If @a newIndex value is greater than fieldCount()-1, it is appended. @return @c false if this field does not belong to this list or is @c nullptr. */ virtual bool moveField(KDbField *field, int newIndex); /*! @return field id or @c nullptr if there is no such a field. */ virtual KDbField* field(int id); /*! @overload KDbField* field(int id) */ virtual const KDbField* field(int id) const; /*! @return field with name @a name or @c nullptr if there is no such a field. */ virtual KDbField* field(const QString& name); /*! @overload . DbField* field(const QString& name) const */ virtual const KDbField* field(const QString& name) const; /*! @return true if this list contains given @a field. */ bool hasField(const KDbField& field) const; /*! @return first occurrence of @a field in the list or -1 if this list does not contain this field. */ int indexOf(const KDbField& field) const; /*! @return list of field names for this list. */ QStringList names() const; //! @return iterator for fields KDbField::ListIterator fieldsIterator() const; //! @return iterator for fields KDbField::ListIterator fieldsIteratorConstEnd() const; //! @return list of fields KDbField::List *fields(); //! @overload const KDbField::List* fields() const; /*! @return list of autoincremented fields. The list is owned by this KDbFieldList object. */ KDbField::List* autoIncrementFields() const; /*! @return true if fields in the list are owned by this list. */ bool isOwner() const; /*! Removes all fields from the list. */ virtual void clear(); /*! Creates and returns a list that contain fields selected by name. At least one field (exising on this list) should be selected, otherwise 0 is returned. Returned KDbFieldList object is not owned by any parent (so you need to destroy yourself) and KDbField objects included in it are not owned by it (but still as before, by 'this' object). Returned list can be usable e.g. as argument for KDbConnection::insertRecord(). 0 is returned if at least one name cannot be found. */ - KDbFieldList* subList(const QString& n1, const QString& n2 = QString(), + Q_REQUIRED_RESULT KDbFieldList *subList(const QString& n1, const QString& n2 = QString(), const QString& n3 = QString(), const QString& n4 = QString(), const QString& n5 = QString(), const QString& n6 = QString(), const QString& n7 = QString(), const QString& n8 = QString(), const QString& n9 = QString(), const QString& n10 = QString(), const QString& n11 = QString(), const QString& n12 = QString(), const QString& n13 = QString(), const QString& n14 = QString(), const QString& n15 = QString(), const QString& n16 = QString(), const QString& n17 = QString(), const QString& n18 = QString() - ) Q_REQUIRED_RESULT; + ); /*! Like above, but for QStringList. */ - KDbFieldList* subList(const QStringList& list) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbFieldList *subList(const QStringList &list); /*! @overload subList(const QStringList&) */ - KDbFieldList* subList(const QList& list) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbFieldList *subList(const QList &list); /*! Like above, but with a list of field indices */ - KDbFieldList* subList(const QList& list) Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbFieldList *subList(const QList &list); /*! @return a string that is a result of all field names concatenated and with @a separator. This is usable e.g. as argument like "field1,field2" for "INSERT INTO (xxx) ..". The result of this method is effectively cached, and it is invalidated when set of fields changes (e.g. using clear() or addField()). @a tableOrAlias, if provided is prepended to each field, so the resulting names will be in form tableOrAlias.fieldName. This option is used for building queries with joins, where fields have to be spicified without ambiguity. See @ref KDbConnection::selectStatement() for example use. @a escapingType can be used to alter default escaping type. If @a conn is not provided for DriverEscaping, no escaping is performed. */ KDbEscapedString sqlFieldsList(KDbConnection *conn, const QString& separator = QLatin1String(","), const QString& tableOrAlias = QString(), KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; /*! Like above, but this is convenient static function, so you can pass any @a list here. */ static KDbEscapedString sqlFieldsList(const KDbField::List& list, KDbConnection *conn, const QString& separator = QLatin1String(","), const QString& tableOrAlias = QString(), KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping); /*! Renames field @a oldName to @a newName. @c false is returned if field with @a oldName name does not exist or field with @a newName name already exists. @note Do not use this for physical renaming columns. Use KDbAlterTableHandler instead. */ bool renameField(const QString& oldName, const QString& newName); //! @overload bool renameField(KDbField *field, const QString& newName); private: class Private; Private * const d; }; //! Sends information about field list @a list to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbFieldList& list); #endif diff --git a/src/KDbOrderByColumn.h b/src/KDbOrderByColumn.h index 96c6cdb6..7c9a218a 100644 --- a/src/KDbOrderByColumn.h +++ b/src/KDbOrderByColumn.h @@ -1,252 +1,252 @@ /* This file is part of the KDE project Copyright (C) 2003-2018 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_ORDERBYCOLUMN_H #define KDB_ORDERBYCOLUMN_H #include "KDbEscapedString.h" #include "KDbGlobal.h" class KDbConnection; class KDbField; class KDbQueryColumnInfo; class KDbQuerySchema; //! @short KDbOrderByColumn provides information about a single query column used for sorting /*! The column can be expression or table field. */ class KDB_EXPORT KDbOrderByColumn { public: //! Column sort order //! @since 3.1 enum class SortOrder { Ascending = Qt::AscendingOrder, Descending = Qt::DescendingOrder }; //! Creates an empty information about a single query column. KDbOrderByColumn(); //! Creates a copy of the @a other //! @since 3.1 KDbOrderByColumn(const KDbOrderByColumn &other); //! Creates information about a single query column @a column used for sorting. explicit KDbOrderByColumn(KDbQueryColumnInfo* column, SortOrder order = SortOrder::Ascending, int pos = -1); //! Like above but used when the field @a field is not present on the list of columns. //! (e.g. SELECT a FROM t ORDER BY b; where T is a table with fields (a,b)). explicit KDbOrderByColumn(KDbField* field, SortOrder order = SortOrder::Ascending); ~KDbOrderByColumn(); /*! @return copy of this KDbOrderByColumn object. @a fromQuery and @a toQuery is needed if column() is assigned to this info. Then, column info within @a toQuery will be assigned to the new KDbOrderByColumn object, corresponding to column() from "this" KDbOrderByColumn object. */ - KDbOrderByColumn *copy(KDbConnection *conn, KDbQuerySchema *fromQuery, - KDbQuerySchema *toQuery) const Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbOrderByColumn *copy(KDbConnection *conn, KDbQuerySchema *fromQuery, + KDbQuerySchema *toQuery) const; //! A column to sort. KDbQueryColumnInfo* column() const; /*! A helper for column() that allows you to know that sorting column was defined by providing its position. -1 by default. Example query: SELECT a, b FROM T ORDER BY 2 */ int position() const; //! A field to sort, used only in case when the second constructor was used. KDbField *field() const; //! @return sort order for the column KDbOrderByColumn::SortOrder sortOrder() const; //! Assigns @a other to this object returns a reference to this object. //! @since 3.1 KDbOrderByColumn& operator=(const KDbOrderByColumn &other); //! @return true if this column is the same as @a col bool operator==(const KDbOrderByColumn& col) const; //! @return @c true if this object is not equal to @a other; otherwise returns @c false. //! @since 3.1 inline bool operator!=(const KDbOrderByColumn &other) const { return !operator==(other); } /** Return an SQL string like "name ASC" or "2 DESC" usable for building an SQL statement * * If @a includeTableNames is @c true fields that are related to a table are * printed as "tablename.fieldname". * * @a escapingType can be used to alter default escaping type. * If @a conn is not provided for DriverEscaping, no escaping is performed. * If @a query is provided, it can be used to obtain alias information. * * @since 3.2 */ KDbEscapedString toSqlString(bool includeTableName, KDbConnection *conn, KDbQuerySchema *query, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; /*! @overload @deprecated since 3.2, use overload that also takes query schema */ KDB_DEPRECATED KDbEscapedString toSqlString(bool includeTableName = true, KDbConnection *conn = nullptr, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; //! Converts @a order to Qt::SortOrder type inline static Qt::SortOrder toQt(SortOrder order) { return static_cast(order); } //! Converts @a order to SortOrder type inline static SortOrder fromQt(Qt::SortOrder order) { return static_cast(order); } private: class Private; Private * const d; }; //! @short KDbOrderByColumnList provides list of sorted columns for a query schema class KDB_EXPORT KDbOrderByColumnList { public: /*! Constructs empty list of ordered columns. */ KDbOrderByColumnList(); /*! A copy constructor. */ KDbOrderByColumnList(const KDbOrderByColumnList& other, KDbConnection *conn, KDbQuerySchema* fromQuery, KDbQuerySchema* toQuery); ~KDbOrderByColumnList(); //! @return @c true if this object is equal to @a other; otherwise returns @c false. //! @since 3.1 bool operator==(const KDbOrderByColumnList &other) const; //! @return @c true if this object is not equal to @a other; otherwise returns @c false. //! @since 3.1 inline bool operator!=(const KDbOrderByColumnList &other) const { return !operator==(other); } //! Returns column with given index. //! @since 3.1 const KDbOrderByColumn* value(int index) const; //! @overload KDbOrderByColumn* value(int index); /*! Appends multiple fields for sorting. @a querySchema is used to find appropriate field or alias name. @return false if there is at least one name for which a field or alias name does not exist (all the newly appended fields are removed in this case) Returns @c false if @a querySchema is @c nullptr. */ bool appendFields(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& field1, KDbOrderByColumn::SortOrder order1 = KDbOrderByColumn::SortOrder::Ascending, const QString& field2 = QString(), KDbOrderByColumn::SortOrder order2 = KDbOrderByColumn::SortOrder::Ascending, const QString& field3 = QString(), KDbOrderByColumn::SortOrder order3 = KDbOrderByColumn::SortOrder::Ascending, const QString& field4 = QString(), KDbOrderByColumn::SortOrder order4 = KDbOrderByColumn::SortOrder::Ascending, const QString& field5 = QString(), KDbOrderByColumn::SortOrder order5 = KDbOrderByColumn::SortOrder::Ascending); /*! Appends column @a columnInfo. Does nothing if @a columnInfo is @c nullptr. */ void appendColumn(KDbQueryColumnInfo* columnInfo, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends a field @a field. Read documentation of @ref KDbOrderByColumn(KDbField* field, SortOrder order) for more info. Does nothing if @a field is @c nullptr. */ void appendField(KDbField* field, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends field with a name @a field. @return @c true on successful appending, and @c false if there is no such field or alias name in the @a querySchema. Returns @c false if @a querySchema is @c nullptr. */ bool appendField(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& fieldName, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends a column that is at position @a pos (counted from 0). @return true on successful adding and false if there is no such position @a pos. Returns @c false if @a querySchema is @c nullptr. */ bool appendColumn(KDbConnection *conn, KDbQuerySchema* querySchema, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending, int pos = -1); /*! @return true if the list is empty. */ bool isEmpty() const; /*! @return number of elements of the list. */ int count() const; /*! Removes all elements from the list (deletes them). */ void clear(); /*! Returns an STL-style iterator pointing to the first column in the list. */ QList::Iterator begin(); /*! Returns an STL-style iterator pointing to the imaginary item after the last column * in the list. */ QList::Iterator end(); /*! Returns an const STL-style iterator pointing to the first column in the list. */ QList::ConstIterator constBegin() const; /*! Returns a const STL-style iterator pointing to the imaginary item after the last column * in the list. */ QList::ConstIterator constEnd() const; /** Return an SQL string like "name ASC, 2 DESC" usable for building an SQL statement * * If @a includeTableNames is @c true (the default) fields that are related to a table are * printed as "tablename.fieldname". * * @a escapingType can be used to alter default escaping type. * If @a conn is not provided for DriverEscaping, no escaping is performed. * If @a query is provided, it can be used to obtain alias information. * * @since 3.2 */ KDbEscapedString toSqlString(bool includeTableNames, KDbConnection *conn, KDbQuerySchema *query, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; /*! @overload @deprecated since 3.2, use overload that also takes query schema */ KDB_DEPRECATED KDbEscapedString toSqlString(bool includeTableNames = true, KDbConnection *conn = nullptr, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; private: class Private; Private * const d; Q_DISABLE_COPY(KDbOrderByColumnList) }; //! Sends order-by-column information @a order to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbOrderByColumn& order); //! Sends order-by-column-list information @a list to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbOrderByColumnList& list); #endif diff --git a/src/drivers/mysql/MysqlConnection.h b/src/drivers/mysql/MysqlConnection.h index 5583cc89..cfe17fcf 100644 --- a/src/drivers/mysql/MysqlConnection.h +++ b/src/drivers/mysql/MysqlConnection.h @@ -1,82 +1,84 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Joseph Wenninger Copyright (C) 2004-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_MYSQLCONNECTION_H #define KDB_MYSQLCONNECTION_H #include #include "KDbConnection.h" class MysqlConnectionInternal; /*! @short Provides database connection, allowing queries and data modification. */ class MysqlConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(MysqlConnection) public: ~MysqlConnection() override; - KDbCursor *prepareQuery(const KDbEscapedString &sql, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; - KDbCursor *prepareQuery(KDbQuerySchema *query, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(const KDbEscapedString &sql, + KDbCursor::Options options + = KDbCursor::Option::None) override; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, + KDbCursor::Options options + = KDbCursor::Option::None) override; - KDbPreparedStatementInterface *prepareStatementInternal() override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbPreparedStatementInterface *prepareStatementInternal() override; protected: /*! Used by driver */ MysqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); bool drv_connect() override; bool drv_getServerVersion(KDbServerVersionInfo* version) override; bool drv_disconnect() override; bool drv_getDatabasesList(QStringList* list) override; //! reimplemented using "SHOW DATABASES LIKE..." because MySQL stores db names in lower case. bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true) override; bool drv_createDatabase(const QString &dbName = QString()) override; bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) override; bool drv_closeDatabase() override; bool drv_dropDatabase(const QString &dbName = QString()) override; - KDbSqlResult* drv_prepareSql(const KDbEscapedString& sql) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbSqlResult *drv_prepareSql(const KDbEscapedString &sql) override; bool drv_executeSql(const KDbEscapedString& sql) override; //! Implemented for KDbResultable QString serverResultName() const override; //! @todo move this somewhere to low level class (MIGRATION?) tristate drv_containsTable(const QString &tableName) override; void storeResult(); MysqlConnectionInternal* const d; friend class MysqlDriver; friend class MysqlCursorData; friend class MysqlSqlResult; private: Q_DISABLE_COPY(MysqlConnection) }; #endif diff --git a/src/drivers/mysql/MysqlConnection_p.h b/src/drivers/mysql/MysqlConnection_p.h index 23154525..05d3da00 100644 --- a/src/drivers/mysql/MysqlConnection_p.h +++ b/src/drivers/mysql/MysqlConnection_p.h @@ -1,228 +1,229 @@ /* This file is part of the KDE project Copyright (C) 2004 Martin Ellis Copyright (C) 2004-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_MYSQLCONNECTION_P_H #define KDB_MYSQLCONNECTION_P_H #include "KDbConnection_p.h" #include "MysqlConnection.h" #include "KDbResult.h" #include "KDbSqlField.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" #include "KDbSqlString.h" #include class KDbConnectionData; class KDbEscapedString; //! Internal MySQL connection data. /*! Provides a low-level API for accessing MySQL databases, that can be shared by any module that needs direct access to the underlying database. Used by the KDb and migration drivers. @todo fix the above note about migration... */ class MysqlConnectionInternal : public KDbConnectionInternal { public: explicit MysqlConnectionInternal(KDbConnection* connection); virtual ~MysqlConnectionInternal(); //! Connects to a MySQL database /*! Connects to the MySQL server on host as the given user using the specified password. If host is "localhost", then a socket on the local file system can be specified to connect to the server (several defaults will be tried if none is specified). If the server is on a remote machine, then a port is the port that the remote server is listening on. */ bool db_connect(const KDbConnectionData& data); //! Disconnects from the database bool db_disconnect(); //! Selects a database that is about to be used bool useDatabase(const QString &dbName = QString()); //! Executes query for a raw SQL statement @a sql using mysql_real_query() bool executeSql(const KDbEscapedString& sql); static QString serverResultName(MYSQL *mysql); void storeResult(KDbResult *result); MYSQL *mysql; bool mysql_owned; //!< true if mysql pointer should be freed on destruction int res; //!< result code of last operation on server //! Get lower_case_table_name variable value so we know if there's case sensitivity supported for table and database names bool lowerCaseTableNames; //! Server version known after successfull connection. //! Equal to major_version*10000 + release_level*100 + sub_version //! 0 if not known. //! See https://dev.mysql.com/doc/refman/5.7/en/mysql-get-server-version.html //! @todo store in Connection base class as a property or as public server info unsigned long serverVersion; private: Q_DISABLE_COPY(MysqlConnectionInternal) }; //! Internal MySQL cursor data. /*! Provides a low-level abstraction for iterating over MySql result sets. */ class MysqlCursorData : public MysqlConnectionInternal { public: explicit MysqlCursorData(KDbConnection* connection); ~MysqlCursorData() override; MYSQL_RES *mysqlres; MYSQL_ROW mysqlrow; unsigned long *lengths; qint64 numRows; private: Q_DISABLE_COPY(MysqlCursorData) }; class MysqlSqlField : public KDbSqlField { public: inline MysqlSqlField(MYSQL_FIELD *f) : data(f) { } //! @return column name inline QString name() override { //! @todo UTF8? return QString::fromLatin1(data->name); } inline int type() override { return data->type; } inline int length() override { return data->length; } MYSQL_FIELD *data; private: Q_DISABLE_COPY(MysqlSqlField) }; class MysqlSqlRecord : public KDbSqlRecord { public: inline MysqlSqlRecord(MYSQL_ROW r, unsigned long* len) : record(r), lengths(len) { } inline ~MysqlSqlRecord() override { } inline QString stringValue(int index) override { return QString::fromUtf8(record[index], lengths[index]); } inline KDbSqlString cstringValue(int index) override { return KDbSqlString(record[index], lengths[index]); } inline QByteArray toByteArray(int index) override { return QByteArray(record[index], lengths[index]); } private: MYSQL_ROW record; unsigned long* lengths; Q_DISABLE_COPY(MysqlSqlRecord) }; class MysqlSqlResult : public KDbSqlResult { public: inline MysqlSqlResult(MysqlConnection *c, MYSQL_RES *d) : conn(c), data(d), fields(nullptr) { Q_ASSERT(c); } inline ~MysqlSqlResult() override { if (data) { mysql_free_result(data); } } inline KDbConnection *connection() const override { return conn; } inline int fieldsCount() override { return data ? mysql_num_fields(data) : 0; } - inline KDbSqlField *field(int index) override Q_REQUIRED_RESULT { + inline Q_REQUIRED_RESULT KDbSqlField *field(int index) override { if (!fields) { if (!data) { return nullptr; } fields = mysql_fetch_fields(data); } return new MysqlSqlField(fields + index); } - KDbField *createField(const QString &tableName, int index) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbField *createField(const QString &tableName, int index) override; - inline QSharedPointer fetchRecord() override Q_REQUIRED_RESULT { + inline Q_REQUIRED_RESULT QSharedPointer fetchRecord() override + { QSharedPointer record; MYSQL_ROW row = data ? mysql_fetch_row(data) : nullptr; if (!row) { return record; } unsigned long* lengths = mysql_fetch_lengths(data); record.reset(new MysqlSqlRecord(row, lengths)); return record; } inline KDbResult lastResult() override { KDbResult res; const int err = mysql_errno(conn->d->mysql); if (err != 0) { res.setCode(ERR_OTHER); res.setServerErrorCode(err); } return res; } inline quint64 lastInsertRecordId() override { //! @todo return static_cast(mysql_insert_id(conn->d->mysql)); } private: //! @return a KDb type for MySQL type //! @todo prompt user if necessary? KDbField::Type type(const QString& tableName, MysqlSqlField *field); //! @return a KDb BLOB-related type for MySQL type /*! Distinguishes between a BLOB and a TEXT types. MySQL uses the same field type to identify BLOB and TEXT fields. This method queries the server to find out if a field is a binary field or a text field. It also considers the length of CHAR and VARCHAR fields to see whether Text or LongText is the appropriate Kexi field type. Assumes fld is a CHAR, VARCHAR, one of the BLOBs or TEXTs. Returns KDbField::Text, KDbField::LongText or KDbField::BLOB. */ KDbField::Type blobType(const QString& tableName, MysqlSqlField *field); MysqlConnection * const conn; MYSQL_RES * const data; MYSQL_FIELD *fields; Q_DISABLE_COPY(MysqlSqlResult) }; #endif diff --git a/src/drivers/mysql/MysqlPreparedStatement.h b/src/drivers/mysql/MysqlPreparedStatement.h index a7702f3b..26f11181 100644 --- a/src/drivers/mysql/MysqlPreparedStatement.h +++ b/src/drivers/mysql/MysqlPreparedStatement.h @@ -1,58 +1,58 @@ /* This file is part of the KDE project Copyright (C) 2006-2010 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_MYSQLPREPAREDSTATEMENT_H #define KDB_MYSQLPREPAREDSTATEMENT_H #include "KDbPreparedStatementInterface.h" #include "MysqlConnection_p.h" //! @todo 3.1 - unfinished: #define KDB_USE_MYSQL_STMT; for 3.0 we're using unoptimized version /*! Implementation of prepared statements for MySQL driver. */ class MysqlPreparedStatement : public KDbPreparedStatementInterface, public MysqlConnectionInternal { public: explicit MysqlPreparedStatement(MysqlConnectionInternal* conn); ~MysqlPreparedStatement() override; private: bool prepare(const KDbEscapedString& sql) override; - QSharedPointer execute(KDbPreparedStatement::Type type, + Q_REQUIRED_RESULT QSharedPointer execute(KDbPreparedStatement::Type type, const KDbField::List &selectFieldList, KDbFieldList *insertFieldList, - const KDbPreparedStatementParameters ¶meters) override Q_REQUIRED_RESULT; + const KDbPreparedStatementParameters ¶meters) override; bool init(); void done(); #ifdef KDB_USE_MYSQL_STMT bool bindValue(KDbField *field, const QVariant& value, int arg); int m_realParamCount; MYSQL_STMT *m_statement; MYSQL_BIND *m_mysqlBind; #endif KDbEscapedString m_tempStatementString; bool m_resetRequired; Q_DISABLE_COPY(MysqlPreparedStatement) }; #endif diff --git a/src/drivers/postgresql/PostgresqlConnection.h b/src/drivers/postgresql/PostgresqlConnection.h index 8e308941..f6aed510 100644 --- a/src/drivers/postgresql/PostgresqlConnection.h +++ b/src/drivers/postgresql/PostgresqlConnection.h @@ -1,106 +1,108 @@ /* This file is part of the KDE project Copyright (C) 2003 Adam Pigg Copyright (C) 2010-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_POSTGRESQLCONNECTION_H #define KDB_POSTGRESQLCONNECTION_H #include "KDbConnection.h" #include "KDbTransactionData.h" #include class PostgresqlConnectionInternal; //! @internal class PostgresqlTransactionData : public KDbTransactionData { public: explicit PostgresqlTransactionData(KDbConnection *conn); ~PostgresqlTransactionData(); private: Q_DISABLE_COPY(PostgresqlTransactionData) }; class PostgresqlConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(PostgresqlConnection) public: ~PostgresqlConnection() override; //! @return a new query based on a query statement - KDbCursor *prepareQuery(const KDbEscapedString &sql, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(const KDbEscapedString &sql, + KDbCursor::Options options + = KDbCursor::Option::None) override; //! @return a new query based on a query object - KDbCursor *prepareQuery(KDbQuerySchema *query, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, + KDbCursor::Options options + = KDbCursor::Option::None) override; - KDbPreparedStatementInterface *prepareStatementInternal() override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbPreparedStatementInterface *prepareStatementInternal() override; /*! Connection-specific string escaping. */ KDbEscapedString escapeString(const QString& str) const override; virtual KDbEscapedString escapeString(const QByteArray& str) const; private: /*! Used by driver */ PostgresqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); //! @return true if currently connected to a database, ignoring the m_is_connected flag. bool drv_isDatabaseUsed() const override; //! Noop: we tell we are connected, but we wont actually connect until we use a database. bool drv_connect() override; bool drv_getServerVersion(KDbServerVersionInfo* version) override; //! Noop: we tell we have disconnected, but it is actually handled by closeDatabase. bool drv_disconnect() override; //! @return a list of database names bool drv_getDatabasesList(QStringList* list) override; //! Create a new database bool drv_createDatabase(const QString &dbName = QString()) override; //! Uses database. Note that if data().localSocketFileName() is not empty, //! only directory path is used for connecting; the local socket's filename stays ".s.PGSQL.5432". bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) override; //! Close the database connection bool drv_closeDatabase() override; //! Drops the given database bool drv_dropDatabase(const QString &dbName = QString()) override; //! Executes an SQL statement - KDbSqlResult* drv_prepareSql(const KDbEscapedString& sql) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbSqlResult *drv_prepareSql(const KDbEscapedString &sql) override; bool drv_executeSql(const KDbEscapedString& sql) override; //! Implemented for KDbResultable QString serverResultName() const override; //! @todo move this somewhere to low level class (MIGRATION?) tristate drv_containsTable(const QString &tableName) override; void storeResult(PGresult *pgResult, ExecStatusType execStatus); PostgresqlConnectionInternal * const d; friend class PostgresqlDriver; friend class PostgresqlCursorData; friend class PostgresqlTransactionData; friend class PostgresqlSqlResult; Q_DISABLE_COPY(PostgresqlConnection) }; #endif diff --git a/src/drivers/postgresql/PostgresqlConnection_p.h b/src/drivers/postgresql/PostgresqlConnection_p.h index 3d221128..c0485786 100644 --- a/src/drivers/postgresql/PostgresqlConnection_p.h +++ b/src/drivers/postgresql/PostgresqlConnection_p.h @@ -1,205 +1,206 @@ /* This file is part of the KDE project Copyright (C) 2005 Adam Pigg Copyright (C) 2010-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_POSTGRESQLCONNECTION_P_H #define KDB_POSTGRESQLCONNECTION_P_H #include "KDbConnection_p.h" #include "PostgresqlConnection.h" #include "PostgresqlDriver.h" #include "KDbResult.h" #include "KDbSqlField.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" #include "KDbSqlString.h" #include #include class KDbEscapedString; class PostgresqlConnectionInternal : public KDbConnectionInternal { public: explicit PostgresqlConnectionInternal(KDbConnection *connection); virtual ~PostgresqlConnectionInternal(); //! Executes query for a raw SQL statement @a sql on the database PGresult* executeSql(const KDbEscapedString& sql); static QString serverResultName(int resultCode); void storeResultAndClear(KDbResult *result, PGresult **pgResult, ExecStatusType execStatus); void storeResult(KDbResult *result); //! @return true if status of connection is "OK". /*! From https://www.postgresql.org/docs/8.4/static/libpq-status.html: "Only two of these are seen outside of an asynchronous connection procedure: CONNECTION_OK and CONNECTION_BAD." */ inline bool connectionOK() { return CONNECTION_OK == PQstatus(conn); } PGconn *conn; bool unicode; QByteArray escapingBuffer; bool fuzzystrmatchExtensionCreated = false; private: Q_DISABLE_COPY(PostgresqlConnectionInternal) }; //! Internal PostgreSQL cursor data. /*! Provides a low-level abstraction for iterating over result sets. */ class PostgresqlCursorData : public PostgresqlConnectionInternal { public: explicit PostgresqlCursorData(KDbConnection* connection); ~PostgresqlCursorData() override; PGresult* res; ExecStatusType resultStatus; private: Q_DISABLE_COPY(PostgresqlCursorData) }; class PostgresqlSqlField : public KDbSqlField { public: inline PostgresqlSqlField(const PGresult *r, int n) : result(r), number(n) { } //! @return column name inline QString name() override { //! @todo UTF8? return QString::fromLatin1(PQfname(result, number)); } inline int type() override { return static_cast(PQftype(result, number)); } inline int length() override { return PostgresqlDriver::pqfmodToLength(PQfmod(result, number)); } const PGresult * const result; const int number; private: Q_DISABLE_COPY(PostgresqlSqlField) }; class PostgresqlSqlRecord : public KDbSqlRecord { public: inline PostgresqlSqlRecord(const PGresult *res, int r) : result(res), record(r) { } inline ~PostgresqlSqlRecord() override { } inline QString stringValue(int index) override { return PQgetisnull(result, record, index) ? QString() : QString::fromUtf8(PQgetvalue(result, record, index), PQgetlength(result, record, index)); } inline KDbSqlString cstringValue(int index) override { return PQgetisnull(result, record, index) ? KDbSqlString() : KDbSqlString(PQgetvalue(result, record, index), PQgetlength(result, record, index)); } inline QByteArray toByteArray(int index) override { return PQgetisnull(result, record, index) ? QByteArray() : QByteArray(PQgetvalue(result, record, index), PQgetlength(result, record, index)); } private: const PGresult * const result; const int record; Q_DISABLE_COPY(PostgresqlSqlRecord) }; class PostgresqlSqlResult : public KDbSqlResult { public: inline PostgresqlSqlResult(PostgresqlConnection *c, PGresult* r, ExecStatusType status) : conn(c), result(r), resultStatus(status), recordToFetch(0), recordsCount(PQntuples(r)) { Q_ASSERT(c); } inline ~PostgresqlSqlResult() override { PQclear(result); } inline KDbConnection *connection() const override { return conn; } inline int fieldsCount() override { return PQnfields(result); } - inline KDbSqlField *field(int index) override Q_REQUIRED_RESULT { + inline Q_REQUIRED_RESULT KDbSqlField *field(int index) override + { return new PostgresqlSqlField(result, index); } - KDbField *createField(const QString &tableName, int index) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbField *createField(const QString &tableName, int index) override; - inline QSharedPointer fetchRecord() override Q_REQUIRED_RESULT + inline Q_REQUIRED_RESULT QSharedPointer fetchRecord() override { return QSharedPointer(recordToFetch < recordsCount ? new PostgresqlSqlRecord(result, recordToFetch++) : nullptr); } inline KDbResult lastResult() override { KDbResult r; if (resultStatus == PGRES_TUPLES_OK || resultStatus == PGRES_COMMAND_OK) { return r; } QByteArray msg(PQresultErrorMessage(result)); if (msg.endsWith('\n')) { msg.chop(1); } r.setServerMessage(QString::fromLatin1(msg)); r.setServerErrorCode(resultStatus); return r; } //! @return the oid of the last insert - only works if there was insert of 1 row inline quint64 lastInsertRecordId() override { // InvalidOid == 0 means error const Oid oid = PQoidValue(result); return oid == 0 ? std::numeric_limits::max() : static_cast(oid); } private: //! @return a KDb type for PostgreSQL type //! @todo prompt user if necessary? KDbField::Type type(const QString& tableName, PostgresqlSqlField *field); PostgresqlConnection* const conn; PGresult* result; ExecStatusType resultStatus; int recordToFetch; int recordsCount; Q_DISABLE_COPY(PostgresqlSqlResult) }; #endif diff --git a/src/drivers/postgresql/PostgresqlPreparedStatement.h b/src/drivers/postgresql/PostgresqlPreparedStatement.h index eae7fcef..8be56375 100644 --- a/src/drivers/postgresql/PostgresqlPreparedStatement.h +++ b/src/drivers/postgresql/PostgresqlPreparedStatement.h @@ -1,45 +1,46 @@ /* This file is part of the KDE project Copyright (C) 2005 Adam Pigg Copyright (C) 2010 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_POSTGRESQLPREPAREDSTATEMENT_H #define KDB_POSTGRESQLPREPAREDSTATEMENT_H #include "KDbPreparedStatementInterface.h" #include "PostgresqlConnection_p.h" class PostgresqlPreparedStatement : public KDbPreparedStatementInterface, public PostgresqlConnectionInternal { public: explicit PostgresqlPreparedStatement(PostgresqlConnectionInternal* conn); ~PostgresqlPreparedStatement() override; bool prepare(const KDbEscapedString& sql) override; - QSharedPointer execute(KDbPreparedStatement::Type type, + Q_REQUIRED_RESULT QSharedPointer execute( + KDbPreparedStatement::Type type, const KDbField::List &selectFieldList, KDbFieldList *insertFieldList, - const KDbPreparedStatementParameters ¶meters) override Q_REQUIRED_RESULT; + const KDbPreparedStatementParameters ¶meters) override; private: Q_DISABLE_COPY(PostgresqlPreparedStatement) }; #endif diff --git a/src/drivers/sqlite/SqliteConnection.h b/src/drivers/sqlite/SqliteConnection.h index 72282291..a9eb087f 100644 --- a/src/drivers/sqlite/SqliteConnection.h +++ b/src/drivers/sqlite/SqliteConnection.h @@ -1,124 +1,126 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONN_SQLITE_H #define KDB_CONN_SQLITE_H #include #include "KDbConnection.h" class SqliteConnectionInternal; class KDbDriver; /*! @brief SQLite-specific connection Following connection options are supported (see KDbConnectionOptions): - extraSqliteExtensionPaths (read/write, QStringList): adds extra seach paths for SQLite extensions. Set them before KDbConnection::useDatabase() is called. Absolute paths are recommended. */ class SqliteConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(SqliteConnection) public: ~SqliteConnection() override; - KDbCursor *prepareQuery(const KDbEscapedString &sql, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; - KDbCursor *prepareQuery(KDbQuerySchema *query, KDbCursor::Options options - = KDbCursor::Option::None) override Q_REQUIRED_RESULT; - - KDbPreparedStatementInterface* prepareStatementInternal() override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(const KDbEscapedString &sql, + KDbCursor::Options options + = KDbCursor::Option::None) override; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, + KDbCursor::Options options + = KDbCursor::Option::None) override; + + Q_REQUIRED_RESULT KDbPreparedStatementInterface *prepareStatementInternal() override; protected: /*! Used by driver */ SqliteConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); bool drv_connect() override; bool drv_getServerVersion(KDbServerVersionInfo* version) override; bool drv_disconnect() override; bool drv_getDatabasesList(QStringList* list) override; #if 0 // TODO //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_getTablesList(QStringList* list); #endif //! @todo move this somewhere to low level class (MIGRATION?) tristate drv_containsTable(const QString &tableName) override; /*! Creates new database using connection. Note: Do not pass @a dbName arg because for file-based engine (that has one database per connection) it is defined during connection. */ bool drv_createDatabase(const QString &dbName = QString()) override; /*! Opens existing database using connection. Do not pass @a dbName arg because for file-based engine (that has one database per connection) it is defined during connection. If you pass it, database file name will be changed. */ bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) override; bool drv_closeDatabase() override; /*! Drops database from the server using connection. After drop, database shouldn't be accessible anymore, so database file is just removed. See note from drv_useDatabase(). */ bool drv_dropDatabase(const QString &dbName = QString()) override; KDbSqlResult* drv_prepareSql(const KDbEscapedString& sql) override; bool drv_executeSql(const KDbEscapedString& sql) override; //! Implemented for KDbResultable QString serverResultName() const override; void storeResult(); tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field, const QString& propertyName, const QVariant& value) override; //! for drv_changeFieldProperty() tristate changeFieldType(KDbTableSchema *table, KDbField *field, KDbField::Type type); SqliteConnectionInternal* d; private: bool drv_useDatabaseInternal(bool *cancelled, KDbMessageHandler* msgHandler, bool createIfMissing); //! Closes database without altering stored result number and message void drv_closeDatabaseSilently(); //! Finds a native SQLite extension @a name in the search path and loads it. //! Path and filename extension should not be provided. //! @return true on success bool findAndLoadExtension(const QString & name); //! Loads extension from plugin at @a path (absolute path is recommended) //! @return true on success bool loadExtension(const QString& path); friend class SqliteDriver; friend class SqliteCursor; friend class SqliteSqlResult; Q_DISABLE_COPY(SqliteConnection) }; #endif diff --git a/src/drivers/sqlite/SqliteConnection_p.h b/src/drivers/sqlite/SqliteConnection_p.h index b30d08ba..841abbd3 100644 --- a/src/drivers/sqlite/SqliteConnection_p.h +++ b/src/drivers/sqlite/SqliteConnection_p.h @@ -1,204 +1,206 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_SQLITECONN_P_H #define KDB_SQLITECONN_P_H #include "KDbConnection_p.h" #include "SqliteConnection.h" #include "KDbSqlField.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" #include "KDbSqlString.h" #include /*! Internal SQLite connection data. Also used by SqliteCursor. */ class SqliteConnectionInternal : public KDbConnectionInternal { public: explicit SqliteConnectionInternal(KDbConnection *connection); virtual ~SqliteConnectionInternal(); //! @return true if loading extensions is enabled bool extensionsLoadingEnabled() const; //! Sets loading extensions flag to @a set void setExtensionsLoadingEnabled(bool set); static QString serverResultName(int serverResultCode); void storeResult(KDbResult *result); sqlite3 *data; bool data_owned; //!< true if data pointer should be freed on destruction private: bool m_extensionsLoadingEnabled; Q_DISABLE_COPY(SqliteConnectionInternal) }; class SqliteSqlField : public KDbSqlField { public: inline SqliteSqlField(sqlite3_stmt *st, int i) : prepared_st(st), index(i) { } //! @return column name inline QString name() override { return QString::fromUtf8(sqlite3_column_name(prepared_st, index)); } //! @return column type inline int type() override { return sqlite3_column_type(prepared_st, index); } //! @return length limit - no limits for SQLite inline int length() override { return std::numeric_limits::max(); } private: sqlite3_stmt * const prepared_st; const int index; Q_DISABLE_COPY(SqliteSqlField) }; class SqliteSqlRecord : public KDbSqlRecord { public: inline SqliteSqlRecord(sqlite3_stmt *st) : prepared_st(st) { Q_ASSERT(st); } inline ~SqliteSqlRecord() override { } inline QString stringValue(int index) override { return QString::fromUtf8( (const char*)sqlite3_column_text(prepared_st, index), sqlite3_column_bytes(prepared_st, index)); } inline KDbSqlString cstringValue(int index) override { // sqlite3_column_text() returns UTF-8 but it's OK if the data is a C string return KDbSqlString((const char*)sqlite3_column_text(prepared_st, index), sqlite3_column_bytes(prepared_st, index)); } inline QByteArray toByteArray(int index) override { return QByteArray((const char*)sqlite3_column_blob(prepared_st, index), sqlite3_column_bytes(prepared_st, index)); } private: sqlite3_stmt * const prepared_st; Q_DISABLE_COPY(SqliteSqlRecord) }; //! Used by SqliteSqlResult::cacheFieldInfo(const QString&) struct SqliteSqlFieldInfo { void setConstraints(KDbField* field); QString defaultValue; bool isNotNull; bool isPrimaryKey; }; class SqliteSqlResult : public KDbSqlResult { public: inline SqliteSqlResult(SqliteConnection *c, sqlite3_stmt *st) : conn(c), prepared_st(st) { Q_ASSERT(c); } inline ~SqliteSqlResult() override { // don't check result here, done elsewhere already (void)sqlite3_finalize(prepared_st); } inline KDbConnection *connection() const override { return conn; } inline int fieldsCount() override { // We're using sqlite3_column_count instead of sqlite3_data_count to know // the column count before fetching. User will know if fetching succeeded anyway. return sqlite3_column_count(prepared_st); } - inline KDbSqlField *field(int index) override Q_REQUIRED_RESULT { + inline Q_REQUIRED_RESULT KDbSqlField *field(int index) override + { return prepared_st ? new SqliteSqlField(prepared_st, index) : nullptr; } - KDbField *createField(const QString &tableName, int index) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbField *createField(const QString &tableName, int index) override; - inline QSharedPointer fetchRecord() override Q_REQUIRED_RESULT { + inline Q_REQUIRED_RESULT QSharedPointer fetchRecord() override + { SqliteSqlRecord *record; const int res = sqlite3_step(prepared_st); if (res == SQLITE_ROW) { record = new SqliteSqlRecord(prepared_st); } else { record = nullptr; } return QSharedPointer(record); } inline KDbResult lastResult() override { KDbResult res; const int err = sqlite3_errcode(conn->d->data); if (err != SQLITE_ROW && err != SQLITE_OK && err != SQLITE_DONE) { res.setCode(ERR_OTHER); res.setServerErrorCode(err); conn->d->storeResult(&res); } return res; } inline quint64 lastInsertRecordId() override { return static_cast(sqlite3_last_insert_rowid(conn->d->data)); } protected: //! @return a KDb type for a SQLite type //! The returned type is a guess, for example KDbField::Integer is returned for SQLITE_INTEGER. //! For unsupported types returns KDbField::InvalidType. //! See https://www.sqlite.org/c3ref/c_blob.html static KDbField::Type type(int sqliteType); //! Sets constraints to a @a field based on SQLite's internal schema: //! - whether the column can be NULL //! - the default value for the column //! - whether the column is primary key //! @note @a field should have its name set //! See https://www.sqlite.org/pragma.html#pragma_table_info //! @todo support keys bool setConstraints(const QString &tableName, KDbField* field); //! Caches information about the fields, for setConstraints() //! @todo Support composite primary keys //! @todo Default values are only encoded as string bool cacheFieldInfo(const QString &tableName); private: SqliteConnection * const conn; sqlite3_stmt * const prepared_st; KDbUtils::AutodeletedHash cachedFieldInfos; friend class SqlitePreparedStatement; Q_DISABLE_COPY(SqliteSqlResult) }; #endif diff --git a/src/drivers/sqlite/SqlitePreparedStatement.h b/src/drivers/sqlite/SqlitePreparedStatement.h index 5923c206..daa3502d 100644 --- a/src/drivers/sqlite/SqlitePreparedStatement.h +++ b/src/drivers/sqlite/SqlitePreparedStatement.h @@ -1,52 +1,53 @@ /* This file is part of the KDE project Copyright (C) 2005-2016 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_SQLITEPREPAREDSTATEMENT_H #define KDB_SQLITEPREPAREDSTATEMENT_H #include "KDbPreparedStatementInterface.h" #include "SqliteConnection_p.h" class KDbField; /*! Implementation of prepared statements for the SQLite driver. */ class SqlitePreparedStatement : public KDbPreparedStatementInterface, public SqliteConnectionInternal { public: explicit SqlitePreparedStatement(SqliteConnectionInternal* conn); ~SqlitePreparedStatement() override; protected: bool prepare(const KDbEscapedString& sql) override; - QSharedPointer execute(KDbPreparedStatement::Type type, + Q_REQUIRED_RESULT QSharedPointer execute( + KDbPreparedStatement::Type type, const KDbField::List &selectFieldList, KDbFieldList *insertFieldList, - const KDbPreparedStatementParameters ¶meters) override Q_REQUIRED_RESULT; + const KDbPreparedStatementParameters ¶meters) override; bool bindValue(KDbField *field, const QVariant& value, int arg); inline SqliteSqlResult *sqlResult() { return static_cast(m_sqlResult.data()); } QSharedPointer m_sqlResult; private: Q_DISABLE_COPY(SqlitePreparedStatement) }; #endif diff --git a/src/drivers/sybase/SybaseConnection.h b/src/drivers/sybase/SybaseConnection.h index ecfa6c2a..793de01a 100644 --- a/src/drivers/sybase/SybaseConnection.h +++ b/src/drivers/sybase/SybaseConnection.h @@ -1,82 +1,82 @@ /* This file is part of the KDE project Copyright (C) 2007 Sharan Rao This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef SYBASECONNECTION_H #define SYBASECONNECTION_H #include #include "KDbConnection.h" #include "SybaseCursor.h" class SybaseConnectionInternal; /*! @short Provides database connection, allowing queries and data modification. */ class SybaseConnection : public KDbConnection { public: virtual ~SybaseConnection(); - KDbCursor *prepareQuery(const KDbEscapedString &sql, - int cursor_options = 0) override Q_REQUIRED_RESULT; - KDbCursor *prepareQuery(KDbQuerySchema *query, - int cursor_options = 0) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(const KDbEscapedString &sql, + int cursor_options = 0) override; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, + int cursor_options = 0) override; KDbPreparedStatement prepareStatement(KDbPreparedStatement::StatementType type, KDbFieldList *fields) override; protected: /*! Used by driver */ SybaseConnection(KDbDriver *driver, const KDbConnectionData& connData); virtual bool drv_connect(KDbServerVersionInfo* version); virtual bool drv_disconnect(); virtual bool drv_getDatabasesList(QStringList* list); virtual bool drv_createDatabase(const QString &dbName = QString()); virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = 0, KDbMessageHandler* msgHandler = 0); virtual bool drv_closeDatabase(); virtual bool drv_dropDatabase(const QString &dbName = QString()); virtual bool drv_executeSql(const KDbEscapedString& sql); virtual quint64 drv_lastInsertRecordId(); //! Implemented for KDbResultable virtual QString serverResultName() const; // virtual void drv_clearServerResult(); //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_getTablesList(QStringList* list); //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_containsTable(const QString &tableName); virtual bool drv_beforeInsert(const QString& table, KDbFieldList* fields); virtual bool drv_afterInsert(const QString& table, KDbFieldList* fields); virtual bool drv_beforeUpdate(const QString& table, KDbFieldList* fields); virtual bool drv_afterUpdate(const QString& table, KDbFieldList* fields); SybaseConnectionInternal* d; friend class SybaseDriver; friend class SybaseCursor; }; #endif diff --git a/src/drivers/xbase/XbaseConnection.h b/src/drivers/xbase/XbaseConnection.h index c5caaf9b..169d0fcf 100644 --- a/src/drivers/xbase/XbaseConnection.h +++ b/src/drivers/xbase/XbaseConnection.h @@ -1,76 +1,76 @@ /* This file is part of the KDE project Copyright (C) 2008 Sharan Rao This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef XBASECONNECTION_H #define XBASECONNECTION_H #include #include "KDbConnection.h" #include "XbaseCursor.h" class xBaseConnectionInternal; /*! @short Provides database connection, allowing queries and data modification. */ class xBaseConnection : public KDbConnection { public: virtual ~xBaseConnection(); - KDbCursor *prepareQuery(const KDbEscapedString &sql, - int cursor_options = 0) override Q_REQUIRED_RESULT; - KDbCursor *prepareQuery(KDbQuerySchema *query, - int cursor_options = 0) override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(const KDbEscapedString &sql, + int cursor_options = 0) override; + Q_REQUIRED_RESULT KDbCursor *prepareQuery(KDbQuerySchema *query, + int cursor_options = 0) override; //! @todo returns @c nullptr for now - KDbPreparedStatementInterface *prepareStatementInternal() override Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbPreparedStatementInterface *prepareStatementInternal() override; protected: /*! Used by driver */ xBaseConnection(KDbDriver *driver, KDbDriver* internalDriver, const KDbConnectionData& connData); virtual bool drv_connect(KDbServerVersionInfo* version); virtual bool drv_disconnect(); virtual bool drv_getDatabasesList(QStringList* list); virtual bool drv_createDatabase( const QString &dbName = QString() ); virtual bool drv_useDatabase( const QString &dbName = QString(), bool *cancelled = 0, KDbMessageHandler* msgHandler = 0 ); virtual bool drv_closeDatabase(); virtual bool drv_dropDatabase(const QString &dbName = QString()); virtual bool drv_executeSql(const KDbEscapedString& sql); virtual quint64 drv_lastInsertRecordId(); //! Implemented for KDbResultable virtual QString serverResultName() const; // virtual void drv_clearServerResult(); //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_getTablesList(QStringList* list); //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_containsTable(const QString &tableName); xBaseConnectionInternal* d; friend class xBaseDriver; friend class xBaseCursor; }; #endif diff --git a/src/parser/KDbParser.h b/src/parser/KDbParser.h index 0d5110a3..48122cca 100644 --- a/src/parser/KDbParser.h +++ b/src/parser/KDbParser.h @@ -1,205 +1,205 @@ /* This file is part of the KDE project Copyright (C) 2003 Lucijan Busch Copyright (C) 2004-2018 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_PARSER_H #define KDB_PARSER_H #include "kdb_export.h" #include #include class KDbConnection; class KDbQuerySchema; class KDbTableSchema; class KDbEscapedString; /** * Provides detailed error description about KDbParser. * * @todo Make it explicitly shared using SDC * @todo change type to enum */ class KDB_EXPORT KDbParserError { public: /** * Empty constructor. */ KDbParserError(); /** * Constructor. * * @param type The error type. * @param message A description of the error. * @param token Token where the Error happend. * @param position The position where the error happened. */ KDbParserError(const QString &type, const QString &message, const QByteArray &token, int position); /** * Copy constructor. */ KDbParserError(const KDbParserError &other); ~KDbParserError(); KDbParserError& operator=(const KDbParserError &other); bool operator==(const KDbParserError &other) const; inline bool operator!=(const KDbParserError &other) const { return !operator==(other); } /** * @return the error type. */ QString type() const; /** * @return translated error message. */ QString message() const; /** * @return (character) position where the error happened. */ int position() const; private: class Private; Private * const d; }; class KDbParserPrivate; //!< @internal /** * A parser tool for SQL statements. * * The KDbParser class offers functionality of a SQL parser for database-backend-independent * KDbSQL dialect. Schema objects such as KDbQuerySchema that are created after successful parsing * can be then used for running the queries on actual data or used for further modification. * * @todo Add examples * @todo Support more types than the SELECT */ class KDB_EXPORT KDbParser { Q_DECLARE_TR_FUNCTIONS(KDbParser) public: /** * The type of the statement. */ enum StatementType { NoType, //!< No statement type specified or detected Select, //!< Query-statement CreateTable, //!< Create a new table AlterTable, //!< Alter schema of an existing table Insert, //!< Insert new records Update, //!< Update existing records Delete //!< Delete existing records }; /** * Constructs an new parser object. * @a connection is used to obtain context, for example wildcards "T.*" resolution * is possible only if information about table T is available. */ explicit KDbParser(KDbConnection *connection); ~KDbParser(); /** * @brief Clears the parser's status and runs the parsing for a raw SQL statement * * If parsing of @a sql results in a proper query and @a query is present, it will be set to * representation of the parsed query. * @since 3.1 */ bool parse(const KDbEscapedString &sql, KDbQuerySchema *query = nullptr); /** * Reset the parser's status (table, query, error, statement, statement type). */ void reset(); /** * @return the resulting statement type * NoType is returned if parsing failed or it has not been yet performed or reset() was called. */ StatementType statementType() const; /** * @return the resulting statement type as string. It is not translated. */ QString statementTypeString() const; /** * @return a pointer to a query schema if 'CREATE TABLE ...' statement was parsed * or @c nullptr for any other statements or on error. * @note A proper table schema is returned only once for each successful parse() call, * and the object is owned by the caller. In all other cases @c nullptr is returned. * * @todo Implement this */ - KDbTableSchema *table() Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbTableSchema *table(); /** * @return a pointer to a new query schema created by parsing 'SELECT ...' statement * or @c nullptr for any other statements or on error. * If existing query was supplied to parse() @c nullptr is returned. * @note A proper query schema is returned only once for each successful parse() call, * and the object is owned by the caller. In all other cases nullptr is returned. */ - KDbQuerySchema *query() Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbQuerySchema *query(); /** * @return a pointer to the used database connection or @c nullptr if it was not set. */ KDbConnection *connection(); //! @overload //! @since 3.1 const KDbConnection *connection() const; /** * @return detailed information about last error. * If no error occurred KDbParserError::type() is empty. */ KDbParserError error() const; /** * @return the statement passed on the most recent call of parse(). */ KDbEscapedString statement() const; private: void init(); friend class KDbParserPrivate; KDbParserPrivate * const d; //!< @internal d-pointer class. Q_DISABLE_COPY(KDbParser) }; //! Sends information about parser error @a error to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbParserError& error); #endif diff --git a/src/parser/KDbParser_p.h b/src/parser/KDbParser_p.h index 8a5669a7..94bb9acc 100644 --- a/src/parser/KDbParser_p.h +++ b/src/parser/KDbParser_p.h @@ -1,180 +1,180 @@ /* This file is part of the KDE project Copyright (C) 2004-2016 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_PARSER_P_H #define KDB_PARSER_P_H #include "KDbParser.h" #include "KDbSqlTypes.h" #include #include #include #include class KDbQuerySchema; class KDbTableSchema; class KDbConnection; class KDbExpression; //! @internal class KDbParserPrivate { public: KDbParserPrivate(); ~KDbParserPrivate(); void reset(); //! For use by parser's low level C functions inline static KDbParserPrivate* get(KDbParser *parser) { return parser->d; } /** * Sets the type of statement. */ void setStatementType(KDbParser::StatementType type); /** * Sets @a table schema object. */ void setTableSchema(KDbTableSchema *table); /** * Sets @a query schema object. */ //! @todo Add other query types void setQuerySchema(KDbQuerySchema *query); /** * Sets a error. */ void setError(const KDbParserError &err); /** * Creates a new query or provides the one provided by KDbParser::parse(). */ - KDbQuerySchema* createQuery() Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbQuerySchema *createQuery(); friend class KDbParser; private: KDbParser::StatementType statementType; KDbTableSchema *table; //! Query created as a result of parse() (createQuery()); can be also predefined - passed as //! argument of parse() KDbQuerySchema *query; KDbConnection *connection; KDbEscapedString sql; KDbParserError error; bool initialized; Q_DISABLE_COPY(KDbParserPrivate) }; /*! Info used on parsing. */ class KDB_TESTING_EXPORT KDbParseInfo { public: ~KDbParseInfo(); //! @return positions of tables/aliases having the same name @a tableOrAliasName. //! First tries to use information provided by appendPositionForTableOrAliasName(), //! then information from the query schema. QList tablesAndAliasesForName(const QString &tableOrAliasName) const; //! @return query schema for this parsing KDbQuerySchema* querySchema() const; //! @return error message for the parsing process QString errorMessage() const; //! Sets error message for the parsing process to @a message void setErrorMessage(const QString &message); //! @return detailed error description for the parsing process QString errorDescription() const; //! Sets detailed error description for the parsing process to @a description void setErrorDescription(const QString &description); protected: //! Constructs parse info structure for query @a query. explicit KDbParseInfo(KDbQuerySchema *query); class Private; Private * const d; private: Q_DISABLE_COPY(KDbParseInfo) }; class Q_DECL_HIDDEN KDbParseInfo::Private { public: Private() {} ~Private() { qDeleteAll(repeatedTablesAndAliases); } //! collects positions of tables/aliases with the same names QHash< QString, QList* > repeatedTablesAndAliases; QString errorMessage, errorDescription; // helpers KDbQuerySchema *querySchema; private: Q_DISABLE_COPY(Private) }; /*! Internal info used on parsing (writable). */ class KDB_TESTING_EXPORT KDbParseInfoInternal : public KDbParseInfo { public: //! Constructs parse info structure for query @a query. explicit KDbParseInfoInternal(KDbQuerySchema *query); ~KDbParseInfoInternal(); //! Appends position @a pos for table or alias @a tableOrAliasName. void appendPositionForTableOrAliasName(const QString &tableOrAliasName, int pos); private: Q_DISABLE_COPY(KDbParseInfoInternal) }; KDB_TESTING_EXPORT const char* g_tokenName(unsigned int offset); void yyerror(const char *str); void setError(const QString& errName, const QString& errDesc); void setError(const QString& errDesc); bool addColumn(KDbParseInfo* parseInfo, KDbExpression* columnExpr); KDbQuerySchema* buildSelectQuery( KDbQuerySchema* querySchema, KDbNArgExpression* colViews, KDbNArgExpression* tablesList = nullptr, SelectOptionsInternal * options = nullptr); extern KDbParser *globalParser; extern KDbField *globalField; #endif diff --git a/src/sql/KDbSqlResult.h b/src/sql/KDbSqlResult.h index fe67d5ee..0e353f43 100644 --- a/src/sql/KDbSqlResult.h +++ b/src/sql/KDbSqlResult.h @@ -1,93 +1,93 @@ /* This file is part of the KDE project Copyright (C) 2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_SQLRESULT_H #define KDB_SQLRESULT_H #include "kdb_export.h" #include #include class KDbConnection; class KDbField; class KDbRecordData; class KDbResult; class KDbSqlField; class KDbSqlRecord; /** * The KDbSqlResult class abstracts result of a raw SQL query preparation by KDbConnection::prepareSql() * * The KDbSqlResult object provides low-level access to information about fields of the result and * can fetch records by actual execution of the prepared query. * * @note the KDbSqlResult object should be deleted before closing the database connection that * created it. This is needed because the connection is used by the object to retrieve data or to * obtain status information. */ class KDB_EXPORT KDbSqlResult { public: KDbSqlResult(); virtual ~KDbSqlResult(); //! @return connection for this result virtual KDbConnection *connection() const { return nullptr; } //! @return number of fields in this result virtual int fieldsCount() = 0; //! @return field @a index from this result virtual KDbSqlField *field(int index) /*Q_REQUIRED_RESULT*/ = 0; //! Creates a KDb field for field @a index and returns it //! On failure returns @c nullptr. //! @a tableName is the table name and may be used to retrieve information but may //! be ignored as well if the KDbSqlResult already has field metadata available. virtual KDbField* createField(const QString &tableName, int index) /*Q_REQUIRED_RESULT*/ = 0; /** * Fetches one record. * * @return a shared pointer to the record or a null pointer if there is no record to fetch or * on error. * Check lastResult() for detailed result. Ownership is transferred to the caller. */ virtual QSharedPointer fetchRecord() /*Q_REQUIRED_RESULT*/ = 0; //! Convenience method. Fetches one record and all values into @a data. //! @return record data object and passes its ownership //! @c nullptr is returned on error or when there is no record to fetch. //! Check lastResult() for errors. - KDbRecordData* fetchRecordData() Q_REQUIRED_RESULT; + Q_REQUIRED_RESULT KDbRecordData *fetchRecordData(); //! @return result of last operation on this SQL result virtual KDbResult lastResult() = 0; /*! @return unique identifier of the most recently inserted record. Typically this is just primary key value. This identifier could be reused when we want to reference just inserted record. If there was no insertion recently performed for the result, std::numeric_limits::max() is returned. */ virtual quint64 lastInsertRecordId() { return std::numeric_limits::max(); } private: Q_DISABLE_COPY(KDbSqlResult) }; #endif