diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f8e2b5a7..86e4a152 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,466 +1,467 @@ # Private options (visible only within KDb) simple_option(KDB_EXPRESSION_DEBUG "Debugging of Expression classes" OFF) simple_option(KDB_DRIVERMANAGER_DEBUG "Debugging of the Driver Manager class" OFF) simple_option(KDB_TRANSACTIONS_DEBUG "Debugging of the Transaction class" OFF) +simple_option(KDB_TABLESCHEMACHANGELISTENER_DEBUG "Debugging of the KDbTableSchemaChangeListener class" OFF) # Public options (affecting public behavior or contents of KDb) simple_option(KDB_DEBUG_GUI "GUI for debugging" OFF) # NOTE: always add public options to KDbConfig.cmake.in as well include(CheckIncludeFile) check_include_file(unistd.h HAVE_UNISTD_H) #add_definitions( # TODO -DKDE_DEFAULT_DEBUG_AREA=44000 #) ########### generate parser/lexer files ############### # as described at http://public.kitware.com/pipermail/cmake/2002-September/003028.html # Create target for the parser add_custom_target(parser echo "Creating parser/lexer files") set(PARSER_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/parser) # Create custom command for flex/lex (note the outputs) # TODO(GEN) uncomment GENERATED if we ever use this patch: https://phabricator.kde.org/D357 "No more generated parser/scanner files in the source dir" add_custom_command( TARGET parser COMMAND ${PARSER_SOURCE_DIR}/generate_parser_code.sh DEPENDS ${PARSER_SOURCE_DIR}/KDbSqlParser.y ${PARSER_SOURCE_DIR}/KDbSqlScanner.l ${PARSER_SOURCE_DIR}/generate_parser_code.sh OUTPUT #TODO(GEN) ${PARSER_SOURCE_DIR}/generated/sqlparser.h #TODO(GEN) ${PARSER_SOURCE_DIR}/generated/sqlparser.cpp #TODO(GEN) ${PARSER_SOURCE_DIR}/generated/sqlscanner.cpp #TODO(GEN) ${PARSER_SOURCE_DIR}/generated/KDbToken.h #TODO(GEN) ${PARSER_SOURCE_DIR}/generated/KDbToken.cpp ) string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER) if("${CMAKE_BUILD_TYPE_LOWER}" MATCHES "debug") add_definitions(-DYYDEBUG=1) # needed where sqlparser.h is used endif() if(NOT HAVE_UNISTD_H) set(EXTRA_SCANNER_COMPILE_FLAGS "-DYY_NO_UNISTD_H=1") endif() if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANG) set(EXTRA_SCANNER_COMPILE_FLAGS "${EXTRA_SCANNER_COMPILE_FLAGS} -Wno-sign-compare -Wno-unused-function -Wno-deprecated-register") elseif(MSVC) set(EXTRA_SCANNER_COMPILE_FLAGS "${EXTRA_SCANNER_COMPILE_FLAGS} /wd4018") # disable warning C4018: '<' : signed/unsigned mismatch endif() # Mark files as generated, set compile flags set_source_files_properties(${PARSER_SOURCE_DIR}/generated/sqlparser.cpp PROPERTIES GENERATED TRUE SKIP_AUTOMOC ON # YYERROR_VERBOSE=1 needed to get a token table for tokenName() even for release builds COMPILE_FLAGS "-DYYERROR_VERBOSE=1 ${EXTRA_PARSER_COMPILE_FLAGS} " ) set_source_files_properties(${PARSER_SOURCE_DIR}/generated/sqlparser.h PROPERTIES GENERATED TRUE) set_source_files_properties(${PARSER_SOURCE_DIR}/generated/KDbToken.h PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/KDbConnectionData_sdc.cpp PROPERTIES GENERATED TRUE SKIP_AUTOMOC ON ) set_source_files_properties( ${PARSER_SOURCE_DIR}/generated/sqlscanner.cpp PROPERTIES GENERATED TRUE SKIP_AUTOMOC ON COMPILE_FLAGS "${EXTRA_SCANNER_COMPILE_FLAGS} " ) set(kdb_LIB_SRCS parser/generated/sqlscanner.cpp parser/generated/sqlparser.cpp parser/generated/KDbToken.cpp parser/KDbParser.cpp parser/KDbParser_p.cpp parser/KDbSqlParser.y parser/KDbSqlScanner.l parser/generate_parser_code.sh parser/extract_tokens.sh parser/TODO tools/KDbJsonTrader_p.cpp # mostly copied from KReport's KReportJsonTrader_p.cpp tools/KDbValidator.cpp tools/KDbFieldValidator.cpp tools/KDbLongLongValidator.cpp tools/KDbObjectNameValidator.cpp tools/KDbIdentifierValidator.cpp tools/KDbUtils.cpp #TODO tools/debuggui.cpp #TODO tools/KDbSimpleCommandLineApp.cpp tools/transliteration/transliteration_table.cpp tools/transliteration/generate_transliteration_table.sh tools/transliteration/transliteration_table.readme KDbEscapedString.cpp KDbResult.cpp KDbQueryAsterisk.cpp KDbConnectionData.cpp KDbVersionInfo.cpp ${CMAKE_CURRENT_BINARY_DIR}/KDbConnectionData_sdc.cpp KDbField.cpp KDbQuerySchemaParameter.cpp expression/KDbExpression.cpp expression/KDbNArgExpression.cpp expression/KDbUnaryExpression.cpp expression/KDbBinaryExpression.cpp expression/KDbConstExpression.cpp expression/KDbQueryParameterExpression.cpp expression/KDbVariableExpression.cpp expression/KDbFunctionExpression.cpp KDbFieldList.cpp KDbTableSchema.cpp KDbTableSchemaChangeListener.cpp KDbIndexSchema.cpp KDbOrderByColumn.cpp KDbQuerySchema.cpp KDbQuerySchema_p.cpp KDbQueryColumnInfo.cpp KDbTableOrQuerySchema.cpp KDbDriverManager.cpp KDbDriver.cpp KDbDriver_p.cpp KDbDriverMetaData.cpp KDbConnection.cpp KDbConnectionProxy.cpp generated/sqlkeywords.cpp KDbObject.cpp KDb.cpp KDbRecordData.cpp KDbCursor.cpp KDbTransaction.cpp KDbGlobal.cpp KDbRelationship.cpp KDbRecordEditBuffer.cpp KDbMessageHandler.cpp KDbPreparedStatement.cpp KDbProperties.cpp KDbAdmin.cpp KDbLookupFieldSchema.cpp KDbAlter.cpp KDbNativeStatementBuilder.cpp kdb_debug.cpp views/KDbTableViewData.cpp views/KDbTableViewColumn.cpp views/chartable.txt sql/KDbSqlField.cpp sql/KDbSqlRecord.cpp sql/KDbSqlResult.cpp # private: tools/KDbUtils_p.h # non-source: Mainpage.dox Messages.sh ) ecm_create_qm_loader(kdb_LIB_SRCS kdb_qt) add_library(KDb SHARED ${kdb_LIB_SRCS}) set_coinstallable_lib_version(KDb) kdb_create_shared_data_classes( kdb_GENERATED_SHARED_DATA_CLASS_HEADERS # output variable with list of headers NO_PREFIX # subdirectory in which the headers should be generated KDbConnectionData.shared.h KDbObject.shared.h KDbQuerySchemaParameter.shared.h KDbResult.shared.h KDbSelectStatementOptions.shared.h KDbVersionInfo.shared.h ) kdb_remove_extensions( kdb_GENERATED_SHARED_DATA_CLASS_BASENAMES ${kdb_GENERATED_SHARED_DATA_CLASS_HEADERS} ) #message(STATUS "kdb_GENERATED_SHARED_DATA_CLASS_HEADERS: ${kdb_GENERATED_SHARED_DATA_CLASS_HEADERS}") #add_dependencies(KDb _shared_classes) # generate shared classes before they can be used in KDb generate_export_header(KDb) set(kdb_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/expression ${CMAKE_CURRENT_SOURCE_DIR}/interfaces ${CMAKE_CURRENT_SOURCE_DIR}/parser ${CMAKE_CURRENT_SOURCE_DIR}/parser/generated ${CMAKE_CURRENT_SOURCE_DIR}/sql ${CMAKE_CURRENT_SOURCE_DIR}/tools ${CMAKE_CURRENT_SOURCE_DIR}/views ) target_include_directories(KDb PUBLIC "$" INTERFACE "$" PRIVATE ${ICU_INCLUDE_DIRS} ) target_link_libraries(KDb PUBLIC Qt5::Core Qt5::Gui Qt5::Widgets KF5::CoreAddons PRIVATE Qt5::Xml ${ICU_I18N_LIBRARY} ) if(BUILD_TEST_COVERAGE) target_link_libraries(KDb PRIVATE gcov ) endif() # Create a Config.cmake and a ConfigVersion.cmake file and install them set(CMAKECONFIG_INSTALL_DIR "${CMAKECONFIG_INSTALL_PREFIX}/${KDB_BASE_NAME}") ecm_setup_version(${PROJECT_VERSION} VARIABLE_PREFIX KDB SOVERSION ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kdb_version.h" PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KDbConfigVersion.cmake" ) install(TARGETS KDb EXPORT KDbTargets ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/KDbConfig.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/KDbConfig.cmake" INSTALL_DESTINATION "${CMAKECONFIG_INSTALL_DIR}" ) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/KDbConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/KDbConfigVersion.cmake" DESTINATION "${CMAKECONFIG_INSTALL_DIR}" COMPONENT Devel) install(EXPORT KDbTargets DESTINATION "${CMAKECONFIG_INSTALL_DIR}" FILE KDbTargets.cmake) ecm_generate_pri_file( BASE_NAME ${KDB_BASE_NAME} LIB_NAME ${KDB_BASE_NAME} DEPS "widgets xml" FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KDB_INCLUDE_INSTALL_DIR} ) install(FILES ${PRI_FILENAME} DESTINATION ${ECM_MKSPECS_INSTALL_DIR}) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/kdb_version.h" DESTINATION "${KDB_INCLUDE_INSTALL_DIR}" COMPONENT Devel) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE HEADER_NAMES KDb KDbAdmin KDbAlter KDbQueryAsterisk KDbConnection KDbConnectionOptions KDbConnectionProxy KDbCursor KDbDriver KDbDriverBehavior KDbDriverManager KDbDriverMetaData KDbError KDbEscapedString KDbField KDbFieldList KDbGlobal KDbIndexSchema KDbLookupFieldSchema KDbMessageHandler KDbNativeStatementBuilder KDbPreparedStatement KDbProperties KDbQueryColumnInfo KDbOrderByColumn KDbQuerySchema KDbRecordData KDbRecordEditBuffer KDbRelationship KDbTableOrQuerySchema KDbTableSchema KDbTableSchemaChangeListener KDbTransaction KDbTransactionData KDbTransactionGuard ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE expression HEADER_NAMES KDbExpression KDbExpressionData ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE interfaces HEADER_NAMES KDbPreparedStatementInterface ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE parser HEADER_NAMES KDbParser ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE parser/generated HEADER_NAMES KDbToken ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE sql HEADER_NAMES KDbSqlField KDbSqlRecord KDbSqlResult KDbSqlString ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE views HEADER_NAMES KDbTableViewData KDbTableViewColumn ) ecm_generate_headers(kdb_FORWARDING_HEADERS REQUIRED_HEADERS kdb_HEADERS ORIGINAL CAMELCASE RELATIVE tools HEADER_NAMES KDbValidator KDbUtils KDbTristate #todo KDbSimpleCommandLineApp KDbLongLongValidator KDbIdentifierValidator KDbFieldValidator KDbObjectNameValidator ) #message(STATUS "%% ${kdb_GENERATED_SHARED_DATA_CLASS_BASENAMES}") ecm_generate_headers(kdb_FORWARDING_HEADERS_FROM_BUILDDIR REQUIRED_HEADERS kdb_HEADERS_FROM_BUILDDIR ORIGINAL CAMELCASE SOURCE_DIR ${PROJECT_BINARY_DIR}/src HEADER_NAMES ${kdb_GENERATED_SHARED_DATA_CLASS_BASENAMES} ) #message(STATUS "%%kdb_HEADERS_FROM_BUILDDIR ${kdb_HEADERS_FROM_BUILDDIR}") install( FILES ${kdb_HEADERS} ${kdb_HEADERS_FROM_BUILDDIR} DESTINATION ${KDB_INCLUDE_INSTALL_DIR} COMPONENT Devel ) install( FILES ${kdb_FORWARDING_HEADERS} ${kdb_FORWARDING_HEADERS_FROM_BUILDDIR} ${PROJECT_BINARY_DIR}/src/kdb_export.h ${PROJECT_BINARY_DIR}/src/config-kdb.h DESTINATION ${KDB_INCLUDE_INSTALL_DIR} COMPONENT Devel ) # KDb/Private includes # install( FILES # Connection_p.h # Driver_p.h # DESTINATION ${KDB_INCLUDE_INSTALL_DIR}/Private COMPONENT Devel # ) # KDb/Interfaces includes # install( FILES # Interfaces/KDbPreparedStatementInterface.h includes/KDb/Interfaces/KDbPreparedStatementInterface # DESTINATION ${KDB_INCLUDE_INSTALL_DIR}/Interfaces COMPONENT Devel # ) if(BUILD_QCH) kdb_add_qch( KDb_QCH NAME KDb BASE_NAME ${KDB_BASE_NAME} VERSION ${PROJECT_VERSION} NAMESPACE org.kde.${KDB_BASE_NAME} SOURCES Mainpage.dox ${kdb_HEADERS} ${kdb_HEADERS_FROM_BUILDDIR} LINK_QCHS Qt5Core_QCH Qt5Gui_QCH Qt5Widgets_QCH KF5CoreAddons_QCH BLANK_MACROS KDB_EXPORT KDB_DEPRECATED TAGFILE_INSTALL_DESTINATION ${KDB_QTQCH_FULL_INSTALL_DIR} QCH_INSTALL_DESTINATION ${KDB_QTQCH_FULL_INSTALL_DIR} ) set(kdb_qch_targets KDb_QCH) endif() kdb_install_qch_export( TARGETS ${kdb_qch_targets} FILE KDbQCHTargets.cmake ​ DESTINATION "${CMAKECONFIG_INSTALL_DIR}" ​ COMPONENT Devel ​) add_subdirectory(drivers) enable_testing() configure_file(config-kdb.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config-kdb.h) diff --git a/src/KDbConnection.cpp b/src/KDbConnection.cpp index f1faae5b..a21fdb5e 100644 --- a/src/KDbConnection.cpp +++ b/src/KDbConnection.cpp @@ -1,3489 +1,3490 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 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. */ #include "KDbConnection.h" #include "KDbConnection_p.h" #include "KDbCursor.h" #include "KDbDriverBehavior.h" #include "KDbDriverMetaData.h" #include "KDbDriver_p.h" #include "KDbLookupFieldSchema.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbQuerySchema_p.h" #include "KDbRecordData.h" #include "KDbRecordEditBuffer.h" #include "KDbRelationship.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" #include "KDbTableOrQuerySchema.h" #include "KDbTableSchemaChangeListener.h" #include "KDbTransactionData.h" #include "KDbTransactionGuard.h" #include "kdb_debug.h" #include #include #include /*! Version number of extended table schema. List of changes: * 2: (Kexi 2.5.0) Added maxLengthIsDefault property (type: bool, if true, KDbField::maxLengthStrategy() == KDbField::DefaultMaxLength) * 1: (Kexi 1.x) Initial version */ #define KDB_EXTENDED_TABLE_SCHEMA_VERSION 2 KDbConnectionInternal::KDbConnectionInternal(KDbConnection *conn) : connection(conn) { } class CursorDeleter { public: explicit CursorDeleter(KDbCursor *cursor) { delete cursor; } }; //================================================ class Q_DECL_HIDDEN KDbConnectionOptions::Private { public: Private() : connection(nullptr) {} Private(const Private &other) { copy(other); } #define KDbConnectionOptionsPrivateArgs(o) std::tie(o.connection) void copy(const Private &other) { KDbConnectionOptionsPrivateArgs((*this)) = KDbConnectionOptionsPrivateArgs(other); } bool operator==(const Private &other) const { return KDbConnectionOptionsPrivateArgs((*this)) == KDbConnectionOptionsPrivateArgs(other); } KDbConnection *connection; }; KDbConnectionOptions::KDbConnectionOptions() : d(new Private) { KDbUtils::PropertySet::insert("readOnly", false, tr("Read only", "Read only connection")); } KDbConnectionOptions::KDbConnectionOptions(const KDbConnectionOptions &other) : KDbUtils::PropertySet(other) , d(new Private(*other.d)) { } KDbConnectionOptions::~KDbConnectionOptions() { delete d; } KDbConnectionOptions& KDbConnectionOptions::operator=(const KDbConnectionOptions &other) { if (this != &other) { KDbUtils::PropertySet::operator=(other); d->copy(*other.d); } return *this; } bool KDbConnectionOptions::operator==(const KDbConnectionOptions &other) const { return KDbUtils::PropertySet::operator==(other) && *d == *other.d; } bool KDbConnectionOptions::isReadOnly() const { return property("readOnly").value().toBool(); } void KDbConnectionOptions::insert(const QByteArray &name, const QVariant &value, const QString &caption) { if (name == "readOnly") { setReadOnly(value.toBool()); return; } QString realCaption; if (property(name).caption().isEmpty()) { // don't allow to change the caption realCaption = caption; } KDbUtils::PropertySet::insert(name, value, realCaption); } void KDbConnectionOptions::setCaption(const QByteArray &name, const QString &caption) { if (name == "readOnly") { return; } KDbUtils::PropertySet::setCaption(name, caption); } void KDbConnectionOptions::setValue(const QByteArray &name, const QVariant &value) { if (name == "readOnly") { setReadOnly(value.toBool()); return; } KDbUtils::PropertySet::setValue(name, value); } void KDbConnectionOptions::remove(const QByteArray &name) { if (name == "readOnly") { return; } KDbUtils::PropertySet::remove(name); } void KDbConnectionOptions::setReadOnly(bool set) { if (d->connection && d->connection->isConnected()) { return; //sanity } KDbUtils::PropertySet::setValue("readOnly", set); } void KDbConnectionOptions::setConnection(KDbConnection *connection) { d->connection = connection; } //================================================ KDbConnectionPrivate::KDbConnectionPrivate(KDbConnection* const conn, KDbDriver *drv, const KDbConnectionData& _connData, const KDbConnectionOptions &_options) : conn(conn) , connData(_connData) , options(_options) , driver(drv) , dbProperties(conn) { options.setConnection(conn); } KDbConnectionPrivate::~KDbConnectionPrivate() { options.setConnection(nullptr); deleteAllCursors(); delete m_parser; qDeleteAll(tableSchemaChangeListeners); qDeleteAll(obsoleteQueries); } void KDbConnectionPrivate::deleteAllCursors() { QSet cursorsToDelete(cursors); cursors.clear(); for(KDbCursor* c : cursorsToDelete) { CursorDeleter deleter(c); } } void KDbConnectionPrivate::errorInvalidDBContents(const QString& details) { conn->m_result = KDbResult(ERR_INVALID_DATABASE_CONTENTS, KDbConnection::tr("Invalid database contents. %1").arg(details)); } QString KDbConnectionPrivate::strItIsASystemObject() const { return KDbConnection::tr("It is a system object."); } void KDbConnectionPrivate::setupKDbSystemSchema() { if (!m_internalKDbTables.isEmpty()) { return; //already set up } { KDbInternalTableSchema *t_objects = new KDbInternalTableSchema(QLatin1String("kexi__objects")); t_objects->addField(new KDbField(QLatin1String("o_id"), KDbField::Integer, KDbField::PrimaryKey | KDbField::AutoInc, KDbField::Unsigned)); t_objects->addField(new KDbField(QLatin1String("o_type"), KDbField::Byte, nullptr, KDbField::Unsigned)); t_objects->addField(new KDbField(QLatin1String("o_name"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_caption"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_desc"), KDbField::LongText)); //kdbDebug() << *t_objects; insertTable(t_objects); } { KDbInternalTableSchema *t_objectdata = new KDbInternalTableSchema(QLatin1String("kexi__objectdata")); t_objectdata->addField(new KDbField(QLatin1String("o_id"), KDbField::Integer, KDbField::NotNull, KDbField::Unsigned)); t_objectdata->addField(new KDbField(QLatin1String("o_data"), KDbField::LongText)); t_objectdata->addField(new KDbField(QLatin1String("o_sub_id"), KDbField::Text)); insertTable(t_objectdata); } { KDbInternalTableSchema *t_fields = new KDbInternalTableSchema(QLatin1String("kexi__fields")); t_fields->addField(new KDbField(QLatin1String("t_id"), KDbField::Integer, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_type"), KDbField::Byte, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_name"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_length"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_precision"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_constraints"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_options"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_default"), KDbField::Text)); //these are additional properties: t_fields->addField(new KDbField(QLatin1String("f_order"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_caption"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_help"), KDbField::LongText)); insertTable(t_fields); } { KDbInternalTableSchema *t_db = new KDbInternalTableSchema(QLatin1String("kexi__db")); t_db->addField(new KDbField(QLatin1String("db_property"), KDbField::Text, KDbField::NoConstraints, KDbField::NoOptions, 32)); t_db->addField(new KDbField(QLatin1String("db_value"), KDbField::LongText)); insertTable(t_db); } } void KDbConnectionPrivate::insertTable(KDbTableSchema* tableSchema) { KDbInternalTableSchema* internalTable = dynamic_cast(tableSchema); if (internalTable) { m_internalKDbTables.insert(internalTable); } else { m_tables.insert(tableSchema->id(), tableSchema); } m_tablesByName.insert(tableSchema->name(), tableSchema); } void KDbConnectionPrivate::removeTable(const KDbTableSchema& tableSchema) { + KDbTableSchemaChangeListener::unregisterForChanges(conn, &tableSchema); m_tablesByName.remove(tableSchema.name()); KDbTableSchema *toDelete = m_tables.take(tableSchema.id()); delete toDelete; } void KDbConnectionPrivate::takeTable(KDbTableSchema* tableSchema) { if (m_tables.isEmpty()) { return; } m_tables.take(tableSchema->id()); m_tablesByName.take(tableSchema->name()); } void KDbConnectionPrivate::renameTable(KDbTableSchema* tableSchema, const QString& newName) { m_tablesByName.take(tableSchema->name()); tableSchema->setName(newName); m_tablesByName.insert(tableSchema->name(), tableSchema); } void KDbConnectionPrivate::changeTableId(KDbTableSchema* tableSchema, int newId) { m_tables.take(tableSchema->id()); m_tables.insert(newId, tableSchema); } void KDbConnectionPrivate::clearTables() { m_tablesByName.clear(); qDeleteAll(m_internalKDbTables); m_internalKDbTables.clear(); QHash tablesToDelete(m_tables); m_tables.clear(); qDeleteAll(tablesToDelete); } void KDbConnectionPrivate::insertQuery(KDbQuerySchema* query) { m_queries.insert(query->id(), query); m_queriesByName.insert(query->name(), query); } void KDbConnectionPrivate::removeQuery(KDbQuerySchema* querySchema) { m_queriesByName.remove(querySchema->name()); m_queries.remove(querySchema->id()); delete querySchema; } void KDbConnectionPrivate::setQueryObsolete(KDbQuerySchema* query) { obsoleteQueries.insert(query); m_queriesByName.take(query->name()); m_queries.take(query->id()); } void KDbConnectionPrivate::clearQueries() { qDeleteAll(m_queries); m_queries.clear(); } KDbTableSchema* KDbConnectionPrivate::setupTableSchema(KDbTableSchema *table) { Q_ASSERT(table); QScopedPointer newTable(table); KDbCursor *cursor; if (!(cursor = conn->executeQuery( KDbEscapedString("SELECT t_id, f_type, f_name, f_length, f_precision, f_constraints, " "f_options, f_default, f_order, f_caption, f_help " "FROM kexi__fields WHERE t_id=%1 ORDER BY f_order") .arg(driver->valueToSql(KDbField::Integer, table->id()))))) { return nullptr; } if (!cursor->moveFirst()) { if (!cursor->result().isError() && cursor->eof()) { conn->m_result = KDbResult(tr("Table has no fields defined.")); } conn->deleteCursor(cursor); return nullptr; } // For each field: load its schema KDbRecordData fieldData; bool ok = true; while (!cursor->eof()) { // kdbDebug()<<"@@@ f_name=="<value(2).asCString(); if (!cursor->storeCurrentRecord(&fieldData)) { ok = false; break; } KDbField *f = conn->setupField(fieldData); if (!f || !table->addField(f)) { ok = false; break; } cursor->moveNext(); } if (!ok) {//error: conn->deleteCursor(cursor); return nullptr; } if (!conn->deleteCursor(cursor)) { return nullptr; } if (!conn->loadExtendedTableSchemaData(table)) { return nullptr; } //store locally: insertTable(table); return newTable.take(); } KDbQuerySchema* KDbConnectionPrivate::setupQuerySchema(KDbQuerySchema *query) { Q_ASSERT(query); QScopedPointer newQuery(query); QString sql; if (!conn->loadDataBlock(query->id(), &sql, QLatin1String("sql"))) { conn->m_result = KDbResult( ERR_OBJECT_NOT_FOUND, tr("Could not find definition for query \"%1\". Deleting this query is recommended.") .arg(query->name())); return nullptr; } if (!parser()->parse(KDbEscapedString(sql), query)) { conn->m_result = KDbResult( ERR_SQL_PARSE_ERROR, tr("

Could not load definition for query \"%1\". " "SQL statement for this query is invalid:
%2

\n" "

This query can be edited only in Text View.

") .arg(query->name(), sql)); return nullptr; } insertQuery(query); return newQuery.take(); } KDbQuerySchemaFieldsExpanded *KDbConnectionPrivate::fieldsExpanded(const KDbQuerySchema *query) { return m_fieldsExpandedCache[query]; } void KDbConnectionPrivate::insertFieldsExpanded(const KDbQuerySchema *query, KDbQuerySchemaFieldsExpanded *cache) { m_fieldsExpandedCache.insert(query, cache); } //================================================ namespace { //! @internal static: list of internal KDb system table names class SystemTables : public QStringList { public: SystemTables() : QStringList({ QLatin1String("kexi__objects"), QLatin1String("kexi__objectdata"), QLatin1String("kexi__fields"), QLatin1String("kexi__db")}) {} }; } Q_GLOBAL_STATIC(SystemTables, g_kdbSystemTableNames) KDbConnection::KDbConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options) : d(new KDbConnectionPrivate(this, driver, connData, options)) { if (d->connData.driverId().isEmpty()) { d->connData.setDriverId(d->driver->metaData()->id()); } } void KDbConnection::destroy() { disconnect(); //do not allow the driver to touch me: I will kill myself. d->driver->d->connections.remove(this); } KDbConnection::~KDbConnection() { KDbConnectionPrivate *thisD = d; d = nullptr; // make sure d is nullptr before destructing delete thisD; } KDbConnectionData KDbConnection::data() const { return d->connData; } KDbDriver* KDbConnection::driver() const { return d->driver; } bool KDbConnection::connect() { clearResult(); if (d->isConnected) { m_result = KDbResult(ERR_ALREADY_CONNECTED, tr("Connection already established.")); return false; } d->serverVersion.clear(); if (!(d->isConnected = drv_connect())) { if (m_result.code() == ERR_NONE) { m_result.setCode(ERR_OTHER); } m_result.setMessage(d->driver->metaData()->isFileBased() ? tr("Could not open \"%1\" project file.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName())) : tr("Could not connect to \"%1\" database server.") .arg(d->connData.toUserVisibleString())); } if (d->isConnected && !d->driver->behavior()->USING_DATABASE_REQUIRED_TO_CONNECT) { if (!drv_getServerVersion(&d->serverVersion)) return false; } return d->isConnected; } bool KDbConnection::isDatabaseUsed() const { return !d->usedDatabase.isEmpty() && d->isConnected && drv_isDatabaseUsed(); } void KDbConnection::clearResult() { KDbResultable::clearResult(); } bool KDbConnection::disconnect() { clearResult(); if (!d->isConnected) return true; if (!closeDatabase()) return false; bool ok = drv_disconnect(); if (ok) d->isConnected = false; return ok; } bool KDbConnection::isConnected() const { return d->isConnected; } bool KDbConnection::checkConnected() { if (d->isConnected) { clearResult(); return true; } m_result = KDbResult(ERR_NO_CONNECTION, tr("Not connected to the database server.")); return false; } bool KDbConnection::checkIsDatabaseUsed() { if (isDatabaseUsed()) { clearResult(); return true; } m_result = KDbResult(ERR_NO_DB_USED, tr("Currently no database is used.")); return false; } QStringList KDbConnection::databaseNames(bool also_system_db) { //kdbDebug() << also_system_db; if (!checkConnected()) return QStringList(); QString tmpdbName; //some engines need to have opened any database before executing "create database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return QStringList(); QStringList list; bool ret = drv_getDatabasesList(&list); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return QStringList(); } if (!ret) return QStringList(); if (also_system_db) return list; //filter system databases: for (QMutableListIterator it(list); it.hasNext();) { if (d->driver->isSystemDatabaseName(it.next())) { it.remove(); } } return list; } bool KDbConnection::drv_getDatabasesList(QStringList* list) { list->clear(); return true; } bool KDbConnection::drv_databaseExists(const QString &dbName, bool ignoreErrors) { QStringList list = databaseNames(true);//also system if (m_result.isError()) { return false; } if (list.indexOf(dbName) == -1) { if (!ignoreErrors) m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("The database \"%1\" does not exist.").arg(dbName)); return false; } return true; } bool KDbConnection::databaseExists(const QString &dbName, bool ignoreErrors) { // kdbDebug() << dbName << ignoreErrors; if (d->driver->behavior()->CONNECTION_REQUIRED_TO_CHECK_DB_EXISTENCE && !checkConnected()) return false; clearResult(); if (d->driver->metaData()->isFileBased()) { //for file-based db: file must exists and be accessible QFileInfo file(d->connData.databaseName()); if (!file.exists() || (!file.isFile() && !file.isSymLink())) { if (!ignoreErrors) m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("The database file \"%1\" does not exist.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } if (!file.isReadable()) { if (!ignoreErrors) m_result = KDbResult(ERR_ACCESS_RIGHTS, tr("Database file \"%1\" is not readable.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } if (!d->options.isReadOnly() && !file.isWritable()) { if (!ignoreErrors) m_result = KDbResult(ERR_ACCESS_RIGHTS, tr("Database file \"%1\" is not writable.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } return true; } QString tmpdbName; //some engines need to have opened any database before executing "create database" const bool orig_skipDatabaseExistsCheckInUseDatabase = d->skipDatabaseExistsCheckInUseDatabase; d->skipDatabaseExistsCheckInUseDatabase = true; bool ret = useTemporaryDatabaseIfNeeded(&tmpdbName); d->skipDatabaseExistsCheckInUseDatabase = orig_skipDatabaseExistsCheckInUseDatabase; if (!ret) return false; ret = drv_databaseExists(dbName, ignoreErrors); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } return ret; } #define createDatabase_CLOSE \ { if (!closeDatabase()) { \ m_result = KDbResult(KDbConnection::tr("Database \"%1\" has been created but " \ "could not be closed after creation.").arg(dbName)); \ return false; \ } } #define createDatabase_ERROR \ { createDatabase_CLOSE; return false; } bool KDbConnection::createDatabase(const QString &dbName) { if (d->driver->behavior()->CONNECTION_REQUIRED_TO_CREATE_DB && !checkConnected()) return false; if (databaseExists(dbName)) { m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Database \"%1\" already exists.").arg(dbName)); return false; } if (d->driver->isSystemDatabaseName(dbName)) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not create database \"%1\". This name is reserved for system database.").arg(dbName)); return false; } if (d->driver->metaData()->isFileBased()) { //update connection data if filename differs if (QFileInfo(dbName).isAbsolute()) { d->connData.setDatabaseName(dbName); } else { d->connData.setDatabaseName( QFileInfo(d->connData.databaseName()).absolutePath() + QDir::separator() + QFileInfo(dbName).fileName()); } } QString tmpdbName; //some engines need to have opened any database before executing "create database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return false; //low-level create if (!drv_createDatabase(dbName)) { m_result.prependMessage(tr("Error creating database \"%1\" on the server.").arg(dbName)); (void)closeDatabase();//sanity return false; } if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } if (!tmpdbName.isEmpty() || !d->driver->behavior()->IS_DB_OPEN_AFTER_CREATE) { //db need to be opened if (!useDatabase(dbName, false/*not yet kexi compatible!*/)) { m_result = KDbResult(tr("Database \"%1\" has been created but could not be opened.").arg(dbName)); return false; } } else { //just for the rule d->usedDatabase = dbName; d->isConnected = true; } KDbTransaction trans; if (d->driver->transactionsSupported()) { trans = beginTransaction(); if (!trans.isActive()) return false; } //-create system tables schema objects d->setupKDbSystemSchema(); //-physically create internal KDb tables foreach(KDbInternalTableSchema* t, d->internalKDbTables()) { if (!drv_createTable(*t)) createDatabase_ERROR; } //-insert KDb version info: // (for compatibility with Kexi expect the legacy kexidb_major_ver/kexidb_minor_ver values) KDbTableSchema *table = d->table(QLatin1String("kexi__db")); if (!table) createDatabase_ERROR; if (!insertRecord(table, QLatin1String("kexidb_major_ver"), KDb::version().major()) || !insertRecord(table, QLatin1String("kexidb_minor_ver"), KDb::version().minor())) createDatabase_ERROR; if (trans.isActive() && !commitTransaction(trans)) createDatabase_ERROR; createDatabase_CLOSE; return true; } #undef createDatabase_CLOSE #undef createDatabase_ERROR bool KDbConnection::useDatabase(const QString &dbName, bool kexiCompatible, bool *cancelled, KDbMessageHandler* msgHandler) { if (cancelled) *cancelled = false; //kdbDebug() << dbName << kexiCompatible; if (!checkConnected()) return false; QString my_dbName; if (dbName.isEmpty()) my_dbName = d->connData.databaseName(); else my_dbName = dbName; if (my_dbName.isEmpty()) return false; if (d->usedDatabase == my_dbName) return true; //already used if (!d->skipDatabaseExistsCheckInUseDatabase) { if (!databaseExists(my_dbName, false /*don't ignore errors*/)) return false; //database must exist } if (!d->usedDatabase.isEmpty() && !closeDatabase()) //close db if already used return false; d->usedDatabase.clear(); if (!drv_useDatabase(my_dbName, cancelled, msgHandler)) { if (cancelled && *cancelled) return false; QString msg(tr("Opening database \"%1\" failed.").arg(my_dbName)); m_result.prependMessage(msg); return false; } if (d->serverVersion.isNull() && d->driver->behavior()->USING_DATABASE_REQUIRED_TO_CONNECT) { // get version just now, it was not possible earlier if (!drv_getServerVersion(&d->serverVersion)) return false; } //-create system tables schema objects d->setupKDbSystemSchema(); if (kexiCompatible && my_dbName.compare(anyAvailableDatabaseName(), Qt::CaseInsensitive) != 0) { //-get global database information bool ok; const int major = d->dbProperties.value(QLatin1String("kexidb_major_ver")).toInt(&ok); if (!ok) { m_result = d->dbProperties.result(); return false; } const int minor = d->dbProperties.value(QLatin1String("kexidb_minor_ver")).toInt(&ok); if (!ok) { m_result = d->dbProperties.result(); return false; } d->databaseVersion.setMajor(major); d->databaseVersion.setMinor(minor); } d->usedDatabase = my_dbName; return true; } bool KDbConnection::closeDatabase() { if (d->usedDatabase.isEmpty()) return true; //no db used if (!checkConnected()) return true; bool ret = true; /*! @todo (js) add CLEVER algorithm here for nested transactions */ if (d->driver->transactionsSupported()) { //rollback all transactions d->dontRemoveTransactions = true; //lock! foreach(const KDbTransaction& tr, d->transactions) { if (!rollbackTransaction(tr)) {//rollback as much as you can, don't stop on prev. errors ret = false; } else { kdbDebug() << "transaction rolled back!"; kdbDebug() << "trans.refcount==" << (tr.m_data ? QString::number(tr.m_data->refcount()) : QLatin1String("(null)")); } } d->dontRemoveTransactions = false; //unlock! d->transactions.clear(); //free trans. data } //delete own cursors: d->deleteAllCursors(); //delete own schemas d->clearTables(); d->clearQueries(); if (!drv_closeDatabase()) return false; d->usedDatabase.clear(); return ret; } QString KDbConnection::currentDatabase() const { return d->usedDatabase; } bool KDbConnection::useTemporaryDatabaseIfNeeded(QString* name) { if (d->driver->behavior()->USE_TEMPORARY_DATABASE_FOR_CONNECTION_IF_NEEDED && !isDatabaseUsed()) { //we have no db used, but it is required by engine to have used any! *name = anyAvailableDatabaseName(); if (name->isEmpty()) { m_result = KDbResult(ERR_NO_DB_USED, tr("Could not find any database for temporary connection.")); return false; } const bool orig_skipDatabaseExistsCheckInUseDatabase = d->skipDatabaseExistsCheckInUseDatabase; d->skipDatabaseExistsCheckInUseDatabase = true; bool ret = useDatabase(*name, false); d->skipDatabaseExistsCheckInUseDatabase = orig_skipDatabaseExistsCheckInUseDatabase; if (!ret) { m_result = KDbResult(m_result.code(), tr("Error during starting temporary connection using \"%1\" database name.").arg(*name)); return false; } } return true; } bool KDbConnection::dropDatabase(const QString &dbName) { if (d->driver->behavior()->CONNECTION_REQUIRED_TO_DROP_DB && !checkConnected()) return false; QString dbToDrop; if (dbName.isEmpty() && d->usedDatabase.isEmpty()) { if (!d->driver->metaData()->isFileBased() || (d->driver->metaData()->isFileBased() && d->connData.databaseName().isEmpty())) { m_result = KDbResult(ERR_NO_NAME_SPECIFIED, tr("Could not delete database. Name is not specified.")); return false; } //this is a file driver so reuse previously passed filename dbToDrop = d->connData.databaseName(); } else { if (dbName.isEmpty()) { dbToDrop = d->usedDatabase; } else { if (d->driver->metaData()->isFileBased()) //lets get full path dbToDrop = QFileInfo(dbName).absoluteFilePath(); else dbToDrop = dbName; } } if (dbToDrop.isEmpty()) { m_result = KDbResult(ERR_NO_NAME_SPECIFIED, tr("Could not delete database. Name is not specified.")); return false; } if (d->driver->isSystemDatabaseName(dbToDrop)) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not delete system database \"%1\".").arg(dbToDrop)); return false; } if (isDatabaseUsed() && d->usedDatabase == dbToDrop) { //we need to close database because cannot drop used this database if (!closeDatabase()) return false; } QString tmpdbName; //some engines need to have opened any database before executing "drop database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return false; //ok, now we have access to dropping bool ret = drv_dropDatabase(dbToDrop); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } return ret; } QStringList KDbConnection::objectNames(int objectType, bool* ok) { if (!checkIsDatabaseUsed()) { if (ok) { *ok = false; } return QStringList(); } KDbEscapedString sql; if (objectType == KDb::AnyObjectType) { sql = "SELECT o_name FROM kexi__objects ORDER BY o_id"; } else { sql = KDbEscapedString("SELECT o_name FROM kexi__objects WHERE o_type=%1" " ORDER BY o_id").arg(d->driver->valueToSql(KDbField::Integer, objectType)); } QStringList list; const bool success = queryStringListInternal(&sql, &list, nullptr, nullptr, 0, KDb::isIdentifier); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of object names.")); } return list; } QStringList KDbConnection::tableNames(bool alsoSystemTables, bool* ok) { bool success; QStringList list = objectNames(KDb::TableObjectType, &success); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of table names.")); } if (alsoSystemTables && success) { list += kdbSystemTableNames(); } return list; } tristate KDbConnection::containsTable(const QString &tableName) { return drv_containsTable(tableName); } QStringList KDbConnection::kdbSystemTableNames() { return *g_kdbSystemTableNames; } KDbServerVersionInfo KDbConnection::serverVersion() const { return isConnected() ? d->serverVersion : KDbServerVersionInfo(); } KDbVersionInfo KDbConnection::databaseVersion() const { return isDatabaseUsed() ? d->databaseVersion : KDbVersionInfo(); } KDbProperties KDbConnection::databaseProperties() const { return d->dbProperties; } QList KDbConnection::tableIds(bool* ok) { return objectIds(KDb::TableObjectType, ok); } QList KDbConnection::queryIds(bool* ok) { return objectIds(KDb::QueryObjectType, ok); } QList KDbConnection::objectIds(int objectType, bool* ok) { if (!checkIsDatabaseUsed()) return QList(); KDbEscapedString sql; if (objectType == KDb::AnyObjectType) sql = "SELECT o_id, o_name FROM kexi__objects ORDER BY o_id"; else sql = "SELECT o_id, o_name FROM kexi__objects WHERE o_type=" + QByteArray::number(objectType) + " ORDER BY o_id"; KDbCursor *c = executeQuery(sql); if (!c) { if (ok) { *ok = false; } m_result.prependMessage(tr("Could not retrieve list of object identifiers.")); return QList(); } QList list; for (c->moveFirst(); !c->eof(); c->moveNext()) { QString tname = c->value(1).toString(); //kexi__objects.o_name if (KDb::isIdentifier(tname)) { list.append(c->value(0).toInt()); //kexi__objects.o_id } } deleteCursor(c); if (ok) { *ok = true; } return list; } //yeah, it is very efficient: #define C_A(a) , const QVariant& c ## a #define V_A0 d->driver->valueToSql( tableSchema->field(0), c0 ) #define V_A(a) + ',' + d->driver->valueToSql( \ tableSchema->field(a) ? tableSchema->field(a)->type() : KDbField::Text, c ## a ) // kdbDebug() << "******** " << QString("INSERT INTO ") + // escapeIdentifier(tableSchema->name()) + // " VALUES (" + vals + ")"; QSharedPointer KDbConnection::insertRecordInternal(const QString &tableSchemaName, KDbFieldList *fields, const KDbEscapedString &sql) { QSharedPointer res; if (!drv_beforeInsert(tableSchemaName,fields )) { return res; } res = prepareSql(sql); if (!res || res->lastResult().isError()) { res.clear(); return res; } if (!drv_afterInsert(tableSchemaName, fields)) { res.clear(); return res; } { // Fetching is needed to perform real execution at least for some backends. // Also we are not expecting record but let's delete if there's any. QSharedPointer record = res->fetchRecord(); Q_UNUSED(record) } if (res->lastResult().isError()) { res.clear(); } return res; } #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbTableSchema* tableSchema args) { \ return insertRecordInternal(tableSchema->name(), tableSchema, \ KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) \ + " (" \ + tableSchema->sqlFieldsList(this) \ + ") VALUES (" + vals + ')'); \ } #define C_INS_REC_ALL \ C_INS_REC( C_A(0), V_A0 ) \ C_INS_REC( C_A(0) C_A(1), V_A0 V_A(1) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2), V_A0 V_A(1) V_A(2) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3), V_A0 V_A(1) V_A(2) V_A(3) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6) C_A(7), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) V_A(7) ) C_INS_REC_ALL #undef V_A0 #undef V_A #undef C_INS_REC #define V_A0 value += d->driver->valueToSql( it.next(), c0 ); #define V_A( a ) value += (',' + d->driver->valueToSql( it.next(), c ## a )); #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbFieldList* fields args) \ { \ KDbEscapedString value; \ const KDbField::List *flist = fields->fields(); \ QListIterator it(*flist); \ vals \ it.toFront(); \ QString tableName((it.hasNext() && it.peekNext()->table()) ? it.next()->table()->name() : QLatin1String("??")); \ return insertRecordInternal(tableName, fields, \ KDbEscapedString(QLatin1String("INSERT INTO ") + escapeIdentifier(tableName)) \ + " (" + fields->sqlFieldsList(this) \ + ") VALUES (" + value + ')'); \ } C_INS_REC_ALL #undef C_A #undef V_A #undef V_ALAST #undef C_INS_REC #undef C_INS_REC_ALL QSharedPointer KDbConnection::insertRecord(KDbTableSchema *tableSchema, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = tableSchema->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); QList::ConstIterator it = values.constBegin(); KDbEscapedString sql; sql.reserve(4096); while (fieldsIt != flist->constEnd() && (it != values.end())) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) + " VALUES ("; } else { sql += ','; } sql += d->driver->valueToSql(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSql( f, *it ); ++it; ++fieldsIt; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableSchema->name(), tableSchema, sql); return res; } QSharedPointer KDbConnection::insertRecord(KDbFieldList *fields, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = fields->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); KDbEscapedString sql; sql.reserve(4096); QList::ConstIterator it = values.constBegin(); const QString tableName(flist->first()->table()->name()); while (fieldsIt != flist->constEnd() && it != values.constEnd()) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableName) + '(' + fields->sqlFieldsList(this) + ") VALUES ("; } else { sql += ','; } sql += d->driver->valueToSql(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSql( f, *it ); ++it; ++fieldsIt; if (fieldsIt == flist->constEnd()) break; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableName, fields, sql); return res; } inline static bool checkSql(const KDbEscapedString& sql, KDbResult* result) { Q_ASSERT(result); if (!sql.isValid()) { *result = KDbResult(ERR_SQL_EXECUTION_ERROR, KDbConnection::tr("SQL statement for execution is invalid or empty.")); result->setErrorSql(sql); //remember for error handling return false; } return true; } QSharedPointer KDbConnection::prepareSql(const KDbEscapedString& sql) { m_result.setSql(sql); return QSharedPointer(drv_prepareSql(sql)); } bool KDbConnection::executeSql(const KDbEscapedString& sql) { m_result.setSql(sql); if (!checkSql(sql, &m_result)) { return false; } if (!drv_executeSql(sql)) { m_result.setMessage(QString()); //clear as this could be most probably just "Unknown error" string. m_result.setErrorSql(sql); m_result.prependMessage(ERR_SQL_EXECUTION_ERROR, tr("Error while executing SQL statement.")); kdbWarning() << m_result; return false; } return true; } KDbField* KDbConnection::findSystemFieldName(const KDbFieldList& fieldlist) { for (KDbField::ListIterator it(fieldlist.fieldsIterator()); it != fieldlist.fieldsIteratorConstEnd(); ++it) { if (d->driver->isSystemFieldName((*it)->name())) return *it; } return nullptr; } //! Creates a KDbField list for kexi__fields, for sanity. Used by createTable() static KDbFieldList* createFieldListForKexi__Fields(KDbTableSchema *kexi__fieldsSchema) { if (!kexi__fieldsSchema) return nullptr; return kexi__fieldsSchema->subList( QList() << "t_id" << "f_type" << "f_name" << "f_length" << "f_precision" << "f_constraints" << "f_options" << "f_default" << "f_order" << "f_caption" << "f_help" ); } static QVariant buildLengthValue(const KDbField &f) { if (f.isFPNumericType()) { return f.scale(); } return f.maxLength(); } //! builds a list of values for field's @a f properties. Used by createTable(). static void buildValuesForKexi__Fields(QList& vals, KDbField* f) { const KDbField::Type type = f->type(); // cache: evaluating type of expressions can be expensive vals.clear(); vals << QVariant(f->table()->id()) << QVariant(type) << QVariant(f->name()) << buildLengthValue(*f) << QVariant(KDbField::isFPNumericType(type) ? f->precision() : 0) << QVariant(f->constraints()) << QVariant(f->options()) // KDb::variantToString() is needed here because the value can be of any QVariant type, // depending on f->type() << (f->defaultValue().isNull() ? QVariant() : QVariant(KDb::variantToString(f->defaultValue()))) << QVariant(f->order()) << QVariant(f->caption()) << QVariant(f->description()); } bool KDbConnection::storeMainFieldSchema(KDbField *field) { if (!field || !field->table()) return false; KDbFieldList *fl = createFieldListForKexi__Fields(d->table(QLatin1String("kexi__fields"))); if (!fl) return false; QList vals; buildValuesForKexi__Fields(vals, field); QList::ConstIterator valsIt = vals.constBegin(); bool first = true; KDbEscapedString sql("UPDATE kexi__fields SET "); foreach(KDbField *f, *fl->fields()) { sql.append((first ? QString() : QLatin1String(", ")) + f->name() + QLatin1Char('=') + d->driver->valueToSql(f, *valsIt)); if (first) first = false; ++valsIt; } delete fl; sql.append(KDbEscapedString(" WHERE t_id=%1 AND f_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, field->table()->id())) .arg(escapeString(field->name()))); return executeSql(sql); } #define createTable_ERR \ { kdbDebug() << "ERROR!"; \ m_result.prependMessage(KDbConnection::tr("Creating table failed.")); \ rollbackAutoCommitTransaction(tg.transaction()); \ return false; } bool KDbConnection::createTable(KDbTableSchema* tableSchema, CreateTableOptions options) { if (!tableSchema || !checkIsDatabaseUsed()) return false; //check if there are any fields if (tableSchema->fieldCount() < 1) { clearResult(); m_result = KDbResult(ERR_CANNOT_CREATE_EMPTY_OBJECT, tr("Could not create table without fields.")); return false; } KDbInternalTableSchema* internalTable = dynamic_cast(tableSchema); const QString tableName(tableSchema->name()); if (!internalTable) { if (d->driver->isSystemObjectName(tableName)) { clearResult(); m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("System name \"%1\" cannot be used as table name.") .arg(tableSchema->name())); return false; } KDbField *sys_field = findSystemFieldName(*tableSchema); if (sys_field) { clearResult(); m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("System name \"%1\" cannot be used as one of fields in \"%2\" table.") .arg(sys_field->name(), tableName)); return false; } } bool previousSchemaStillKept = false; KDbTableSchema *existingTable = nullptr; if (options & CreateTableOption::DropDestination) { //get previous table (do not retrieve, though) existingTable = this->tableSchema(tableName); if (existingTable) { if (existingTable == tableSchema) { clearResult(); m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Could not create the same table \"%1\" twice.").arg(tableSchema->name())); return false; } //! @todo (js) update any structure (e.g. queries) that depend on this table! if (existingTable->id() > 0) tableSchema->setId(existingTable->id()); //copy id from existing table previousSchemaStillKept = true; if (!dropTableInternal(existingTable, false /*alsoRemoveSchema*/)) return false; } } else { if (!internalTable && this->tableSchema(tableSchema->name())) { clearResult(); m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Table \"%1\" already exists.").arg(tableSchema->name())); return false; } } KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; if (internalTable) { if (!drv_containsTable(internalTable->name())) { // internal table may exist if (!drv_createTable(*tableSchema)) { createTable_ERR; } } } else { if (!drv_createTable(*tableSchema)) { createTable_ERR; } } //add the object data to kexi__* tables if (!internalTable) { //update kexi__objects if (!storeNewObjectData(tableSchema)) createTable_ERR; KDbTableSchema *ts = d->table(QLatin1String("kexi__fields")); if (!ts) return false; //for sanity: remove field info (if any) for this table id if (!KDb::deleteRecords(this, *ts, QLatin1String("t_id"), tableSchema->id())) return false; KDbFieldList *fl = createFieldListForKexi__Fields(ts); if (!fl) return false; foreach(KDbField *f, *tableSchema->fields()) { QList vals; buildValuesForKexi__Fields(vals, f); if (!insertRecord(fl, vals)) createTable_ERR; } delete fl; if (!storeExtendedTableSchemaData(tableSchema)) createTable_ERR; } bool res = commitAutoCommitTransaction(tg.transaction()); if (res) { if (!internalTable) { if (previousSchemaStillKept) { //remove previous table schema d->removeTable(*tableSchema); } } //store locally d->insertTable(tableSchema); //ok, this table is not created by the connection tableSchema->setConnection(this); } return res; } KDbTableSchema *KDbConnection::copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData) { clearResult(); if (this->tableSchema(tableSchema.name()) != &tableSchema) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableSchema.name())); return nullptr; } KDbTableSchema *copiedTable = new KDbTableSchema(tableSchema, false /* !copyId*/); // copy name, caption, description copiedTable->setName(newData.name()); copiedTable->setCaption(newData.caption()); copiedTable->setDescription(newData.description()); // copy the structure and data if (!createTable(copiedTable, CreateTableOptions(CreateTableOption::Default) & ~CreateTableOptions(CreateTableOption::DropDestination))) { delete copiedTable; return nullptr; } if (!drv_copyTableData(tableSchema, *copiedTable)) { dropTable(copiedTable); delete copiedTable; return nullptr; } return copiedTable; } KDbTableSchema *KDbConnection::copyTable(const QString &tableName, const KDbObject &newData) { clearResult(); KDbTableSchema* ts = tableSchema(tableName); if (!ts) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableName)); return nullptr; } return copyTable(*ts, newData); } bool KDbConnection::drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) { KDbEscapedString sql = KDbEscapedString("INSERT INTO %1 SELECT * FROM %2") .arg(escapeIdentifier(destinationTableSchema.name())) .arg(escapeIdentifier(tableSchema.name())); return executeSql(sql); } bool KDbConnection::removeObject(int objId) { clearResult(); //remove table schema from kexi__* tables KDbTableSchema *kexi__objects = d->table(QLatin1String("kexi__objects")); KDbTableSchema *kexi__objectdata = d->table(QLatin1String("kexi__objectdata")); if (!kexi__objects || !kexi__objectdata || !KDb::deleteRecords(this, *kexi__objects, QLatin1String("o_id"), objId) //schema entry || !KDb::deleteRecords(this, *kexi__objectdata, QLatin1String("o_id"), objId)) //data blocks { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Could not delete object's data.")); return false; } return true; } bool KDbConnection::drv_dropTable(const QString& tableName) { return executeSql(KDbEscapedString("DROP TABLE %1").arg(escapeIdentifier(tableName))); } tristate KDbConnection::dropTable(KDbTableSchema* tableSchema) { return dropTableInternal(tableSchema, true); } tristate KDbConnection::dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); if (!tableSchema) return false; //be sure that we handle the correct KDbTableSchema object: if (tableSchema->id() < 0 || this->tableSchema(tableSchema->name()) != tableSchema || this->tableSchema(tableSchema->id()) != tableSchema) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not delete table \"%1\". %2") .arg(tr("Unexpected name or identifier."), tableSchema->name())); return false; } tristate res = KDbTableSchemaChangeListener::closeListeners(this, tableSchema); if (true != res) return res; //sanity checks: if (d->driver->isSystemObjectName(tableSchema->name())) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not delete table \"%1\". %2") .arg(tableSchema->name(), d->strItIsASystemObject())); return false; } KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; //for sanity we're checking if this table exists physically const tristate result = drv_containsTable(tableSchema->name()); if (~result) { return cancelled; } if (result == true) { if (!drv_dropTable(tableSchema->name())) return false; } KDbTableSchema *ts = d->table(QLatin1String("kexi__fields")); if (!ts || !KDb::deleteRecords(this, *ts, QLatin1String("t_id"), tableSchema->id())) //field entries return false; //remove table schema from kexi__objects table if (!removeObject(tableSchema->id())) { return false; } if (alsoRemoveSchema) { //! @todo js: update any structure (e.g. queries) that depend on this table! tristate res = removeDataBlock(tableSchema->id(), QLatin1String("extended_schema")); if (!res) return false; d->removeTable(*tableSchema); } return commitAutoCommitTransaction(tg.transaction()); } tristate KDbConnection::dropTable(const QString& tableName) { clearResult(); KDbTableSchema* ts = tableSchema(tableName); if (!ts) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableName)); return false; } return dropTable(ts); } tristate KDbConnection::alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema) { clearResult(); tristate res = KDbTableSchemaChangeListener::closeListeners(this, tableSchema); if (true != res) return res; if (tableSchema == newTableSchema) { m_result = KDbResult(ERR_OBJECT_THE_SAME, tr("Could not alter table \"%1\" using the same table as destination.") .arg(tableSchema->name())); return false; } //! @todo (js) implement real altering //! @todo (js) update any structure (e.g. query) that depend on this table! bool ok = true; bool empty; #if 0 //! @todo uncomment: empty = isEmpty(tableSchema, ok) && ok; #else empty = true; #endif if (empty) { ok = createTable(newTableSchema, KDbConnection::CreateTableOption::Default | KDbConnection::CreateTableOption::DropDestination); } return ok; } bool KDbConnection::alterTableName(KDbTableSchema* tableSchema, const QString& newName, AlterTableNameOptions options) { clearResult(); if (tableSchema != this->tableSchema(tableSchema->id())) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Unknown table \"%1\".").arg(tableSchema->name())); return false; } if (newName.isEmpty() || !KDb::isIdentifier(newName)) { m_result = KDbResult(ERR_INVALID_IDENTIFIER, tr("Invalid table name \"%1\".").arg(newName)); return false; } const QString oldTableName = tableSchema->name(); const QString newTableName = newName.trimmed(); if (oldTableName.trimmed() == newTableName) { m_result = KDbResult(ERR_OBJECT_THE_SAME, tr("Could not rename table \"%1\" using the same name.") .arg(newTableName)); return false; } //! @todo alter table name for server DB backends! //! @todo what about objects (queries/forms) that use old name? KDbTableSchema *tableToReplace = this->tableSchema(newName); const bool destTableExists = tableToReplace != nullptr; const int origID = destTableExists ? tableToReplace->id() : -1; //will be reused in the new table if (!(options & AlterTableNameOption::DropDestination) && destTableExists) { m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Could not rename table \"%1\" to \"%2\". Table \"%3\" already exists.") .arg(tableSchema->name(), newName, newName)); return false; } //helper: #define alterTableName_ERR \ tableSchema->setName(oldTableName) //restore old name KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; // drop the table replaced (with schema) if (destTableExists) { if (!dropTable(newName)) { return false; } // the new table owns the previous table's id: if (!executeSql( KDbEscapedString("UPDATE kexi__objects SET o_id=%1 WHERE o_id=%2 AND o_type=%3") .arg(d->driver->valueToSql(KDbField::Integer, origID)) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())) .arg(d->driver->valueToSql(KDbField::Integer, int(KDb::TableObjectType))))) { return false; } if (!executeSql(KDbEscapedString("UPDATE kexi__fields SET t_id=%1 WHERE t_id=%2") .arg(d->driver->valueToSql(KDbField::Integer, origID)) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())))) { return false; } //maintain table ID d->changeTableId(tableSchema, origID); tableSchema->setId(origID); } if (!drv_alterTableName(tableSchema, newTableName)) { alterTableName_ERR; return false; } // Update kexi__objects //! @todo if (!executeSql(KDbEscapedString("UPDATE kexi__objects SET o_name=%1 WHERE o_id=%2") .arg(escapeString(tableSchema->name())) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())))) { alterTableName_ERR; return false; } //! @todo what about caption? //restore old name: it will be changed soon! tableSchema->setName(oldTableName); if (!commitAutoCommitTransaction(tg.transaction())) { alterTableName_ERR; return false; } //update tableSchema: d->renameTable(tableSchema, newTableName); return true; } bool KDbConnection::drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) { const QString oldTableName = tableSchema->name(); tableSchema->setName(newName); if (!executeSql(KDbEscapedString("ALTER TABLE %1 RENAME TO %2") .arg(KDbEscapedString(escapeIdentifier(oldTableName)), KDbEscapedString(escapeIdentifier(newName))))) { tableSchema->setName(oldTableName); //restore old name return false; } return true; } bool KDbConnection::dropQuery(KDbQuerySchema* querySchema) { clearResult(); if (!querySchema) return false; KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; //remove query schema from kexi__objects table if (!removeObject(querySchema->id())) { return false; } //! @todo update any structure that depend on this table! d->removeQuery(querySchema); return commitAutoCommitTransaction(tg.transaction()); } bool KDbConnection::dropQuery(const QString& queryName) { clearResult(); KDbQuerySchema* qs = querySchema(queryName); if (!qs) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Query \"%1\" does not exist.").arg(queryName)); return false; } return dropQuery(qs); } bool KDbConnection::drv_createTable(const KDbTableSchema& tableSchema) { const KDbNativeStatementBuilder builder(this, KDb::DriverEscaping); KDbEscapedString sql; if (!builder.generateCreateTableStatement(&sql,tableSchema)) { return false; } //kdbDebug() << "******** " << sql; return executeSql(sql); } bool KDbConnection::drv_createTable(const QString& tableName) { KDbTableSchema *ts = tableSchema(tableName); if (!ts) return false; return drv_createTable(*ts); } bool KDbConnection::beginAutoCommitTransaction(KDbTransactionGuard* tg) { if ((d->driver->behavior()->features & KDbDriver::IgnoreTransactions) || !d->autoCommit) { tg->setTransaction(KDbTransaction()); return true; } // commit current transaction (if present) for drivers // that allow single transaction per connection if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (d->defaultTransactionStartedInside) //only commit internally started transaction if (!commitTransaction(d->default_trans, KDbTransaction::CommitOption::IgnoreInactive)) { tg->setTransaction(KDbTransaction()); return false; //we have a real error } d->defaultTransactionStartedInside = d->default_trans.isNull(); if (!d->defaultTransactionStartedInside) { tg->setTransaction(d->default_trans); tg->doNothing(); return true; //reuse externally started transaction } } else if (!(d->driver->behavior()->features & KDbDriver::MultipleTransactions)) { tg->setTransaction(KDbTransaction()); return true; //no trans. supported at all - just return } tg->setTransaction(beginTransaction()); return !m_result.isError(); } bool KDbConnection::commitAutoCommitTransaction(const KDbTransaction& trans) { if (d->driver->behavior()->features & KDbDriver::IgnoreTransactions) return true; if (trans.isNull() || !d->driver->transactionsSupported()) return true; if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (!d->defaultTransactionStartedInside) //only commit internally started transaction return true; //give up } return commitTransaction(trans, KDbTransaction::CommitOption::IgnoreInactive); } bool KDbConnection::rollbackAutoCommitTransaction(const KDbTransaction& trans) { if (trans.isNull() || !d->driver->transactionsSupported()) return true; return rollbackTransaction(trans); } #define SET_ERR_TRANS_NOT_SUPP \ { m_result = KDbResult(ERR_UNSUPPORTED_DRV_FEATURE, \ KDbConnection::tr("Transactions are not supported for \"%1\" driver.").arg( d->driver->metaData()->name() )); } #define SET_BEGIN_TR_ERROR \ { if (!m_result.isError()) \ m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, \ KDbConnection::tr("Begin transaction failed.")); } KDbTransaction KDbConnection::beginTransaction() { if (!checkIsDatabaseUsed()) return KDbTransaction(); KDbTransaction trans; if (d->driver->behavior()->features & KDbDriver::IgnoreTransactions) { //we're creating dummy transaction data here, //so it will look like active trans.m_data = new KDbTransactionData(this); d->transactions.append(trans); return trans; } if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (d->default_trans.isActive()) { m_result = KDbResult(ERR_TRANSACTION_ACTIVE, tr("Transaction already started.")); return KDbTransaction(); } if (!(trans.m_data = drv_beginTransaction())) { SET_BEGIN_TR_ERROR; return KDbTransaction(); } d->default_trans = trans; d->transactions.append(trans); return d->default_trans; } if (d->driver->behavior()->features & KDbDriver::MultipleTransactions) { if (!(trans.m_data = drv_beginTransaction())) { SET_BEGIN_TR_ERROR; return KDbTransaction(); } d->transactions.append(trans); return trans; } SET_ERR_TRANS_NOT_SUPP; return KDbTransaction(); } bool KDbConnection::commitTransaction(const KDbTransaction trans, KDbTransaction::CommitOptions options) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.isActive()) { //try default tr. if (!d->default_trans.isActive()) { if (options & KDbTransaction::CommitOption::IgnoreInactive) { return true; } clearResult(); m_result = KDbResult(ERR_NO_TRANSACTION_ACTIVE, tr("Transaction not started.")); return false; } t = d->default_trans; d->default_trans = KDbTransaction(); //now: no default tr. } bool ret = true; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) ret = drv_commitTransaction(t.m_data); if (t.m_data) t.m_data->setActive(false); //now this transaction if inactive if (!d->dontRemoveTransactions) //true=transaction obj will be later removed from list d->transactions.removeAt(d->transactions.indexOf(t)); if (!ret && !m_result.isError()) m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, tr("Error on commit transaction.")); return ret; } bool KDbConnection::rollbackTransaction(const KDbTransaction trans, KDbTransaction::CommitOptions options) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.isActive()) { //try default tr. if (!d->default_trans.isActive()) { if (options & KDbTransaction::CommitOption::IgnoreInactive) { return true; } clearResult(); m_result = KDbResult(ERR_NO_TRANSACTION_ACTIVE, tr("Transaction not started.")); return false; } t = d->default_trans; d->default_trans = KDbTransaction(); //now: no default tr. } bool ret = true; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) ret = drv_rollbackTransaction(t.m_data); if (t.m_data) t.m_data->setActive(false); //now this transaction if inactive if (!d->dontRemoveTransactions) //true=transaction obj will be later removed from list d->transactions.removeAt(d->transactions.indexOf(t)); if (!ret && !m_result.isError()) m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, tr("Error on rollback transaction.")); return ret; } #undef SET_ERR_TRANS_NOT_SUPP #undef SET_BEGIN_TR_ERROR /*bool KDbConnection::duringTransaction() { return drv_duringTransaction(); }*/ KDbTransaction KDbConnection::defaultTransaction() const { return d->default_trans; } void KDbConnection::setDefaultTransaction(const KDbTransaction& trans) { if (!isDatabaseUsed()) return; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions) && (!trans.isActive() || !d->driver->transactionsSupported())) { return; } d->default_trans = trans; } QList KDbConnection::transactions() { return d->transactions; } bool KDbConnection::autoCommit() const { return d->autoCommit; } bool KDbConnection::setAutoCommit(bool on) { if (d->autoCommit == on || d->driver->behavior()->features & KDbDriver::IgnoreTransactions) return true; if (!drv_setAutoCommit(on)) return false; d->autoCommit = on; return true; } KDbTransactionData* KDbConnection::drv_beginTransaction() { if (!executeSql(KDbEscapedString("BEGIN"))) return nullptr; return new KDbTransactionData(this); } bool KDbConnection::drv_commitTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("COMMIT")); } bool KDbConnection::drv_rollbackTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("ROLLBACK")); } bool KDbConnection::drv_setAutoCommit(bool /*on*/) { return true; } KDbCursor* KDbConnection::executeQuery(const KDbEscapedString& sql, KDbCursor::Options options) { if (sql.isEmpty()) return nullptr; KDbCursor *c = prepareQuery(sql, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor *c = prepareQuery(query, params, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, KDbCursor::Options options) { return executeQuery(query, QList(), options); } KDbCursor* KDbConnection::executeQuery(KDbTableSchema* table, KDbCursor::Options options) { return executeQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbTableSchema* table, KDbCursor::Options options) { return prepareQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor* cursor = prepareQuery(query, options); if (cursor) cursor->setQueryParameters(params); return cursor; } bool KDbConnection::deleteCursor(KDbCursor *cursor) { if (!cursor) return false; if (cursor->connection() != this) {//illegal call kdbWarning() << "Could not delete the cursor not owned by the same connection!"; return false; } const bool ret = cursor->close(); CursorDeleter deleter(cursor); return ret; } //! @todo IMPORTANT: fix KDbConnection::setupObjectData() after refactoring bool KDbConnection::setupObjectData(const KDbRecordData &data, KDbObject *object) { if (data.count() < 5) { kdbWarning() << "Aborting, object data should have at least 5 elements, found" << data.count(); return false; } bool ok; const int id = data[0].toInt(&ok); if (!ok) return false; object->setId(id); const QString name(data[2].toString()); if (!KDb::isIdentifier(name)) { m_result = KDbResult(ERR_INVALID_IDENTIFIER, tr("Invalid object name \"%1\".").arg(name)); return false; } object->setName(name); object->setCaption(data[3].toString()); object->setDescription(data[4].toString()); // kdbDebug()<<"@@@ KDbConnection::setupObjectData() == " << sdata.schemaDataDebugString(); return true; } tristate KDbConnection::loadObjectData(int type, int id, KDbObject* object) { KDbRecordData data; if (type == KDb::AnyObjectType) { if (true != querySingleRecord(KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, " "o_desc FROM kexi__objects WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, id)), &data)) { return cancelled; } } else { if (true != querySingleRecord(KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc " "FROM kexi__objects WHERE o_type=%1 AND o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, type)) .arg(d->driver->valueToSql(KDbField::Integer, id)), &data)) { return cancelled; } } return setupObjectData(data, object); } tristate KDbConnection::loadObjectData(int type, const QString& name, KDbObject* object) { KDbRecordData data; if (true != querySingleRecord( KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc " "FROM kexi__objects WHERE o_type=%1 AND o_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, type)) .arg(escapeString(name)), &data)) { return cancelled; } return setupObjectData(data, object); } bool KDbConnection::storeObjectDataInternal(KDbObject* object, bool newObject) { KDbTableSchema *ts = d->table(QLatin1String("kexi__objects")); if (!ts) return false; if (newObject) { int existingID; if (true == querySingleNumber( KDbEscapedString("SELECT o_id FROM kexi__objects WHERE o_type=%1 AND o_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, object->type())) .arg(escapeString(object->name())), &existingID)) { //we already have stored an object data with the same name and type: //just update it's properties as it would be existing object object->setId(existingID); newObject = false; } } if (newObject) { if (object->id() <= 0) {//get new ID QScopedPointer fl(ts->subList( QList() << "o_type" << "o_name" << "o_caption" << "o_desc")); if (!fl) { return false; } QSharedPointer result = insertRecord(fl.data(), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); if (!result) { return false; } //fetch newly assigned ID //! @todo safe to cast it? quint64 obj_id = KDb::lastInsertedAutoIncValue(result, QLatin1String("o_id"), *ts); //kdbDebug() << "NEW obj_id == " << obj_id; if (obj_id == std::numeric_limits::max()) { return false; } object->setId(obj_id); return true; } else { QScopedPointer fl(ts->subList( QList() << "o_id" << "o_type" << "o_name" << "o_caption" << "o_desc")); return fl && insertRecord(fl.data(), QVariant(object->id()), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); } } //existing object: return executeSql( KDbEscapedString("UPDATE kexi__objects SET o_type=%2, o_caption=%3, o_desc=%4 WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, object->id())) .arg(d->driver->valueToSql(KDbField::Integer, object->type())) .arg(escapeString(object->caption())) .arg(escapeString(object->description()))); } bool KDbConnection::storeObjectData(KDbObject* object) { return storeObjectDataInternal(object, false); } bool KDbConnection::storeNewObjectData(KDbObject* object) { return storeObjectDataInternal(object, true); } QString KDbConnection::escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const { return escapingType == KDb::KDbEscaping ? KDb::escapeIdentifier(id) : escapeIdentifier(id); } KDbCursor* KDbConnection::executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params) { Q_ASSERT(!sql.isEmpty() || query); clearResult(); if (!sql.isEmpty()) { return executeQuery(sql); } if (!query) { return nullptr; } if (params) { return executeQuery(query, *params); } return executeQuery(query); } tristate KDbConnection::querySingleRecordInternal(KDbRecordData *data, const KDbEscapedString *sql, KDbQuerySchema *query, const QList *params, QueryRecordOptions options) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, options & QueryRecordOption::AddLimitTo1)); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!querySingleRecordInternal() " << m_result.sql(); return false; } if (!cursor->moveFirst() || cursor->eof() || !cursor->storeCurrentRecord(data)) { const tristate result = cursor->result().isError() ? tristate(false) : tristate(cancelled); // kdbDebug() << "!cursor->moveFirst() || cursor->eof() || cursor->storeCurrentRecord(data) // " // "m_result.sql()=" << m_result.sql(); m_result = cursor->result(); deleteCursor(cursor); return result; } return deleteCursor(cursor); } tristate KDbConnection::querySingleRecord(const KDbEscapedString &sql, KDbRecordData *data, QueryRecordOptions options) { return querySingleRecordInternal(data, &sql, nullptr, nullptr, options); } tristate KDbConnection::querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, QueryRecordOptions options) { return querySingleRecordInternal(data, nullptr, query, nullptr, options); } tristate KDbConnection::querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, const QList ¶ms, QueryRecordOptions options) { return querySingleRecordInternal(data, nullptr, query, ¶ms, options); } bool KDbConnection::checkIfColumnExists(KDbCursor *cursor, int column) { if (column >= cursor->fieldCount()) { m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Column \"%1\" does not exist in the query.").arg(column)); return false; } return true; } tristate KDbConnection::querySingleStringInternal(const KDbEscapedString *sql, QString *value, KDbQuerySchema *query, const QList *params, int column, QueryRecordOptions options) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, options & QueryRecordOption::AddLimitTo1)); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!querySingleStringInternal()" << m_result.sql(); return false; } if (!cursor->moveFirst() || cursor->eof()) { const tristate result = cursor->result().isError() ? tristate(false) : tristate(cancelled); // kdbDebug() << "!cursor->moveFirst() || cursor->eof()" << m_result.sql(); deleteCursor(cursor); return result; } if (!checkIfColumnExists(cursor, column)) { deleteCursor(cursor); return false; } if (value) { *value = cursor->value(column).toString(); } return deleteCursor(cursor); } tristate KDbConnection::querySingleString(const KDbEscapedString &sql, QString *value, int column, QueryRecordOptions options) { return querySingleStringInternal(&sql, value, nullptr, nullptr, column, options); } tristate KDbConnection::querySingleString(KDbQuerySchema *query, QString *value, int column, QueryRecordOptions options) { return querySingleStringInternal(nullptr, value, query, nullptr, column, options); } tristate KDbConnection::querySingleString(KDbQuerySchema *query, QString *value, const QList ¶ms, int column, QueryRecordOptions options) { return querySingleStringInternal(nullptr, value, query, ¶ms, column, options); } tristate KDbConnection::querySingleNumberInternal(const KDbEscapedString *sql, int *number, KDbQuerySchema *query, const QList *params, int column, QueryRecordOptions options) { QString str; const tristate result = querySingleStringInternal(sql, &str, query, params, column, options); if (result != true) return result; bool ok; const int _number = str.toInt(&ok); if (!ok) return false; if (number) { *number = _number; } return true; } tristate KDbConnection::querySingleNumber(const KDbEscapedString &sql, int *number, int column, QueryRecordOptions options) { return querySingleNumberInternal(&sql, number, nullptr, nullptr, column, options); } tristate KDbConnection::querySingleNumber(KDbQuerySchema *query, int *number, int column, QueryRecordOptions options) { return querySingleNumberInternal(nullptr, number, query, nullptr, column, options); } tristate KDbConnection::querySingleNumber(KDbQuerySchema *query, int *number, const QList ¶ms, int column, QueryRecordOptions options) { return querySingleNumberInternal(nullptr, number, query, ¶ms, column, options); } bool KDbConnection::queryStringListInternal(const KDbEscapedString *sql, QStringList *list, KDbQuerySchema *query, const QList *params, int column, bool (*filterFunction)(const QString &)) { if (sql) { m_result.setSql(*sql); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!queryStringListInternal() " << m_result.sql(); return false; } cursor->moveFirst(); if (cursor->result().isError()) { m_result = cursor->result(); deleteCursor(cursor); return false; } if (!cursor->eof() && !checkIfColumnExists(cursor, column)) { deleteCursor(cursor); return false; } if (list) { list->clear(); } QStringList listResult; while (!cursor->eof()) { const QString str(cursor->value(column).toString()); if (!filterFunction || filterFunction(str)) { listResult.append(str); } if (!cursor->moveNext() && cursor->result().isError()) { m_result = cursor->result(); deleteCursor(cursor); return false; } } if (list) { *list = listResult; } return deleteCursor(cursor); } bool KDbConnection::queryStringList(const KDbEscapedString& sql, QStringList* list, int column) { return queryStringListInternal(&sql, list, nullptr, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, int column) { return queryStringListInternal(nullptr, list, query, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column) { return queryStringListInternal(nullptr, list, query, ¶ms, column, nullptr); } tristate KDbConnection::resultExists(const KDbEscapedString &sql, QueryRecordOptions options) { // optimization if (d->driver->behavior()->SELECT_1_SUBQUERY_SUPPORTED) { // this is at least for sqlite if ((options & QueryRecordOption::AddLimitTo1) && sql.left(6).toUpper() == "SELECT") { m_result.setSql(d->driver->addLimitTo1("SELECT 1 FROM (" + sql + ')')); } else { m_result.setSql(sql); } } else { if ((options & QueryRecordOption::AddLimitTo1) && sql.startsWith("SELECT")) { m_result.setSql(d->driver->addLimitTo1(sql)); } else { m_result.setSql(sql); } } KDbCursor *cursor = executeQuery(m_result.sql()); if (!cursor) { kdbWarning() << "!executeQuery()" << m_result.sql(); return cancelled; } if (!cursor->moveFirst() || cursor->eof()) { kdbWarning() << "!cursor->moveFirst() || cursor->eof()" << m_result.sql(); m_result = cursor->result(); deleteCursor(cursor); return m_result.isError() ? cancelled : tristate(false); } return deleteCursor(cursor) ? tristate(true) : cancelled; } tristate KDbConnection::isEmpty(KDbTableSchema* table) { const KDbNativeStatementBuilder builder(this, KDb::DriverEscaping); KDbEscapedString sql; if (!builder.generateSelectStatement(&sql, table)) { return cancelled; } const tristate result = resultExists(sql); if (~result) { return cancelled; } return result == false; } //! Used by addFieldPropertyToExtendedTableSchemaData() static void createExtendedTableSchemaMainElementIfNeeded( QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, bool* extendedTableSchemaStringIsEmpty) { if (!*extendedTableSchemaStringIsEmpty) return; //init document *extendedTableSchemaMainEl = doc->createElement(QLatin1String("EXTENDED_TABLE_SCHEMA")); doc->appendChild(*extendedTableSchemaMainEl); extendedTableSchemaMainEl->setAttribute(QLatin1String("version"), QString::number(KDB_EXTENDED_TABLE_SCHEMA_VERSION)); *extendedTableSchemaStringIsEmpty = false; } //! Used by addFieldPropertyToExtendedTableSchemaData() static void createExtendedTableSchemaFieldElementIfNeeded(QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, const QString& fieldName, QDomElement* extendedTableSchemaFieldEl, bool append = true) { if (!extendedTableSchemaFieldEl->isNull()) return; *extendedTableSchemaFieldEl = doc->createElement(QLatin1String("field")); if (append) extendedTableSchemaMainEl->appendChild(*extendedTableSchemaFieldEl); extendedTableSchemaFieldEl->setAttribute(QLatin1String("name"), fieldName); } /*! @internal used by storeExtendedTableSchemaData() Creates DOM node for @a propertyName and @a propertyValue. Creates enclosing EXTENDED_TABLE_SCHEMA element if EXTENDED_TABLE_SCHEMA is true. Updates extendedTableSchemaStringIsEmpty and extendedTableSchemaMainEl afterwards. If extendedTableSchemaFieldEl is null, creates element (with optional "custom" attribute is @a custom is false). */ static void addFieldPropertyToExtendedTableSchemaData( const KDbField& f, const QByteArray &propertyName, const QVariant& propertyValue, QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, QDomElement* extendedTableSchemaFieldEl, bool* extendedTableSchemaStringIsEmpty, bool custom = false) { createExtendedTableSchemaMainElementIfNeeded(doc, extendedTableSchemaMainEl, extendedTableSchemaStringIsEmpty); createExtendedTableSchemaFieldElementIfNeeded( doc, extendedTableSchemaMainEl, f.name(), extendedTableSchemaFieldEl); //create QDomElement extendedTableSchemaFieldPropertyEl = doc->createElement(QLatin1String("property")); extendedTableSchemaFieldEl->appendChild(extendedTableSchemaFieldPropertyEl); if (custom) extendedTableSchemaFieldPropertyEl.setAttribute(QLatin1String("custom"), QLatin1String("true")); extendedTableSchemaFieldPropertyEl.setAttribute(QLatin1String("name"), QLatin1String(propertyName)); QDomElement extendedTableSchemaFieldPropertyValueEl; switch (propertyValue.type()) { case QVariant::String: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("string")); break; case QVariant::ByteArray: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("cstring")); break; case QVariant::Int: case QVariant::Double: case QVariant::UInt: case QVariant::LongLong: case QVariant::ULongLong: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("number")); break; case QVariant::Bool: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("bool")); break; default: //! @todo add more QVariant types kdbCritical() << "addFieldPropertyToExtendedTableSchemaData(): impl. error"; } extendedTableSchemaFieldPropertyEl.appendChild(extendedTableSchemaFieldPropertyValueEl); extendedTableSchemaFieldPropertyValueEl.appendChild( doc->createTextNode(propertyValue.toString())); } bool KDbConnection::storeExtendedTableSchemaData(KDbTableSchema* tableSchema) { //! @todo future: save in older versions if neeed QDomDocument doc(QLatin1String("EXTENDED_TABLE_SCHEMA")); QDomElement extendedTableSchemaMainEl; bool extendedTableSchemaStringIsEmpty = true; //for each field: foreach(KDbField* f, *tableSchema->fields()) { QDomElement extendedTableSchemaFieldEl; const KDbField::Type type = f->type(); // cache: evaluating type of expressions can be expensive if (f->visibleDecimalPlaces() >= 0/*nondefault*/ && KDb::supportsVisibleDecimalPlacesProperty(type)) { addFieldPropertyToExtendedTableSchemaData( *f, "visibleDecimalPlaces", f->visibleDecimalPlaces(), &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty); } if (type == KDbField::Text) { if (f->maxLengthStrategy() == KDbField::DefaultMaxLength) { addFieldPropertyToExtendedTableSchemaData( *f, "maxLengthIsDefault", true, &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty); } } // boolean field with "not null" // add custom properties const KDbField::CustomPropertiesMap customProperties(f->customProperties()); for (KDbField::CustomPropertiesMap::ConstIterator itCustom = customProperties.constBegin(); itCustom != customProperties.constEnd(); ++itCustom) { addFieldPropertyToExtendedTableSchemaData( *f, itCustom.key(), itCustom.value(), &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty, /*custom*/true); } // save lookup table specification, if present KDbLookupFieldSchema *lookupFieldSchema = tableSchema->lookupFieldSchema(*f); if (lookupFieldSchema) { createExtendedTableSchemaFieldElementIfNeeded( &doc, &extendedTableSchemaMainEl, f->name(), &extendedTableSchemaFieldEl, false/* !append */); lookupFieldSchema->saveToDom(&doc, &extendedTableSchemaFieldEl); if (extendedTableSchemaFieldEl.hasChildNodes()) { // this element provides the definition, so let's append it now createExtendedTableSchemaMainElementIfNeeded(&doc, &extendedTableSchemaMainEl, &extendedTableSchemaStringIsEmpty); extendedTableSchemaMainEl.appendChild(extendedTableSchemaFieldEl); } } } // Store extended schema information (see ExtendedTableSchemaInformation in Kexi Wiki) if (extendedTableSchemaStringIsEmpty) { #ifdef KDB_DEBUG_GUI KDb::alterTableActionDebugGUI(QLatin1String("** Extended table schema REMOVED.")); #endif if (!removeDataBlock(tableSchema->id(), QLatin1String("extended_schema"))) return false; } else { #ifdef KDB_DEBUG_GUI KDb::alterTableActionDebugGUI( QLatin1String("** Extended table schema set to:\n") + doc.toString(4)); #endif if (!storeDataBlock(tableSchema->id(), doc.toString(1), QLatin1String("extended_schema"))) return false; } return true; } bool KDbConnection::loadExtendedTableSchemaData(KDbTableSchema* tableSchema) { #define loadExtendedTableSchemaData_ERR \ { m_result = KDbResult(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } #define loadExtendedTableSchemaData_ERR2(details) \ { m_result = KDbResult(details); \ m_result.setMessageTitle(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } #define loadExtendedTableSchemaData_ERR3(data) \ { m_result = KDbResult(tr("Invalid XML data: %1").arg(data.left(1024))); \ m_result.setMessageTitle(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } // Load extended schema information, if present (see ExtendedTableSchemaInformation in Kexi Wiki) QString extendedTableSchemaString; tristate res = loadDataBlock(tableSchema->id(), &extendedTableSchemaString, QLatin1String("extended_schema")); if (!res) loadExtendedTableSchemaData_ERR; // extendedTableSchemaString will be just empty if there is no such data block if (extendedTableSchemaString.isEmpty()) return true; QDomDocument doc; QString errorMsg; int errorLine, errorColumn; if (!doc.setContent(extendedTableSchemaString, &errorMsg, &errorLine, &errorColumn)) { loadExtendedTableSchemaData_ERR2( tr("Error in XML data: \"%1\" in line %2, column %3.\nXML data: %4") .arg(errorMsg).arg(errorLine).arg(errorColumn).arg(extendedTableSchemaString.left(1024))); } //! @todo look at the current format version (KDB_EXTENDED_TABLE_SCHEMA_VERSION) if (doc.doctype().name() != QLatin1String("EXTENDED_TABLE_SCHEMA")) loadExtendedTableSchemaData_ERR3(extendedTableSchemaString); QDomElement docEl = doc.documentElement(); if (docEl.tagName() != QLatin1String("EXTENDED_TABLE_SCHEMA")) loadExtendedTableSchemaData_ERR3(extendedTableSchemaString); for (QDomNode n = docEl.firstChild(); !n.isNull(); n = n.nextSibling()) { QDomElement fieldEl = n.toElement(); if (fieldEl.tagName() == QLatin1String("field")) { KDbField *f = tableSchema->field(fieldEl.attribute(QLatin1String("name"))); if (f) { //set properties of the field: //! @todo more properties for (QDomNode propNode = fieldEl.firstChild(); !propNode.isNull(); propNode = propNode.nextSibling()) { const QDomElement propEl = propNode.toElement(); bool ok; int intValue; if (propEl.tagName() == QLatin1String("property")) { QByteArray propertyName = propEl.attribute(QLatin1String("name")).toLatin1(); if (propEl.attribute(QLatin1String("custom")) == QLatin1String("true")) { //custom property const QVariant v(KDb::loadPropertyValueFromDom(propEl.firstChild(), &ok)); if (ok) { f->setCustomProperty(propertyName, v); } } else if (propertyName == "visibleDecimalPlaces") { if (KDb::supportsVisibleDecimalPlacesProperty(f->type())) { intValue = KDb::loadIntPropertyValueFromDom(propEl.firstChild(), &ok); if (ok) f->setVisibleDecimalPlaces(intValue); } } else if (propertyName == "maxLengthIsDefault") { if (f->type() == KDbField::Text) { const bool maxLengthIsDefault = KDb::loadPropertyValueFromDom(propEl.firstChild(), &ok).toBool(); if (ok) { f->setMaxLengthStrategy( maxLengthIsDefault ? KDbField::DefaultMaxLength : KDbField::DefinedMaxLength); } } } //! @todo more properties... } else if (propEl.tagName() == QLatin1String("lookup-column")) { KDbLookupFieldSchema *lookupFieldSchema = KDbLookupFieldSchema::loadFromDom(propEl); if (lookupFieldSchema) { kdbDebug() << f->name() << *lookupFieldSchema; tableSchema->setLookupFieldSchema(f->name(), lookupFieldSchema); } } } } else { kdbWarning() << "no such field:" << fieldEl.attribute(QLatin1String("name")) << "in table:" << tableSchema->name(); } } } return true; } KDbField* KDbConnection::setupField(const KDbRecordData &data) { bool ok = true; int f_int_type = data.at(1).toInt(&ok); if (f_int_type <= KDbField::InvalidType || f_int_type > KDbField::LastType) ok = false; if (!ok) return nullptr; KDbField::Type f_type = (KDbField::Type)f_int_type; const int f_len = qMax(0, data.at(3).toInt(&ok)); // defined limit if (!ok) { return nullptr; } //! @todo load maxLengthStrategy info to see if the maxLength is the default int f_prec = data.at(4).toInt(&ok); if (!ok) return nullptr; KDbField::Constraints f_constr = (KDbField::Constraints)data.at(5).toInt(&ok); if (!ok) return nullptr; KDbField::Options f_opts = (KDbField::Options)data.at(6).toInt(&ok); if (!ok) return nullptr; QString name(data.at(2).toString()); if (!KDb::isIdentifier(name)) { name = KDb::stringToIdentifier(name); } KDbField *f = new KDbField( name, f_type, f_constr, f_opts, f_len, f_prec); QVariant defaultVariant = data.at(7); if (defaultVariant.isValid()) { defaultVariant = KDb::stringToVariant(defaultVariant.toString(), KDbField::variantType(f_type), &ok); if (ok) { f->setDefaultValue(defaultVariant); } else { kdbWarning() << "problem with KDb::stringToVariant(" << defaultVariant << ')'; ok = true; //problem with defaultValue is not critical } } f->setCaption(data.at(9).toString()); f->setDescription(data.at(10).toString()); return f; } KDbTableSchema* KDbConnection::tableSchema(const QString& tableName) { KDbTableSchema *t = d->table(tableName); if (t || tableName.isEmpty()) { return t; } //not found: retrieve schema QScopedPointer newTable(new KDbTableSchema); clearResult(); if (true != loadObjectData(KDb::TableObjectType, tableName, newTable.data())) { return nullptr; } return d->setupTableSchema(newTable.take()); } KDbTableSchema* KDbConnection::tableSchema(int tableId) { KDbTableSchema *t = d->table(tableId); if (t) return t; //not found: retrieve schema QScopedPointer newTable(new KDbTableSchema); clearResult(); if (true != loadObjectData(KDb::TableObjectType, tableId, newTable.data())) { return nullptr; } return d->setupTableSchema(newTable.take()); } tristate KDbConnection::loadDataBlock(int objectID, QString* dataString, const QString& dataID) { if (objectID <= 0) return false; return querySingleString( KDbEscapedString("SELECT o_data FROM kexi__objectdata WHERE o_id=%1 AND ") .arg(d->driver->valueToSql(KDbField::Integer, objectID)) + KDbEscapedString(KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID.isEmpty() ? QVariant() : QVariant(dataID))), dataString); } bool KDbConnection::storeDataBlock(int objectID, const QString &dataString, const QString& dataID) { if (objectID <= 0) return false; KDbEscapedString sql( KDbEscapedString("SELECT kexi__objectdata.o_id FROM kexi__objectdata WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, objectID))); KDbEscapedString sql_sub(KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID.isEmpty() ? QVariant() : QVariant(dataID))); const tristate result = resultExists(sql + " AND " + sql_sub); if (~result) { return false; } if (result == true) { return executeSql(KDbEscapedString("UPDATE kexi__objectdata SET o_data=%1 WHERE o_id=%2 AND ") .arg(d->driver->valueToSql(KDbField::LongText, dataString)) .arg(d->driver->valueToSql(KDbField::Integer, objectID)) + sql_sub); } return executeSql( KDbEscapedString("INSERT INTO kexi__objectdata (o_id, o_data, o_sub_id) VALUES (") + KDbEscapedString::number(objectID) + ',' + d->driver->valueToSql(KDbField::LongText, dataString) + ',' + d->driver->valueToSql(KDbField::Text, dataID) + ')'); } bool KDbConnection::copyDataBlock(int sourceObjectID, int destObjectID, const QString &dataID) { if (sourceObjectID <= 0 || destObjectID <= 0) return false; if (sourceObjectID == destObjectID) return true; if (!removeDataBlock(destObjectID, dataID)) // remove before copying return false; KDbEscapedString sql = KDbEscapedString( "INSERT INTO kexi__objectdata SELECT %1, t.o_data, t.o_sub_id " "FROM kexi__objectdata AS t WHERE o_id=%2") .arg(d->driver->valueToSql(KDbField::Integer, destObjectID)) .arg(d->driver->valueToSql(KDbField::Integer, sourceObjectID)); if (!dataID.isEmpty()) { sql += KDbEscapedString(" AND ") + KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID); } return executeSql(sql); } bool KDbConnection::removeDataBlock(int objectID, const QString& dataID) { if (objectID <= 0) return false; if (dataID.isEmpty()) return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), QString::number(objectID)); else return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), KDbField::Integer, objectID, QLatin1String("o_sub_id"), KDbField::Text, dataID); } KDbQuerySchema* KDbConnection::querySchema(const QString& aQueryName) { QString queryName = aQueryName.toLower(); KDbQuerySchema *q = d->query(queryName); if (q || queryName.isEmpty()) { return q; } //not found: retrieve schema QScopedPointer newQuery(new KDbQuerySchema); clearResult(); if (true != loadObjectData(KDb::QueryObjectType, aQueryName, newQuery.data())) { return nullptr; } return d->setupQuerySchema(newQuery.take()); } KDbQuerySchema* KDbConnection::querySchema(int queryId) { KDbQuerySchema *q = d->query(queryId); if (q) return q; //not found: retrieve schema QScopedPointer newQuery(new KDbQuerySchema); clearResult(); if (true != loadObjectData(KDb::QueryObjectType, queryId, newQuery.data())) { return nullptr; } return d->setupQuerySchema(newQuery.take()); } bool KDbConnection::setQuerySchemaObsolete(const QString& queryName) { KDbQuerySchema* oldQuery = querySchema(queryName); if (!oldQuery) return false; d->setQueryObsolete(oldQuery); return true; } QString KDbConnection::escapeIdentifier(const QString& id) const { return d->driver->escapeIdentifier(id); } bool KDbConnection::isInternalTableSchema(const QString& tableName) { KDbTableSchema* schema = d->table(tableName); return (schema && schema->isInternal()) // these are here for compatiblility because we're no longer instantiate // them but can exist in projects created with previous Kexi versions: || tableName == QLatin1String("kexi__final") || tableName == QLatin1String("kexi__useractions"); } void KDbConnection::removeMe(KDbTableSchema *table) { if (table && d) { d->takeTable(table); } } QString KDbConnection::anyAvailableDatabaseName() { if (!d->availableDatabaseName.isEmpty()) { return d->availableDatabaseName; } return d->driver->behavior()->ALWAYS_AVAILABLE_DATABASE_NAME; } void KDbConnection::setAvailableDatabaseName(const QString& dbName) { d->availableDatabaseName = dbName; } //! @internal used in updateRecord(), insertRecord(), inline static void updateRecordDataWithNewValues( KDbConnection *conn, KDbQuerySchema* query, KDbRecordData* data, const KDbRecordEditBuffer::DbHash& b, QHash* columnsOrderExpanded) { *columnsOrderExpanded = query->columnsOrder(conn, KDbQuerySchema::ColumnsOrderMode::ExpandedList); QHash::ConstIterator columnsOrderExpandedIt; for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { columnsOrderExpandedIt = columnsOrderExpanded->constFind(it.key()); if (columnsOrderExpandedIt == columnsOrderExpanded->constEnd()) { kdbWarning() << "(KDbConnection) \"now also assign new value in memory\" step" "- could not find item" << it.key()->aliasOrName(); continue; } (*data)[ columnsOrderExpandedIt.value() ] = it.value(); } } bool KDbConnection::updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { // Each SQL identifier needs to be escaped in the generated query. // kdbDebug() << *query; clearResult(); //--get PKEY if (buf->dbBuffer().isEmpty()) { kdbDebug() << " -- NO CHANGES DATA!"; return true; } KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_UPDATE_NO_MASTER_TABLE, tr("Could not update record because there is no master table defined.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; if (!useRecordId && !pkey) { kdbWarning() << " -- NO MASTER TABLE's PKEY!"; m_result = KDbResult(ERR_UPDATE_NO_MASTER_TABLES_PKEY, tr("Could not update record because master table has no primary key defined.")); //! @todo perhaps we can try to update without using PKEY? return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("UPDATE ") + escapeIdentifier(mt->name()) + " SET "; KDbEscapedString sqlset, sqlwhere; sqlset.reserve(1024); sqlwhere.reserve(1024); KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); //gather the fields which are updated ( have values in KDbRecordEditBuffer) KDbFieldList affectedFields; for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { if (it.key()->field()->table() != mt) continue; // skip values for fields outside of the master table (e.g. a "visible value" of the lookup field) if (!sqlset.isEmpty()) sqlset += ','; KDbField* currentField = it.key()->field(); const bool affectedFieldsAddOk = affectedFields.addField(currentField); Q_ASSERT(affectedFieldsAddOk); sqlset += KDbEscapedString(escapeIdentifier(currentField->name())) + '=' + d->driver->valueToSql(currentField, it.value()); } if (pkey) { const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount(this)) { //sanity check kdbWarning() << " -- NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_UPDATE_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not update record because it does not contain entire primary key of master table.")); return false; } if (!pkey->fields()->isEmpty()) { int i = 0; foreach(KDbField *f, *pkey->fields()) { if (!sqlwhere.isEmpty()) sqlwhere += " AND "; QVariant val(data->at(pkeyFieldsOrder.at(i))); if (val.isNull() || !val.isValid()) { m_result = KDbResult(ERR_UPDATE_NULL_PKEY_FIELD, tr("Primary key's field \"%1\" cannot be empty.").arg(f->name())); //js todo: pass the field's name somewhere! return false; } sqlwhere += KDbEscapedString(escapeIdentifier(f->name())) + '=' + d->driver->valueToSql(f, val); i++; } } } else { //use RecordId sqlwhere = KDbEscapedString(escapeIdentifier(d->driver->behavior()->ROW_ID_FIELD_NAME)) + '=' + d->driver->valueToSql(KDbField::BigInteger, (*data)[data->size() - 1]); } sql += (sqlset + " WHERE " + sqlwhere); //kdbDebug() << " -- SQL == " << ((sql.length() > 400) ? (sql.left(400) + "[.....]") : sql); // preprocessing before update if (!drv_beforeUpdate(mt->name(), &affectedFields)) return false; bool res = executeSql(sql); // postprocessing after update if (!drv_afterUpdate(mt->name(), &affectedFields)) return false; if (!res) { m_result = KDbResult(ERR_UPDATE_SERVER_ERROR, tr("Record updating on the server failed.")); return false; } //success: now also assign new values in memory: QHash columnsOrderExpanded; updateRecordDataWithNewValues(this, query, data, b, &columnsOrderExpanded); return true; } bool KDbConnection::insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); //--get PKEY /*disabled: there may be empty records (with autoinc) if (buf.dbBuffer().isEmpty()) { kdbDebug() << " -- NO CHANGES DATA!"; return true; }*/ KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_INSERT_NO_MASTER_TABLE, tr("Could not insert record because there is no master table specified.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; if (!getRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sqlcols, sqlvals; sqlcols.reserve(1024); sqlvals.reserve(1024); //insert the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(mt->name()) + " ("; KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); // add default values, if available (for any column without value explicitly set) const KDbQueryColumnInfo::Vector fieldsExpanded( query->fieldsExpanded(this, KDbQuerySchema::FieldsExpandedMode::Unique)); int fieldsExpandedCount = fieldsExpanded.count(); for (int i = 0; i < fieldsExpandedCount; i++) { KDbQueryColumnInfo *ci = fieldsExpanded.at(i); if (ci->field() && KDb::isDefaultValueAllowed(*ci->field()) && !ci->field()->defaultValue().isNull() && !b.contains(ci)) { //kdbDebug() << "adding default value" << ci->field->defaultValue().toString() << "for column" << ci->field->name(); b.insert(ci, ci->field()->defaultValue()); } } //collect fields which have values in KDbRecordEditBuffer KDbFieldList affectedFields; if (b.isEmpty()) { // empty record inserting requested: if (!getRecordId && !pkey) { kdbWarning() << "MASTER TABLE's PKEY REQUIRED FOR INSERTING EMPTY RECORDS: INSERT CANCELLED"; m_result = KDbResult(ERR_INSERT_NO_MASTER_TABLES_PKEY, tr("Could not insert record because master table has no primary key specified.")); return false; } if (pkey) { const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); // kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount(this)) { // sanity check kdbWarning() << "NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_INSERT_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not insert record because it does not contain " "entire master table's primary key.")); return false; } } //at least one value is needed for VALUES section: find it and set to NULL: KDbField *anyField = mt->anyNonPKField(); if (!anyField) { if (!pkey) { kdbWarning() << "WARNING: NO FIELD AVAILABLE TO SET IT TO NULL"; return false; } else { //try to set NULL in pkey field (could not work for every SQL engine!) anyField = pkey->fields()->first(); } } sqlcols += escapeIdentifier(anyField->name()); sqlvals += d->driver->valueToSql(anyField, QVariant()/*NULL*/); const bool affectedFieldsAddOk = affectedFields.addField(anyField); Q_ASSERT(affectedFieldsAddOk); } else { // non-empty record inserting requested: for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { if (it.key()->field()->table() != mt) continue; // skip values for fields outside of the master table (e.g. a "visible value" of the lookup field) if (!sqlcols.isEmpty()) { sqlcols += ','; sqlvals += ','; } KDbField* currentField = it.key()->field(); const bool affectedFieldsAddOk = affectedFields.addField(currentField); Q_ASSERT(affectedFieldsAddOk); sqlcols += escapeIdentifier(currentField->name()); sqlvals += d->driver->valueToSql(currentField, it.value()); } } sql += (sqlcols + ") VALUES (" + sqlvals + ')'); // kdbDebug() << " -- SQL == " << sql; // low-level insert QSharedPointer result = insertRecordInternal(mt->name(), &affectedFields, sql); if (!result) { m_result = KDbResult(ERR_INSERT_SERVER_ERROR, tr("Record inserting on the server failed.")); return false; } //success: now also assign a new value in memory: QHash columnsOrderExpanded; updateRecordDataWithNewValues(this, query, data, b, &columnsOrderExpanded); //fetch autoincremented values KDbQueryColumnInfo::List *aif_list = query->autoIncrementFields(this); quint64 recordId = 0; if (pkey && !aif_list->isEmpty()) { //! @todo now only if PKEY is present, this should also work when there's no PKEY KDbQueryColumnInfo *id_columnInfo = aif_list->first(); //! @todo safe to cast it? quint64 last_id = KDb::lastInsertedAutoIncValue(result, id_columnInfo->field()->name(), id_columnInfo->field()->table()->name(), &recordId); if (last_id == std::numeric_limits::max()) { //! @todo show error //! @todo remove just inserted record. How? Using ROLLBACK? return false; } KDbRecordData aif_data; KDbEscapedString getAutoIncForInsertedValue("SELECT " + query->autoIncrementSqlFieldsList(this) + " FROM " + escapeIdentifier(id_columnInfo->field()->table()->name()) + " WHERE " + escapeIdentifier(id_columnInfo->field()->name()) + '=' + QByteArray::number(last_id)); if (true != querySingleRecord(getAutoIncForInsertedValue, &aif_data)) { //! @todo show error return false; } int i = 0; foreach(KDbQueryColumnInfo *ci, *aif_list) { // kdbDebug() << "AUTOINCREMENTED FIELD" << fi->field->name() << "==" << aif_data[i].toInt(); ((*data)[ columnsOrderExpanded.value(ci)] = aif_data.value(i)).convert(ci->field()->variantType()); //cast to get proper type i++; } } else { recordId = result->lastInsertRecordId(); // kdbDebug() << "new recordId ==" << recordId; if (d->driver->behavior()->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE) { kdbWarning() << "d->driver->behavior()->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE"; return false; } } if (getRecordId && /*sanity check*/data->size() > fieldsExpanded.size()) { // kdbDebug() << "new ROWID ==" << ROWID; (*data)[data->size() - 1] = recordId; } return true; } bool KDbConnection::deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_DELETE_NO_MASTER_TABLE, tr("Could not delete record because there is no master table specified.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; //! @todo allow to delete from a table without pkey if (!useRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; m_result = KDbResult(ERR_DELETE_NO_MASTER_TABLES_PKEY, tr("Could not delete record because there is no primary key for master table specified.")); return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()) + " WHERE "; KDbEscapedString sqlwhere; sqlwhere.reserve(1024); if (pkey) { const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount(this)) { //sanity check kdbWarning() << " -- NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_DELETE_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not delete record because it does not contain entire master table's primary key.")); return false; } int i = 0; foreach(KDbField *f, *pkey->fields()) { if (!sqlwhere.isEmpty()) sqlwhere += " AND "; QVariant val(data->at(pkeyFieldsOrder.at(i))); if (val.isNull() || !val.isValid()) { m_result = KDbResult(ERR_DELETE_NULL_PKEY_FIELD, tr("Primary key's field \"%1\" cannot be empty.").arg(f->name())); //js todo: pass the field's name somewhere! return false; } sqlwhere += KDbEscapedString(escapeIdentifier(f->name())) + '=' + d->driver->valueToSql(f, val); i++; } } else {//use RecordId sqlwhere = KDbEscapedString(escapeIdentifier(d->driver->behavior()->ROW_ID_FIELD_NAME)) + '=' + d->driver->valueToSql(KDbField::BigInteger, (*data)[data->size() - 1]); } sql += sqlwhere; //kdbDebug() << " -- SQL == " << sql; if (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } bool KDbConnection::deleteAllRecords(KDbQuerySchema* query) { clearResult(); KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; return false; } KDbIndexSchema *pkey = mt->primaryKey(); if (!pkey || pkey->fields()->isEmpty()) { kdbWarning() << "-- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()); //kdbDebug() << "-- SQL == " << sql; if (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } int KDbConnection::recordCount(const KDbEscapedString& sql) { int count = -1; //will be changed only on success of querySingleNumber() const tristate result = querySingleNumber( KDbEscapedString("SELECT COUNT() FROM (") + sql + ") AS kdb__subquery", &count); if (~result) { count = 0; } return count; } int KDbConnection::recordCount(const KDbTableSchema& tableSchema) { //! @todo does not work with non-SQL data sources int count = -1; // will be changed only on success of querySingleNumber() const tristate result = querySingleNumber(KDbEscapedString("SELECT COUNT(*) FROM ") + tableSchema.connection()->escapeIdentifier(tableSchema.name()), &count); if (~result) { count = 0; } return count; } int KDbConnection::recordCount(KDbQuerySchema* querySchema, const QList& params) { //! @todo does not work with non-SQL data sources int count = -1; //will be changed only on success of querySingleNumber() KDbNativeStatementBuilder builder(this, KDb::DriverEscaping); KDbEscapedString subSql; if (!builder.generateSelectStatement(&subSql, querySchema, params)) { return -1; } const tristate result = querySingleNumber( KDbEscapedString("SELECT COUNT(*) FROM (") + subSql + ") AS kdb__subquery", &count); if (~result) { count = 0; } return count; } int KDbConnection::recordCount(KDbTableOrQuerySchema* tableOrQuery, const QList& params) { if (tableOrQuery) { if (tableOrQuery->table()) return recordCount(*tableOrQuery->table()); if (tableOrQuery->query()) return recordCount(tableOrQuery->query(), params); } return -1; } KDbConnectionOptions* KDbConnection::options() { return &d->options; } void KDbConnection::addCursor(KDbCursor* cursor) { d->cursors.insert(cursor); } void KDbConnection::takeCursor(KDbCursor* cursor) { if (d && !d->cursors.isEmpty()) { // checking because this may be called from ~KDbConnection() d->cursors.remove(cursor); } } KDbPreparedStatement KDbConnection::prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames) { //! @todo move to ConnectionInterface just like we moved execute() and prepare() to KDbPreparedStatementInterface... KDbPreparedStatementInterface *iface = prepareStatementInternal(); if (!iface) return KDbPreparedStatement(); return KDbPreparedStatement(iface, type, fields, whereFieldNames); } KDbEscapedString KDbConnection::recentSqlString() const { return result().errorSql().isEmpty() ? m_result.sql() : result().errorSql(); } KDbEscapedString KDbConnection::escapeString(const QString& str) const { return d->driver->escapeString(str); } //! @todo extraMessages #if 0 static const char *extraMessages[] = { QT_TRANSLATE_NOOP("KDbConnection", "Unknown error.") }; #endif diff --git a/src/KDbConnection.h b/src/KDbConnection.h index 360de03a..4372752a 100644 --- a/src/KDbConnection.h +++ b/src/KDbConnection.h @@ -1,1419 +1,1420 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 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; /*! @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; /*! 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; /*! @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; /*! @overload */ KDbCursor* executeQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! @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; /*! 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; /** * 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. 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; /** * 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; /*! 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; /*! 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 KDbTableSchemaChangeListener; + 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/KDbConnection_p.h b/src/KDbConnection_p.h index 618c0aa9..9cf4e85d 100644 --- a/src/KDbConnection_p.h +++ b/src/KDbConnection_p.h @@ -1,209 +1,211 @@ /* 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 pointed by tableSchema.id() and tableSchema.name() from internal structures and destroys it. Does not make any change at the backend. Note that the table schema being removed may be not the same as @a tableSchema. */ void removeTable(const KDbTableSchema& tableSchema); 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; /*! @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; //! @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); 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/KDbTableSchemaChangeListener.cpp b/src/KDbTableSchemaChangeListener.cpp index 7c007a9e..343ab1c5 100644 --- a/src/KDbTableSchemaChangeListener.cpp +++ b/src/KDbTableSchemaChangeListener.cpp @@ -1,112 +1,571 @@ /* This file is part of the KDE project - Copyright (C) 2003-2016 Jarosław Staniek + Copyright (C) 2003-2017 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. */ #include "KDbTableSchemaChangeListener.h" #include "KDbConnection.h" #include "KDbConnection_p.h" +#include "KDbLookupFieldSchema.h" +#include "kdb_debug.h" -class Q_DECL_HIDDEN KDbTableSchemaChangeListener::Private +#ifdef KDB_TABLESCHEMACHANGELISTENER_DEBUG +# define localDebug(...) kdbDebug(__VA_ARGS__) +#else +# define localDebug(...) if (true) {} else kdbDebug(__VA_ARGS__) +#endif + +class KDbTableSchemaChangeListenerPrivate { public: - Private() {} + KDbTableSchemaChangeListenerPrivate() + { + } + + //! Registers listener @a listener for changes in table @a table + static void registerForChanges(KDbConnection *conn, KDbTableSchemaChangeListener *listener, + const KDbTableSchema *table) + { + Q_ASSERT(conn); + Q_ASSERT(listener); + Q_ASSERT(table); + QSet* listeners = conn->d->tableSchemaChangeListeners.value(table); + if (!listeners) { + listeners = new QSet(); + conn->d->tableSchemaChangeListeners.insert(table, listeners); + } + localDebug() << "listener=" << listener->name() << "table=" << table->name(); + listeners->insert(listener); + } + + //! Registers listener @a listener for changes in query @a query + static void registerForChanges(KDbConnection *conn, KDbTableSchemaChangeListener *listener, + const KDbQuerySchema *query) + { + Q_ASSERT(conn); + Q_ASSERT(listener); + Q_ASSERT(query); + QSet *listeners + = conn->d->queryTableSchemaChangeListeners.value(query); + if (!listeners) { + listeners = new QSet(); + conn->d->queryTableSchemaChangeListeners.insert(query, listeners); + } + localDebug() << "listener=" << listener->name() << "query=" << query->name(); + listeners->insert(listener); + } + + //! Unregisters listener @a listener for changes in table @a table + static void unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener *listener, + const KDbTableSchema *table) + { + Q_ASSERT(conn); + Q_ASSERT(table); + QSet *listeners + = conn->d->tableSchemaChangeListeners.value(table); + if (!listeners) { + return; + } + localDebug() << "listener=" << (listener ? listener->name() : QString::fromLatin1("")) + << "table=" << table->name(); + if (listener) { + listeners->remove(listener); + } else { + listeners->clear(); + } + } + + //! Unregisters listener @a listener for changes in query @a query + static void unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener *listener, + const KDbQuerySchema *query) + { + Q_ASSERT(conn); + Q_ASSERT(query); + QSet *listeners + = conn->d->queryTableSchemaChangeListeners.value(query); + if (!listeners) { + return; + } + localDebug() << "listener=" << (listener ? listener->name() : QString::fromLatin1("")) + << "query=" << query->name(); + if (listener) { + listeners->remove(listener); + } else { + listeners->clear(); + } + } + + //! Unregisters listener @a listener for any changes + static void unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener) + { + Q_ASSERT(conn); + Q_ASSERT(listener); + localDebug() << "listener=" << listener->name(); + for (QSet *listeners : conn->d->tableSchemaChangeListeners) { + listeners->remove(listener); + } + for (QSet *listeners : conn->d->queryTableSchemaChangeListeners) { + listeners->remove(listener); + } + } + + //! Returns @c true if @a table1 depends on @a table2, that is, if: + //! - @a table1 == @a table2, or + //! - @a table1 has lookup columns that reference @a table2 + static bool tableDependsOnTable(QSet *checkedTables, + QSet *checkedQueries, + KDbConnection *conn, const KDbTableSchema *table1, + const KDbTableSchema *table2) + { + if (checkedTables->contains(table1)) { + localDebug() << "Table" << table1->name() << "already checked"; + return false; // protection against infinite recursion + } + checkedTables->insert(table1); + localDebug() << "Checking if table" << table1->name() << "depends on table" << table2->name(); + if (table1 == table2) { + localDebug() << "Yes"; + return true; + } + for (KDbLookupFieldSchema *lookup : table1->lookupFields()) { + switch (lookup->recordSource().type()) { + case KDbLookupFieldSchemaRecordSource::Type::Table: { + const KDbTableSchema *sourceTable + = conn->tableSchema(lookup->recordSource().name()); + if (sourceTable + && tableDependsOnTable(checkedTables, checkedQueries, conn, sourceTable, table2)) + { + return true; + } + break; + } + case KDbLookupFieldSchemaRecordSource::Type::Query: { + const KDbQuerySchema *sourceQuery + = conn->querySchema(lookup->recordSource().name()); + if (sourceQuery + && queryDependsOnTable(checkedTables, checkedQueries, conn, sourceQuery, table2)) + { + return true; + } + break; + } + default: + kdbWarning() << "Unsupported lookup field's source type" << lookup->recordSource().typeName(); + //! @todo support more record source types + break; + } + } + return false; + } + + //! Returns @c true if @a table depends on @a query, that is, if: + //! - @a table has lookup columns that reference @a query + static bool tableDependsOnQuery(QSet *checkedTables, + QSet *checkedQueries, + KDbConnection *conn, const KDbTableSchema *table, + const KDbQuerySchema *query) + { + if (checkedTables->contains(table)) { + localDebug() << "Table" << table->name() << "already checked"; + return false; // protection against infinite recursion + } + checkedTables->insert(table); + localDebug() << "Checking if table" << table->name() << "depends on query" << query->name(); + for (KDbLookupFieldSchema *lookup : table->lookupFields()) { + switch (lookup->recordSource().type()) { + case KDbLookupFieldSchemaRecordSource::Type::Table: { + const KDbTableSchema *sourceTable + = conn->tableSchema(lookup->recordSource().name()); + if (sourceTable + && tableDependsOnQuery(checkedTables, checkedQueries, conn, sourceTable, query)) + { + return true; + } + break; + } + case KDbLookupFieldSchemaRecordSource::Type::Query: { + const KDbQuerySchema *sourceQuery + = conn->querySchema(lookup->recordSource().name()); + if (sourceQuery + && queryDependsOnQuery(checkedTables, checkedQueries, conn, sourceQuery, query)) + { + return true; + } + break; + } + default: + kdbWarning() << "Unsupported lookup field's source type" << lookup->recordSource().typeName(); + //! @todo support more record source types + } + } + return false; + } + + //! Returns @c true if @a query depends on @a table, that is, if: + //! - @a query references table that depends on @a table (dependency is checked using + //! tableDependsOnTable()) + static bool queryDependsOnTable(QSet *checkedTables, + QSet *checkedQueries, + KDbConnection *conn, const KDbQuerySchema *query, + const KDbTableSchema *table) + { + if (checkedQueries->contains(query)) { + localDebug() << "Query" << query->name() << "already checked"; + return false; // protection against infinite recursion + } + checkedQueries->insert(query); + localDebug() << "Checking if query" << query->name() << "depends on table" << table->name(); + for (const KDbTableSchema *queryTable : *query->tables()) { + if (tableDependsOnTable(checkedTables, checkedQueries, conn, queryTable, table)) { + return true; + } + } + return false; + } + + //! Returns @c true if @a query1 depends on @a query2, that is, if: + //! - @a query1 == @a query2, or + //! - @a query2 references table that depends on @a query (dependency is checked using + //! tableDependsOnQuery()) + static bool queryDependsOnQuery(QSet *checkedTables, + QSet *checkedQueries, + KDbConnection *conn, const KDbQuerySchema *query1, + const KDbQuerySchema *query2) + { + if (checkedQueries->contains(query1)) { + localDebug() << "Query" << query1->name() << "already checked"; + return false; // protection against infinite recursion + } + checkedQueries->insert(query1); + localDebug() << "Checking if query" << query1->name() << "depends on query" << query2->name(); + if (query1 == query2) { + localDebug() << "Yes"; + return true; + } + for (const KDbTableSchema *queryTable : *query1->tables()) { + if (tableDependsOnQuery(checkedTables, checkedQueries, conn, queryTable, query2)) { + return true; + } + } + return false; + } + + //! Inserts to @a *result all listeners that listen to changes in table @a table and other tables + //! or queries depending on @a table. + static void collectListeners(QSet *result, + KDbConnection *conn, + const KDbTableSchema *table) + { + Q_ASSERT(result); + Q_ASSERT(conn); + Q_ASSERT(table); + // for all tables with listeners: + for (QHash* >::ConstIterator it( + conn->d->tableSchemaChangeListeners.constBegin()); + it != conn->d->tableSchemaChangeListeners.constEnd(); ++it) + { + // check if it depends on our table + QSet checkedTables; + QSet checkedQueries; + if (tableDependsOnTable(&checkedTables, &checkedQueries, conn, it.key(), table)) { + QSet* set = it.value(); + result->unite(*set); + } + } + // for all queries with listeners: + for (QHash* >::ConstIterator it( + conn->d->queryTableSchemaChangeListeners.constBegin()); + it != conn->d->queryTableSchemaChangeListeners.constEnd(); ++it) + { + // check if it depends on our table + QSet checkedTables; + QSet checkedQueries; + if (queryDependsOnTable(&checkedTables, &checkedQueries, conn, it.key(), table)) { + QSet* set = it.value(); + result->unite(*set); + } + } + } + + //! Inserts to @a *result all listeners that listen to changes in query @a table and other tables + //! or queries depending on @a query. + static void collectListeners(QSet *result, + KDbConnection *conn, + const KDbQuerySchema *query) + { + Q_ASSERT(result); + Q_ASSERT(conn); + Q_ASSERT(query); + QSet* set = conn->d->queryTableSchemaChangeListeners.value(query); + if (set) { + result->unite(*set); + } + // for all tables with listeners: + for (QHash* >::ConstIterator it( + conn->d->tableSchemaChangeListeners.constBegin()); + it != conn->d->tableSchemaChangeListeners.constEnd(); ++it) + { + // check if it depends on our query + QSet checkedTables; + QSet checkedQueries; + if (tableDependsOnQuery(&checkedTables, &checkedQueries, conn, it.key(), query)) { + QSet* set = it.value(); + result->unite(*set); + } + } + // for all queries with listeners: + for (QHash* >::ConstIterator it( + conn->d->queryTableSchemaChangeListeners.constBegin()); + it != conn->d->queryTableSchemaChangeListeners.constEnd(); ++it) + { + // check if it depends on our query + QSet checkedTables; + QSet checkedQueries; + if (queryDependsOnQuery(&checkedTables, &checkedQueries, conn, it.key(), query)) { + QSet* set = it.value(); + result->unite(*set); + } + } + } + QString name; - Q_DISABLE_COPY(Private) + Q_DISABLE_COPY(KDbTableSchemaChangeListenerPrivate) }; KDbTableSchemaChangeListener::KDbTableSchemaChangeListener() - : d(new Private) + : d(new KDbTableSchemaChangeListenerPrivate) { } KDbTableSchemaChangeListener::~KDbTableSchemaChangeListener() { delete d; } QString KDbTableSchemaChangeListener::name() const { return d->name; } void KDbTableSchemaChangeListener::setName(const QString &name) { d->name = name; } // static void KDbTableSchemaChangeListener::registerForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener, const KDbTableSchema* table) { - QSet* listeners = conn->d->tableSchemaChangeListeners.value(table); - if (!listeners) { - listeners = new QSet(); - conn->d->tableSchemaChangeListeners.insert(table, listeners); + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!listener) { + kdbWarning() << "Missing listener"; + return; + } + if (!table) { + kdbWarning() << "Missing table"; + return; + } + KDbTableSchemaChangeListenerPrivate::registerForChanges(conn, listener, table); +} + +// static +void KDbTableSchemaChangeListener::registerForChanges(KDbConnection *conn, + KDbTableSchemaChangeListener *listener, + const KDbQuerySchema *query) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!listener) { + kdbWarning() << "Missing listener"; + return; + } + if (!query) { + kdbWarning() << "Missing query"; + return; } - listeners->insert(listener); + KDbTableSchemaChangeListenerPrivate::registerForChanges(conn, listener, query); } // static void KDbTableSchemaChangeListener::unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener, const KDbTableSchema* table) { - QSet* listeners = conn->d->tableSchemaChangeListeners.value(table); - if (!listeners) + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!listener) { + kdbWarning() << "Missing listener"; return; - listeners->remove(listener); + } + if (!table) { + kdbWarning() << "Missing table"; + return; + } + KDbTableSchemaChangeListenerPrivate::unregisterForChanges(conn, listener, table); } // static void KDbTableSchemaChangeListener::unregisterForChanges(KDbConnection *conn, - KDbTableSchemaChangeListener* listener) + const KDbTableSchema* table) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!table) { + kdbWarning() << "Missing table"; + return; + } + KDbTableSchemaChangeListenerPrivate::unregisterForChanges(conn, nullptr, table); +} + +void KDbTableSchemaChangeListener::unregisterForChanges(KDbConnection *conn, + KDbTableSchemaChangeListener *listener, + const KDbQuerySchema *query) { - foreach(QSet *listeners, conn->d->tableSchemaChangeListeners) { - listeners->remove(listener); + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!listener) { + kdbWarning() << "Missing listener"; + return; + } + if (!query) { + kdbWarning() << "Missing query"; + return; } + KDbTableSchemaChangeListenerPrivate::unregisterForChanges(conn, listener, query); +} + +// static +void KDbTableSchemaChangeListener::unregisterForChanges(KDbConnection *conn, + const KDbQuerySchema *query) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!query) { + kdbWarning() << "Missing query"; + return; + } + KDbTableSchemaChangeListenerPrivate::unregisterForChanges(conn, nullptr, query); +} + +// static +void KDbTableSchemaChangeListener::unregisterForChanges( + KDbConnection *conn, KDbTableSchemaChangeListener* listener) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return; + } + if (!listener) { + kdbWarning() << "Missing listener"; + return; + } + KDbTableSchemaChangeListenerPrivate::unregisterForChanges(conn, listener); } // static QList KDbTableSchemaChangeListener::listeners( - const KDbConnection *conn, const KDbTableSchema* table) + KDbConnection *conn, const KDbTableSchema* table) { - //kdbDebug() << d->tableSchemaChangeListeners.count(); - QSet* set = conn->d->tableSchemaChangeListeners.value(table); - return set ? set->toList() : QList(); + if (!conn) { + kdbWarning() << "Missing connection"; + return QList(); + } + if (!table) { + kdbWarning() << "Missing table"; + return QList(); + } + QSet result; + KDbTableSchemaChangeListenerPrivate::collectListeners(&result, conn, table); + return result.toList(); } // static -tristate KDbTableSchemaChangeListener::closeListeners(KDbConnection *conn, const KDbTableSchema* table) +QList KDbTableSchemaChangeListener::listeners( + KDbConnection *conn, const KDbQuerySchema *query) { - QSet *listeners = conn->d->tableSchemaChangeListeners.value(table); - if (!listeners) { - return true; + if (!conn) { + kdbWarning() << "Missing connection"; + return QList(); + } + if (!query) { + kdbWarning() << "Missing query"; + return QList(); } + QSet result; + KDbTableSchemaChangeListenerPrivate::collectListeners(&result, conn, query); + return result.toList(); +} - //try to close every window - tristate res = true; - QList list(listeners->toList()); - foreach (KDbTableSchemaChangeListener* listener, list) { +// static +tristate KDbTableSchemaChangeListener::closeListeners(KDbConnection *conn, + const KDbTableSchema *table, const QList &except) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return false; + } + if (!table) { + kdbWarning() << "Missing table"; + return false; + } + QSet toClose(listeners(conn, table).toSet().subtract(except.toSet())); + tristate result = true; + for (KDbTableSchemaChangeListener *listener : toClose) { + const tristate localResult = listener->closeListener(); + if (localResult != true) { + result = localResult; + } + } + return result; +} + +// static +tristate KDbTableSchemaChangeListener::closeListeners(KDbConnection *conn, + const KDbQuerySchema *query, const QList &except) +{ + if (!conn) { + kdbWarning() << "Missing connection"; + return false; + } + if (!query) { + kdbWarning() << "Missing query"; + return false; + } + QSet toClose(listeners(conn, query).toSet().subtract(except.toSet())); + tristate result = true; + for (KDbTableSchemaChangeListener *listener : toClose) { const tristate localResult = listener->closeListener(); if (localResult != true) { - res = localResult; + result = localResult; } } - return res; + return result; } diff --git a/src/KDbTableSchemaChangeListener.h b/src/KDbTableSchemaChangeListener.h index f32d83ef..5e3ef408 100644 --- a/src/KDbTableSchemaChangeListener.h +++ b/src/KDbTableSchemaChangeListener.h @@ -1,116 +1,180 @@ /* This file is part of the KDE project - Copyright (C) 2003-2016 Jarosław Staniek + Copyright (C) 2003-2017 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_KDBTABLESCHEMACHANGELISTENER_H #include #include class KDbConnection; +class KDbQuerySchema; class KDbTableSchema; +class KDbTableSchemaChangeListenerPrivate; //! @short An interface allowing to listen for table schema changes /** * The KDbTableSchemaChangeListener class can be used to listen for changes in table schema. * For example query designer window that uses given table schema can be informed about * planned changes and it can be decided about closing the window prior to changes in the schema. */ class KDB_EXPORT KDbTableSchemaChangeListener { public: KDbTableSchemaChangeListener(); virtual ~KDbTableSchemaChangeListener(); /** * Closes listening object so it will be deleted and thus no longer use a conflicting * table schema. For example if the listening object is a query designer in Kexi * application, the designer window will be closed. * This method can be used to avoid conflicts altering table schema or deleting it. */ virtual tristate closeListener() = 0; /** * @return translated string that clearly identifies object that listens for changes * in a given table schema. * * For example it can be a query that uses the table, see KexiQueryPart in Kexi application * and the translated name can be "Query \"abc\"". This friendly identifier can be then * displayed by the application to inform users about objects depending on the table * so users can decide whether to approve schema changes or close the depending windows * to avoid conflicts. * * By default the name string is empty. */ QString name() const; /** * @return translated string that clearly identifies object that listens for changes * in a given table schema. * * @see name() */ void setName(const QString &name); - //! @todo will be more generic - /** Registers @a listener for receiving (listening) information about changes - in table schema @a table. Changes could be related to altering and removing. */ + /** Registers @a listener for receiving (listening) information about changes in table schema + * @a table and all tables related to lookup fields. Changes can be related to altering and + * removing. + */ static void registerForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener, const KDbTableSchema* table); + /** + * Registers @a listener for receiving (listening) information about changes in query schema + * @a query and all tables that the query uses. + * + * All tables related to lookup fields of these tables are also checked. + * Changes can be related to table altering and removing. + */ + static void registerForChanges(KDbConnection *conn, + KDbTableSchemaChangeListener* listener, + const KDbQuerySchema* query); + /** * Unregisters @a listener for receiving (listening) information about changes * in table schema @a table. */ static void unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener, const KDbTableSchema* table); + /** + * Unregisters all listeners for receiving (listening) information about changes + * in table schema @a table. + */ + static void unregisterForChanges(KDbConnection *conn, + const KDbTableSchema* table); + /** * Unregisters @a listener for receiving (listening) information about changes - * in any table schema. + * in any table or query schema. */ static void unregisterForChanges(KDbConnection *conn, KDbTableSchemaChangeListener* listener); + /** + * Unregisters @a listener for receiving (listening) information about changes + * in query schema @a query. + */ + static void unregisterForChanges(KDbConnection *conn, + KDbTableSchemaChangeListener* listener, + const KDbQuerySchema* query); + + /** + * Unregisters all listeners for receiving (listening) information about changes + * in query schema @a query. + */ + static void unregisterForChanges(KDbConnection *conn, + const KDbQuerySchema* query); + + /** + * @return list of all table schema listeners registered for receiving (listening) + * information about changes in table schema @a table and other tables or queries depending + * on @a table. + */ + static QList listeners(KDbConnection *conn, + const KDbTableSchema *table); + /** * @return list of all table schema listeners registered for receiving (listening) - * information about changes in table schema @a table. + * information about changes in query @a query and other tables or queries depending on @a query. */ - static QList listeners( - const KDbConnection *conn, const KDbTableSchema* table); + static QList listeners(KDbConnection *conn, + const KDbQuerySchema *query); /** - * Closes all table schema listeners for table schema @a table. - * See KDbTableSchemaChangeListener::closeListener() for explanation - * of the operation of closing listener. + * Closes all table schema listeners for table schema @a table except for the ones from + * the @a except list. + * + * See KDbTableSchemaChangeListener::closeListener() for explanation of the operation + * of closing listener. + * + * @return true if all listenters for the table schema @a table have been successfully closed + * (returned true) or @c false or @c cancelled if at least one listener returned + * @c false or @c cancelled, respectively. + * Regardless of returned value, closeListener() is called on all listeners for @a table. + */ + static tristate closeListeners(KDbConnection *conn, const KDbTableSchema* table, + const QList &except + = QList()); + + /** + * Closes all table schema listeners for query schema @a query except for the ones from + * the @a except list. + * + * See KDbTableSchemaChangeListener::closeListener() for explanation of the operation + * of closing listener. + * * @return true if all listenters for the table schema @a table have been successfully closed * (returned true) or @c false or @c cancelled if at least one listener returned * @c false or @c cancelled, respectively. * Regardless of returned value, closeListener() is called on all listeners for @a table. */ - static tristate closeListeners(KDbConnection *conn, const KDbTableSchema* table); + static tristate closeListeners(KDbConnection *conn, const KDbQuerySchema* query, + const QList &except + = QList()); private: Q_DISABLE_COPY(KDbTableSchemaChangeListener) - class Private; - Private * const d; + KDbTableSchemaChangeListenerPrivate * const d; }; #endif diff --git a/src/config-kdb.h.cmake b/src/config-kdb.h.cmake index b6321bbf..b3be9c0b 100644 --- a/src/config-kdb.h.cmake +++ b/src/config-kdb.h.cmake @@ -1,72 +1,77 @@ #ifndef KDB_CONFIG_H #define KDB_CONFIG_H /* config-kdb.h. Generated by cmake from config-kdb.h.cmake */ /*! @file config-kdb.h Global KDb configuration (build time) */ //! @def KDB_GIT_SHA1_STRING //! @brief Indicates the git sha1 commit which was used for compilation of KDb #cmakedefine KDB_GIT_SHA1_STRING "@KDB_GIT_SHA1_STRING@" //! @def KDB_GIT_BRANCH_STRING //! @brief Indicates the git branch which was used for compilation of KDb #cmakedefine KDB_GIT_BRANCH_STRING "@KDB_GIT_BRANCH_STRING@" //! @def BIN_INSTALL_DIR //! @brief The subdirectory relative to the install prefix for executables. #define BIN_INSTALL_DIR "${BIN_INSTALL_DIR}" //! @def KDB_BASE_NAME //! @brief Base name for the framework, based on major stable version. //! Useful for co-installability. #define KDB_BASE_NAME "@KDB_BASE_NAME@" //! @def KDB_BASE_NAME_LOWER //! @brief Like KDB_BASE_NAME but lowercase. #define KDB_BASE_NAME_LOWER "@KDB_BASE_NAME_LOWER@" //! @def KDB_STABLE_VERSION_MAJOR //! @brief Extra version info, stable major, e.g. 3 for 3.1.0 Alpha (3.0.90) #define KDB_STABLE_VERSION_MAJOR @PROJECT_STABLE_VERSION_MAJOR@ //! @def KDB_STABLE_VERSION_MINOR //! @brief Extra version info, stable minor, e.g. 1 for 3.1.0 Alpha (3.0.90) #define KDB_STABLE_VERSION_MINOR @PROJECT_STABLE_VERSION_MINOR@ //! @def KDB_STABLE_VERSION_PATCH //! @brief Extra version info, stable patch, e.g. 0 for 3.1.0 Alpha (3.0.90) #define KDB_STABLE_VERSION_PATCH @PROJECT_STABLE_VERSION_PATCH@ //! @def KDB_TESTING_EXPORT //! @brief Export symbols for testing #ifdef BUILD_TESTING # define KDB_TESTING_EXPORT KDB_EXPORT #else # define KDB_TESTING_EXPORT #endif //! @def KDB_EXPRESSION_DEBUG //! @brief Defined if debugging for expressions is enabled #cmakedefine KDB_EXPRESSION_DEBUG //! @def KDB_DRIVERMANAGER_DEBUG //! @brief Defined if debugging for the driver manager is enabled #cmakedefine KDB_DRIVERMANAGER_DEBUG //! @def KDB_TRANSACTIONS_DEBUG //! @brief Defined if debugging for database transactions is enabled //! @since 3.1 #cmakedefine KDB_TRANSACTIONS_DEBUG +//! @def KDB_TABLESCHEMACHANGELISTENER_DEBUG +//! @brief Debugging of the KDbTableSchemaChangeListener class +//! @since 3.1 +#cmakedefine KDB_TABLESCHEMACHANGELISTENER_DEBUG + //! @def KDB_DEBUG_GUI //! @brief Defined if a GUI for debugging is enabled #cmakedefine KDB_DEBUG_GUI //! @def KDB_UNFINISHED //! @brief Defined if unfinished features of KDb are enabled #cmakedefine KDB_UNFINISHED #endif