diff --git a/src/KDbConnection.cpp b/src/KDbConnection.cpp index b83ece6e..390a3f64 100644 --- a/src/KDbConnection.cpp +++ b/src/KDbConnection.cpp @@ -1,3425 +1,3425 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbConnection.h" #include "KDbConnection_p.h" #include "KDbCursor.h" #include "kdb_debug.h" #include "KDbDriverBehavior.h" #include "KDbDriverMetaData.h" #include "KDbDriver_p.h" #include "KDbLookupFieldSchema.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbRecordData.h" #include "KDbRecordEditBuffer.h" #include "KDbRelationship.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" #include "KDbTableSchemaChangeListener.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, 0, 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, 0, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_type"), KDbField::Byte, 0, 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) { 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(); } //================================================ 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->beh->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->beh->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->beh->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->beh->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.active()) 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.active() && !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->beh->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->beh->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->beh->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, 0, 0, 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 + ")"; bool KDbConnection::insertRecordInternal(const QString &tableSchemaName, KDbFieldList* fields, const KDbEscapedString &sql, KDbSqlResult** result = 0) { if (!drv_beforeInsert(tableSchemaName,fields )) { return false; } QScopedPointer res(executeSQL(sql)); if (!res || res->lastResult().isError()) { return false; } if (!drv_afterInsert(tableSchemaName, fields)) { return false; } { // Fetching is needed to performs real execution, at least for some backends. // Also we're not expecting record but let's delete if there's any. QScopedPointer record(res->fetchRecord()); } if (!res->lastResult().isError()) { if (result) { *result = res.take(); } return true; } return false; } #define C_INS_REC(args, vals) \ bool KDbConnection::insertRecord(KDbTableSchema* tableSchema args, KDbSqlResult** result) {\ return insertRecordInternal(tableSchema->name(), tableSchema, \ KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) \ + " (" \ + tableSchema->sqlFieldsList(this) \ + ") VALUES (" + vals + ")", \ result); \ } #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) \ bool KDbConnection::insertRecord(KDbFieldList* fields args, KDbSqlResult** result) \ { \ 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 + ')', \ result); \ } C_INS_REC_ALL #undef C_A #undef V_A #undef V_ALAST #undef C_INS_REC #undef C_INS_REC_ALL bool KDbConnection::insertRecord(KDbTableSchema* tableSchema, const QList& values, KDbSqlResult** result) { // Each SQL identifier needs to be escaped in the generated query. const KDbField::List *flist = tableSchema->fields(); if (flist->isEmpty()) { return false; } 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); return insertRecordInternal(tableSchema->name(), tableSchema, sql, result); } bool KDbConnection::insertRecord(KDbFieldList* fields, const QList& values, KDbSqlResult** result) { // Each SQL identifier needs to be escaped in the generated query. const KDbField::List *flist = fields->fields(); if (flist->isEmpty()) { return false; } 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); return insertRecordInternal(tableName, fields, sql, result); } 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; } KDbSqlResult* KDbConnection::executeSQL(const KDbEscapedString& sql) { m_result.setSql(sql); return drv_executeSQL(sql); } bool KDbConnection::executeVoidSQL(const KDbEscapedString& sql) { m_result.setSql(sql); if (!checkSql(sql, &m_result)) { return false; } if (!drv_executeVoidSQL(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.")); qWarning() << 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 0; } //! Creates a KDbField list for kexi__fields, for sanity. Used by createTable() static KDbFieldList* createFieldListForKexi__Fields(KDbTableSchema *kexi__fieldsSchema) { if (!kexi__fieldsSchema) return 0; 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 executeVoidSQL(sql); } #define createTable_ERR \ { kdbDebug() << "ERROR!"; \ m_result.prependMessage(KDbConnection::tr("Creating table failed.")); \ rollbackAutoCommitTransaction(tg.transaction()); \ return false; } bool KDbConnection::createTable(KDbTableSchema* tableSchema, bool replaceExisting) { 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 = 0; if (replaceExisting) { //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 (!dropTable(existingTable, false /*alsoRemoveSchema*/)) return false; } } else { if (this->tableSchema(tableSchema->name()) != 0) { 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 0; } 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, false /* !replaceExisting */)) { delete copiedTable; return 0; } if (!drv_copyTableData(tableSchema, *copiedTable)) { dropTable(copiedTable); delete copiedTable; return 0; } 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 0; } 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 executeVoidSQL(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 executeVoidSQL(KDbEscapedString("DROP TABLE %1").arg(escapeIdentifier(tableName))); } tristate KDbConnection::dropTable(KDbTableSchema* tableSchema) { return dropTable(tableSchema, true); } tristate KDbConnection::dropTable(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, true/*replace*/); } return ok; } bool KDbConnection::alterTableName(KDbTableSchema* tableSchema, const QString& newName, bool replace) { 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 != 0; const int origID = destTableExists ? tableToReplace->id() : -1; //will be reused in the new table if (!replace && 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 (!executeVoidSQL( 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 (!executeVoidSQL(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 (!executeVoidSQL(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 (!executeVoidSQL(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); KDbEscapedString sql; if (!builder.generateCreateTableStatement(&sql,tableSchema)) { return false; } //kdbDebug() << "******** " << sql; return executeVoidSQL(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->beh->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->beh->features & KDbDriver::SingleTransactions) { if (d->defaultTransactionStartedInside) //only commit internally started transaction if (!commitTransaction(d->default_trans, true)) { 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->beh->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->beh->features & KDbDriver::IgnoreTransactions) return true; if (trans.isNull() || !d->driver->transactionsSupported()) return true; if (d->driver->beh->features & KDbDriver::SingleTransactions) { if (!d->defaultTransactionStartedInside) //only commit internally started transaction return true; //give up } return commitTransaction(trans, true); } 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->beh->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->beh->features & KDbDriver::SingleTransactions) { if (d->default_trans.active()) { 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->beh->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, bool ignore_inactive) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->beh->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.active()) { //try default tr. if (!d->default_trans.active()) { if (ignore_inactive) 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->beh->features & KDbDriver::IgnoreTransactions)) ret = drv_commitTransaction(t.m_data); if (t.m_data) t.m_data->m_active = 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, bool ignore_inactive) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->beh->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.active()) { //try default tr. if (!d->default_trans.active()) { if (ignore_inactive) 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->beh->features & KDbDriver::IgnoreTransactions)) ret = drv_rollbackTransaction(t.m_data); if (t.m_data) t.m_data->m_active = 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->beh->features & KDbDriver::IgnoreTransactions) && (!trans.active() || !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->beh->features & KDbDriver::IgnoreTransactions) return true; if (!drv_setAutoCommit(on)) return false; d->autoCommit = on; return true; } KDbTransactionData* KDbConnection::drv_beginTransaction() { if (!executeVoidSQL(KDbEscapedString("BEGIN"))) return 0; return new KDbTransactionData(this); } bool KDbConnection::drv_commitTransaction(KDbTransactionData *) { return executeVoidSQL(KDbEscapedString("COMMIT")); } bool KDbConnection::drv_rollbackTransaction(KDbTransactionData *) { return executeVoidSQL(KDbEscapedString("ROLLBACK")); } bool KDbConnection::drv_setAutoCommit(bool /*on*/) { return true; } -KDbCursor* KDbConnection::executeQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* KDbConnection::executeQuery(const KDbEscapedString& sql, KDbCursor::Options options) { if (sql.isEmpty()) return 0; - KDbCursor *c = prepareQuery(sql, cursor_options); + KDbCursor *c = prepareQuery(sql, options); if (!c) return 0; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return 0; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, const QList& params, - int cursor_options) + KDbCursor::Options options) { - KDbCursor *c = prepareQuery(query, params, cursor_options); + KDbCursor *c = prepareQuery(query, params, options); if (!c) return 0; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return 0; } return c; } -KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, KDbCursor::Options options) { - return executeQuery(query, QList(), cursor_options); + return executeQuery(query, QList(), options); } -KDbCursor* KDbConnection::executeQuery(KDbTableSchema* table, int cursor_options) +KDbCursor* KDbConnection::executeQuery(KDbTableSchema* table, KDbCursor::Options options) { - return executeQuery(table->query(), cursor_options); + return executeQuery(table->query(), options); } -KDbCursor* KDbConnection::prepareQuery(KDbTableSchema* table, int cursor_options) +KDbCursor* KDbConnection::prepareQuery(KDbTableSchema* table, KDbCursor::Options options) { - return prepareQuery(table->query(), cursor_options); + return prepareQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbQuerySchema* query, const QList& params, - int cursor_options) + KDbCursor::Options options) { - KDbCursor* cursor = prepareQuery(query, cursor_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 id, KDbObject* object) { KDbRecordData data; 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; } 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; } KDbSqlResult* result; if (!insertRecord(fl.data(), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description()), &result)) { return false; } QScopedPointer resultGuard(result); //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 executeVoidSQL( 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 0; } if (params) { return executeQuery(query, *params); } return executeQuery(query); } tristate KDbConnection::querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, bool addLimitTo1) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, 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, bool addLimitTo1) { return querySingleRecordInternal(data, &sql, 0, 0, addLimitTo1); } tristate KDbConnection::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1) { return querySingleRecordInternal(data, 0, query, 0, addLimitTo1); } tristate KDbConnection::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, bool addLimitTo1) { return querySingleRecordInternal(data, 0, query, ¶ms, addLimitTo1); } 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, bool addLimitTo1) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, 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; } *value = cursor->value(column).toString(); return deleteCursor(cursor); } tristate KDbConnection::querySingleString(const KDbEscapedString& sql, QString* value, int column, bool addLimitTo1) { return querySingleStringInternal(&sql, value, 0, 0, column, addLimitTo1); } tristate KDbConnection::querySingleString(KDbQuerySchema* query, QString* value, int column, bool addLimitTo1) { return querySingleStringInternal(0, value, query, 0, column, addLimitTo1); } tristate KDbConnection::querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column, bool addLimitTo1) { return querySingleStringInternal(0, value, query, ¶ms, column, addLimitTo1); } tristate KDbConnection::querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1) { QString str; const tristate result = querySingleStringInternal(sql, &str, query, params, column, addLimitTo1); if (result != true) return result; bool ok; const int _number = str.toInt(&ok); if (!ok) return false; *number = _number; return true; } tristate KDbConnection::querySingleNumber(const KDbEscapedString& sql, int* number, int column, bool addLimitTo1) { return querySingleNumberInternal(&sql, number, 0, 0, column, addLimitTo1); } tristate KDbConnection::querySingleNumber(KDbQuerySchema* query, int* number, int column, bool addLimitTo1) { return querySingleNumberInternal(0, number, query, 0, column, addLimitTo1); } tristate KDbConnection::querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column, bool addLimitTo1) { return querySingleNumberInternal(0, number, query, ¶ms, column, addLimitTo1); } 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; } list->clear(); while (!cursor->eof()) { const QString str(cursor->value(column).toString()); if (!filterFunction || filterFunction(str)) { list->append(str); } if (!cursor->moveNext() && cursor->result().isError()) { m_result = cursor->result(); deleteCursor(cursor); return false; } } return deleteCursor(cursor); } bool KDbConnection::queryStringList(const KDbEscapedString& sql, QStringList* list, int column) { return queryStringListInternal(&sql, list, 0, 0, column, 0); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, int column) { return queryStringListInternal(0, list, query, 0, column, 0); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column) { return queryStringListInternal(0, list, query, ¶ms, column, 0); } tristate KDbConnection::resultExists(const KDbEscapedString& sql, bool addLimitTo1) { //optimization if (d->driver->beh->SELECT_1_SUBQUERY_SUPPORTED) { //this is at least for sqlite if (addLimitTo1 && sql.left(6).toUpper() == "SELECT") { m_result.setSql( d->driver->addLimitTo1("SELECT 1 FROM (" + sql + ')', addLimitTo1)); } else { m_result.setSql(sql); } } else { if (addLimitTo1 && sql.startsWith("SELECT")) { m_result.setSql(d->driver->addLimitTo1(sql, addLimitTo1)); } 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); 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 0; KDbField::Type f_type = (KDbField::Type)f_int_type; int f_len = qMax(0, data.at(3).toInt(&ok)); // defined limit if (!ok) { return 0; } if (f_len < 0) { f_len = 0; } //! @todo load maxLengthStrategy info to see if the maxLength is the default int f_prec = data.at(4).toInt(&ok); if (!ok) return 0; KDbField::Constraints f_constr = (KDbField::Constraints)data.at(5).toInt(&ok); if (!ok) return 0; KDbField::Options f_opts = (KDbField::Options)data.at(6).toInt(&ok); if (!ok) return 0; 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::setupTableSchema(const KDbRecordData &data) { KDbTableSchema *t = new KDbTableSchema(this); if (!setupObjectData(data, t)) { delete t; return 0; } KDbCursor *cursor; if (!(cursor = 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(d->driver->valueToSQL(KDbField::Integer, t->id()))))) { delete t; return 0; } if (!cursor->moveFirst()) { if (!cursor->result().isError() && cursor->eof()) { m_result = KDbResult(tr("Table has no fields defined.")); } deleteCursor(cursor); delete t; return 0; } // 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 = setupField(fieldData); if (!f || !t->addField(f)) { ok = false; break; } cursor->moveNext(); } if (!ok) {//error: deleteCursor(cursor); delete t; return 0; } if (!deleteCursor(cursor)) { delete t; return 0; } if (!loadExtendedTableSchemaData(t)) { delete t; return 0; } //store locally: d->insertTable(t); return t; } KDbTableSchema* KDbConnection::tableSchema(const QString& tableName) { KDbTableSchema *t = d->table(tableName); if (t) return t; //not found: retrieve schema KDbRecordData data; if (true != querySingleRecord( KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc FROM kexi__objects " "WHERE o_name=%1 AND o_type=%2") .arg(escapeString(tableName)) .arg(d->driver->valueToSQL(KDbField::Integer, KDb::TableObjectType)), &data)) { return 0; } return setupTableSchema(data); } KDbTableSchema* KDbConnection::tableSchema(int tableId) { KDbTableSchema *t = d->table(tableId); if (t) return t; //not found: retrieve schema KDbRecordData data; 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, tableId)), &data)) { return 0; } return setupTableSchema(data); } 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 executeVoidSQL(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 executeVoidSQL( 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 executeVoidSQL(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::setupQuerySchema(const KDbRecordData &data) { bool ok = true; const int objID = data[0].toInt(&ok); if (!ok) return 0; QString sql; if (!loadDataBlock(objID, &sql, QLatin1String("sql"))) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not find definition for query \"%1\". Deleting this query is recommended.").arg(data[2].toString())); return 0; } KDbQuerySchema *query = 0; if (d->parser()->parse(KDbEscapedString(sql))) { query = d->parser()->query(); } //error? if (!query) { 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(data[2].toString(), sql)); return 0; } if (!setupObjectData(data, query)) { delete query; return 0; } d->insertQuery(query); return query; } KDbQuerySchema* KDbConnection::querySchema(const QString& queryName) { QString m_queryName = queryName.toLower(); KDbQuerySchema *q = d->query(m_queryName); if (q) return q; //not found: retrieve schema KDbRecordData data; if (true != querySingleRecord( KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc FROM kexi__objects " "WHERE o_name=%1 AND o_type=%2") .arg(escapeString(m_queryName)) .arg(d->driver->valueToSQL(KDbField::Integer, int(KDb::QueryObjectType))), &data)) { return 0; } return setupQuerySchema(data); } KDbQuerySchema* KDbConnection::querySchema(int queryId) { KDbQuerySchema *q = d->query(queryId); if (q) return q; //not found: retrieve schema clearResult(); KDbRecordData data; 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, queryId)), &data)) { return 0; } return setupQuerySchema(data); } 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->beh->ALWAYS_AVAILABLE_DATABASE_NAME; } void KDbConnection::setAvailableDatabaseName(const QString& dbName) { d->availableDatabaseName = dbName; } //! @internal used in updateRecord(), insertRecord(), inline static void updateRecordDataWithNewValues(KDbQuerySchema* query, KDbRecordData* data, const KDbRecordEditBuffer::DbHash& b, QHash* columnsOrderExpanded) { *columnsOrderExpanded = query->columnsOrder(KDbQuerySchema::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() : 0; 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()); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount()) { //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->beh->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 = executeVoidSQL(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(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() : 0; 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(KDbQuerySchema::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()); // kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount()) { //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 KDbSqlResult* result; if (!insertRecordInternal(mt->name(), &affectedFields, sql, &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: QScopedPointer resultGuard(result); QHash columnsOrderExpanded; updateRecordDataWithNewValues(query, data, b, &columnsOrderExpanded); //fetch autoincremented values KDbQueryColumnInfo::List *aif_list = query->autoIncrementFields(); 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->beh->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE) { kdbWarning() << "d->driver->beh->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() : 0; //! @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()); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); if (pkey->fieldCount() != query->pkeyFieldCount()) { //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->beh->ROW_ID_FIELD_NAME)) + '=' + d->driver->valueToSQL(KDbField::BigInteger, (*data)[data->size() - 1]); } sql += sqlwhere; //kdbDebug() << " -- SQL == " << sql; if (!executeVoidSQL(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 (!executeVoidSQL(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } 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 795f2797..0ae5d956 100644 --- a/src/KDbConnection.h +++ b/src/KDbConnection.h @@ -1,1284 +1,1286 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_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 KDbConnectionPrivate; class KDbConnectionData; class KDbConnectionOptions; class KDbConnectionProxy; -class KDbCursor; class KDbDriver; class KDbProperties; class KDbRecordData; class KDbRecordEditBuffer; class KDbServerVersionInfo; class KDbSqlResult; class KDbTableSchemaChangeListener; 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. */ virtual ~KDbConnection(); /*! @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 = 0, KDbMessageHandler* msgHandler = 0); /*! @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 = 0); /*! @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 = 0); /*! @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 = 0); /*! @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 = 0); /*! @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 = 0); /*! @brief Creates new KDbTransaction handle and starts a new transaction. @return KDbTransaction object if transaction has been started successfully, otherwise null transaction. For drivers that allow single transaction per connection (KDbDriver::features() && SingleTransactions) this method can be called one time, and then this single transaction will be default ( setDefaultTransaction() will be called). For drivers that allow multiple transactions per connection, no default transaction is set automatically in beginTransaction() method, you could do this by hand. @see setDefaultTransaction(), defaultTransaction(). */ KDbTransaction beginTransaction(); /*! @todo for nested transactions: Tansaction* beginTransaction(transaction *parent_transaction); */ /*! Commits transaction @a trans. If there is not @a trans argument passed, and there is default transaction (obtained from defaultTransaction()) defined, this one will be committed. If default is not present, false is returned (when ignore_inactive is false, the default), or true is returned (when ignore_inactive is true). On successful commit, @a trans object will be destroyed. If this was default transaction, there is no default transaction for now. */ bool commitTransaction(KDbTransaction trans = KDbTransaction(), bool ignore_inactive = false); /*! Rollbacks transaction @a trans. If there is not @a trans argument passed, and there is default transaction (obtained from defaultTransaction()) defined, this one will be rolled back. If default is not present, false is returned (when ignore_inactive is false, the default), or true is returned (when ignore_inactive is true). or any error occurred, false is returned. On successful rollback, @a trans object will be destroyed. If this was default transaction, there is no default transaction for now. */ bool rollbackTransaction(KDbTransaction trans = KDbTransaction(), bool ignore_inactive = false); /*! @return handle for default transaction for this connection or null transaction if there is no such a transaction defined. 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. Returned null transaction doesn't mean that there is no transactions started at all. Default transaction can be defined automatically for some drivers -- see beginTransaction(). @see KDbDriver::transactionsSupported() */ KDbTransaction defaultTransaction() const; /*! Sets default transaction that will be used as context for operations on data in opened database for this connection. */ void setDefaultTransaction(const KDbTransaction& trans); /*! @return set of handles of currently active transactions. Note that in multithreading environment some of these transactions can be already inactive after calling this method. Use KDbTransaction::active() to check that. Inactive transaction handle is useless and can be safely dropped. */ 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 functional statement (statement that changes 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 sql functional statement execution. 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 cursor_options (one of more selected from KDbCursor::Options). + 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 cursor_options to its constructor). + (passing @a sql and @a options to its constructor). */ - virtual KDbCursor* prepareQuery(const KDbEscapedString& sql, int cursor_options = 0) Q_REQUIRED_RESULT = 0; + virtual KDbCursor* prepareQuery(const KDbEscapedString& sql, + KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT = 0; - /*! @overload prepareQuery(const KDbEscapedString&, int) + /*! @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 cursor_options to it's constructor). + (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, - int cursor_options = 0) Q_REQUIRED_RESULT; + KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; - /*! @overload prepareQuery(KDbQuerySchema* query, const QList& params, - int cursor_options = 0 ) + /*! @overload Prepares query described by @a query schema without parameters. */ - virtual KDbCursor* prepareQuery(KDbQuerySchema* query, int cursor_options = 0) Q_REQUIRED_RESULT = 0; + virtual KDbCursor* prepareQuery(KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT = 0; - /*! @overload prepareQuery(const KDbEscapedString&, int) - Statement is build from data provided by @a table schema, - it is like "select * from table_name".*/ - KDbCursor* prepareQuery(KDbTableSchema* table, int cursor_options = 0) Q_REQUIRED_RESULT; + /*! @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 cursor_options - (one of more selected from KDbCursor::Options). + 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, int cursor_options = 0) Q_REQUIRED_RESULT; + 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, - int cursor_options = 0) Q_REQUIRED_RESULT; + KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; - /*! @overload executeQuery(KDbQuerySchema* query, const QList& params, - int cursor_options = 0 ) */ - KDbCursor* executeQuery(KDbQuerySchema* query, int cursor_options = 0) Q_REQUIRED_RESULT; + /*! @overload */ + KDbCursor* executeQuery(KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; - /*! @overload executeQuery(const KDbEscapedString&, int) + /*! @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, int cursor_options = 0) Q_REQUIRED_RESULT; + 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); /*! 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 addLimitTo1 is true (the default), adds a LIMIT clause to the query, so @a sql should not include one 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 querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, bool addLimitTo1 = true); /*! @overload tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, bool addLimitTo1) Uses a KDbQuerySchema object. */ tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1 = true); /*! @overload tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1) Accepts @a params as parameters that will be inserted into places marked with [] before query execution. */ tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, bool addLimitTo1 = true); /*! 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 addLimitTo1 is true (the default), adds a LIMIT clause to the query, so @a sql should not include one 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. @see queryStringList() */ tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, bool addLimitTo1 = true); /*! @overload tristate querySingleString(const KDbEscapedString& sql, QString* value, int column, bool addLimitTo1) Uses a KDbQuerySchema object. */ tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, bool addLimitTo1 = true); /*! @overload tristate querySingleString(QuerySchema* query, QString* value, int column, bool addLimitTo1) 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, bool addLimitTo1 = true); /*! 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(). Note: "LIMIT 1" is appended to @a sql statement if @a addLimitTo1 is true (the default). @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, bool addLimitTo1 = true); /*! @overload tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column, bool addLimitTo1) Uses a KDbQuerySchema object. */ tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, bool addLimitTo1 = true); /*! @overload tristate querySingleNumber(KDbQuerySchema* query, int* number, int column, bool addLimitTo1) 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, bool addLimitTo1 = true); /*! 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 tristate queryStringList(const KDbEscapedString& sql, QStringList* list, int column) Uses a QuerySchema object. */ bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); /*! @overload tristate queryStringList(KDbQuerySchema* query, QStringList* list, int column) 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. Does not fetch any records. On error returns @c cancelled. Note: real executed query is: "SELECT 1 FROM (@a sql) LIMIT 1" if @a addLimitTo1 is true (the default). */ tristate resultExists(const KDbEscapedString& sql, bool addLimitTo1 = true); /*! @return true if there is at least one record in @a table. */ tristate isEmpty(KDbTableSchema* table); virtual KDbEscapedString recentSQLString() const; //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args) bool insertRecord(KDbTableSchema* tableSchema args, KDbSqlResult** result = 0) #define H_INS_REC_ALL \ H_INS_REC(A); \ H_INS_REC(A A); \ H_INS_REC(A A A); \ H_INS_REC(A A A A); \ H_INS_REC(A A A A A); \ H_INS_REC(A A A A A A); \ H_INS_REC(A A A A A A A); \ H_INS_REC(A A A A A A A A) H_INS_REC_ALL; #undef H_INS_REC #define H_INS_REC(args) bool insertRecord(KDbFieldList* fields args, KDbSqlResult** result = 0) H_INS_REC_ALL; #undef H_INS_REC_ALL #undef H_INS_REC #undef A bool insertRecord(KDbTableSchema* tableSchema, const QList& values, KDbSqlResult** result = 0); bool insertRecord(KDbFieldList* fields, const QList& values, KDbSqlResult** result = 0); /*! Creates table defined by @a tableSchema. Schema information is also added into kexi system tables, for later reuse. @return true on success - @a tableSchema object is then inserted to KDbConnection structures - it is owned by KDbConnection object now, so you shouldn't destroy the tableSchema object by hand (or declare it as local-scope variable). If @a replaceExisting is false (the default) and table with the same name (as tableSchema->name()) exists, false is returned. If @a replaceExisting is true, a table schema with the same name (if exists) is overwritten, then a new table schema gets the same identifier as existing table schema's identifier. Table and column definitions are added to to kexi__* "system schema" tables. Checks that a database is in use, and that the schema defines at least one column. Note that on error: - @a tableSchema is not inserted into KDbConnection's structures, so you are still owner of this object - existing table schema object is not destroyed (i.e. it is still available e.g. using KDbConnection::tableSchema(const QString&), even if the table was physically dropped. */ bool createTable(KDbTableSchema* tableSchema, bool replaceExisting = false); /*! 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); /*! It is a convenience function, does exactly the same as bool dropTable( KDbTableSchema* tableSchema ) */ 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); /*! Alters name of table described by @a tableSchema to @a newName. If @a replace is true, destination table is completely dropped and replaced by @a tableSchema, if present. In this case, identifier of @a tableSchema becomes equal to the dropped table's id, what can be useful if @a tableSchema was created with a temporary name and ID (used in KDbAlterTableHandler). If @a replace is false (the default) and destination table is present -- false is returned and ERR_OBJECT_EXISTS error is set. The schema of @a tableSchema is updated on success. @return true on success. */ bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, bool replace = false); /*! 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, null 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); /*! Executes a new native (raw, backend-specific) SQL query for statement @a sql. * Only use this method in cases if a non-portable raw query is required. * Access to results can be obtained using the returned KDbSqlResult object. * @c nullptr is returned on failure. Use result() to obtain detailed status information. * The KDbConnection object is owner of the returned object. Before closing, the * connection object deletes all its owned KDbSqlResult objects. It is also possible * and recommended that caller deletes the KDbSqlResult object as soon as the result * is not needed. * If the query is not supposed to return records (e.g. is a functional query) * or the caller is not interested in the records, the returned object can be just deleted. * In this case executeVoidSQL() can be a better choice. * Using QScopedPointer construct may simplify memory management of the * returned object. */ KDbSqlResult* executeSQL(const KDbEscapedString& sql) Q_REQUIRED_RESULT; /*! Executes a new native (raw, backend-specific) SQL query for statement @a sql. * This method is equivalent of executeSQL() useful for cases when the query is not * supposed to return records (e.g. is a functional query) or if the caller is not * interested in the records. */ bool executeVoidSQL(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); /*! Added for convenience. @see setupObjectData(const KDbRecordData*, KDbObject*). @return true on success, false on failure and cancelled when such object couldn't be found. */ tristate loadObjectData(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); //! 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 drv_executeSQL() Note for driver developers: reimplement this only if you want do to this 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 SQLite2, 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 dropTable(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; /*! Executes query for a raw SQL statement @a sql with possibility of returning records. It is useful mostly for functional (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 @c nullptr if there is no proper result. Ownership of the returned object is passed to the caller. @see executeSQL */ virtual KDbSqlResult* drv_executeSQL(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. Only use this method if you really need. @see executeVoidSQL */ virtual bool drv_executeVoidSQL(const KDbEscapedString& sql) = 0; /*! Uses result of execution of raw SQL query using drv_executeSQL(). 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 @c nullptr if there is no proper result. Ownership of the returned object is passed to the caller. */ //virtual KDbSqlResult* drv_getSqlResult() Q_REQUIRED_RESULT = 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 = 0, KDbMessageHandler* msgHandler = 0) = 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. You should return NULL if any error occurred. Do not check anything in connection (isConnected(), etc.) - all is already done. */ 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 null 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: Rollbacks 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(); /*! @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. */ KDbTableSchema* setupTableSchema(const KDbRecordData& data) 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. */ KDbQuerySchema* setupQuerySchema(const KDbRecordData& data) Q_REQUIRED_RESULT; /*! 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 @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. */ bool insertRecordInternal(const QString &tableSchemaName, KDbFieldList* fields, const KDbEscapedString &sql, KDbSqlResult** result); /*! @internal used by querySingleRecord() methods. Note: "LIMIT 1" is appended to @a sql statement if @a addLimitTo1 is true (the default). */ tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, bool addLimitTo1 = true); /*! @internal used by querySingleString() methods. Note: "LIMIT 1" is appended to @a sql statement if @a addLimitTo1 is true (the default). */ tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1); /*! @internal used by queryNumberString() methods. Note: "LIMIT 1" is appended to @a sql statement if @a addLimitTo1 is true (the default). */ tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1); /*! @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 KDbTableSchemaChangeListener; friend class KDbTableSchema; //!< for removeMe() }; #endif diff --git a/src/KDbConnectionProxy.cpp b/src/KDbConnectionProxy.cpp index 911cc00b..af0da3a8 100644 --- a/src/KDbConnectionProxy.cpp +++ b/src/KDbConnectionProxy.cpp @@ -1,833 +1,833 @@ /* This file is part of the KDE project Copyright (C) 2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbConnectionProxy.h" #include "KDbConnectionData.h" #include "KDbProperties.h" #include "KDbVersionInfo.h" class Q_DECL_HIDDEN KDbConnectionProxy::Private { public: Private() : connectionIsOwned(true) { } ~Private() { if (connectionIsOwned) { connection->disconnect(); delete connection; } } bool connectionIsOwned; KDbConnection *connection; private: Q_DISABLE_COPY(Private) }; KDbConnectionProxy::KDbConnectionProxy(KDbConnection *parentConnection) : KDbConnection(parentConnection->driver(), parentConnection->data(), *parentConnection->options()) , d(new Private) { Q_ASSERT(parentConnection); d->connection = parentConnection; } KDbConnectionProxy::~KDbConnectionProxy() { delete d; } KDbConnection* KDbConnectionProxy::parentConnection() { return d->connection; } const KDbConnection* KDbConnectionProxy::parentConnection() const { return d->connection; } void KDbConnectionProxy::setParentConnectionIsOwned(bool set) { d->connectionIsOwned = set; } KDbConnectionData KDbConnectionProxy::data() const { return d->connection->data(); } KDbDriver* KDbConnectionProxy::driver() const { return d->connection->driver(); } bool KDbConnectionProxy::connect() { return d->connection->connect(); } bool KDbConnectionProxy::isConnected() const { return d->connection->isConnected(); } bool KDbConnectionProxy::isDatabaseUsed() const { return d->connection->isDatabaseUsed(); } KDbConnectionOptions* KDbConnectionProxy::options() { return d->connection->options(); } void KDbConnectionProxy::clearResult() { d->connection->clearResult(); } KDbResult KDbConnectionProxy::result() const { return d->connection->result(); } KDbResultable KDbConnectionProxy::resultable() const { return *d->connection; } bool KDbConnectionProxy::disconnect() { return d->connection->disconnect(); } QStringList KDbConnectionProxy::databaseNames(bool also_system_db) { return d->connection->databaseNames(also_system_db); } bool KDbConnectionProxy::databaseExists(const QString &dbName, bool ignoreErrors) { return d->connection->databaseExists(dbName, ignoreErrors); } bool KDbConnectionProxy::createDatabase(const QString &dbName) { return d->connection->createDatabase(dbName); } bool KDbConnectionProxy::useDatabase(const QString &dbName, bool kexiCompatible, bool *cancelled, KDbMessageHandler* msgHandler) { return d->connection->useDatabase(dbName, kexiCompatible, cancelled, msgHandler); } bool KDbConnectionProxy::closeDatabase() { return d->connection->closeDatabase(); } QString KDbConnectionProxy::currentDatabase() const { return d->connection->currentDatabase(); } bool KDbConnectionProxy::dropDatabase(const QString &dbName) { return d->connection->dropDatabase(dbName); } QStringList KDbConnectionProxy::objectNames(int objectType, bool* ok) { return d->connection->objectNames(objectType, ok); } QStringList KDbConnectionProxy::tableNames(bool alsoSystemTables, bool* ok) { return d->connection->tableNames(alsoSystemTables, ok); } tristate KDbConnectionProxy::containsTable(const QString &tableName) { return d->connection->containsTable(tableName); } KDbServerVersionInfo KDbConnectionProxy::serverVersion() const { return d->connection->serverVersion(); } KDbVersionInfo KDbConnectionProxy::databaseVersion() const { return d->connection->databaseVersion(); } KDbProperties KDbConnectionProxy::databaseProperties() const { return d->connection->databaseProperties(); } QList KDbConnectionProxy::tableIds(bool* ok) { return d->connection->tableIds(ok); } QList KDbConnectionProxy::queryIds(bool* ok) { return d->connection->queryIds(ok); } QList KDbConnectionProxy::objectIds(int objectType, bool* ok) { return d->connection->objectIds(objectType, ok); } KDbTransaction KDbConnectionProxy::beginTransaction() { return d->connection->beginTransaction(); } bool KDbConnectionProxy::commitTransaction(KDbTransaction trans, bool ignore_inactive) { return d->connection->commitTransaction(trans, ignore_inactive); } bool KDbConnectionProxy::rollbackTransaction(KDbTransaction trans, bool ignore_inactive) { return d->connection->rollbackTransaction(trans, ignore_inactive); } KDbTransaction KDbConnectionProxy::defaultTransaction() const { return d->connection->defaultTransaction(); } void KDbConnectionProxy::setDefaultTransaction(const KDbTransaction& trans) { d->connection->setDefaultTransaction(trans); } QList KDbConnectionProxy::transactions() { return d->connection->transactions(); } bool KDbConnectionProxy::autoCommit() const { return d->connection->autoCommit(); } bool KDbConnectionProxy::setAutoCommit(bool on) { return d->connection->setAutoCommit(on); } KDbEscapedString KDbConnectionProxy::escapeString(const QString& str) const { return d->connection->escapeString(str); } -KDbCursor* KDbConnectionProxy::prepareQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* KDbConnectionProxy::prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options) { - return d->connection->prepareQuery(sql, cursor_options); + return d->connection->prepareQuery(sql, options); } -KDbCursor* KDbConnectionProxy::prepareQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* KDbConnectionProxy::prepareQuery(KDbQuerySchema* query, KDbCursor::Options options) { - return d->connection->prepareQuery(query, cursor_options); + return d->connection->prepareQuery(query, options); } -KDbCursor* KDbConnectionProxy::prepareQuery(KDbTableSchema* table, int cursor_options) +KDbCursor* KDbConnectionProxy::prepareQuery(KDbTableSchema* table, KDbCursor::Options options) { - return d->connection->prepareQuery(table, cursor_options); + return d->connection->prepareQuery(table, options); } -KDbCursor* KDbConnectionProxy::executeQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* KDbConnectionProxy::executeQuery(const KDbEscapedString& sql, KDbCursor::Options options) { - return d->connection->executeQuery(sql, cursor_options); + return d->connection->executeQuery(sql, options); } KDbCursor* KDbConnectionProxy::executeQuery(KDbQuerySchema* query, const QList& params, - int cursor_options) + KDbCursor::Options options) { - return d->connection->executeQuery(query, params, cursor_options); + return d->connection->executeQuery(query, params, options); } -KDbCursor* KDbConnectionProxy::executeQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* KDbConnectionProxy::executeQuery(KDbQuerySchema* query, KDbCursor::Options options) { - return d->connection->executeQuery(query, cursor_options); + return d->connection->executeQuery(query, options); } -KDbCursor* KDbConnectionProxy::executeQuery(KDbTableSchema* table, int cursor_options) +KDbCursor* KDbConnectionProxy::executeQuery(KDbTableSchema* table, KDbCursor::Options options) { - return d->connection->executeQuery(table, cursor_options); + return d->connection->executeQuery(table, options); } bool KDbConnectionProxy::deleteCursor(KDbCursor *cursor) { return d->connection->deleteCursor(cursor); } KDbTableSchema* KDbConnectionProxy::tableSchema(int tableId) { return d->connection->tableSchema(tableId); } KDbTableSchema* KDbConnectionProxy::tableSchema(const QString& tableName) { return d->connection->tableSchema(tableName); } KDbQuerySchema* KDbConnectionProxy::querySchema(int queryId) { return d->connection->querySchema(queryId); } KDbQuerySchema* KDbConnectionProxy::querySchema(const QString& queryName) { return d->connection->querySchema(queryName); } bool KDbConnectionProxy::setQuerySchemaObsolete(const QString& queryName) { return d->connection->setQuerySchemaObsolete(queryName); } tristate KDbConnectionProxy::querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, bool addLimitTo1) { return d->connection->querySingleRecord(sql, data, addLimitTo1); } tristate KDbConnectionProxy::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1) { return d->connection->querySingleRecord(query, data, addLimitTo1); } tristate KDbConnectionProxy::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, bool addLimitTo1) { return d->connection->querySingleRecord(query, data, params, addLimitTo1); } tristate KDbConnectionProxy::querySingleString(const KDbEscapedString& sql, QString* value, int column, bool addLimitTo1) { return d->connection->querySingleString(sql, value, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleString(KDbQuerySchema* query, QString* value, int column, bool addLimitTo1) { return d->connection->querySingleString(query, value, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column, bool addLimitTo1) { return d->connection->querySingleString(query, value, params, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleNumber(const KDbEscapedString& sql, int* number, int column, bool addLimitTo1) { return d->connection->querySingleNumber(sql, number, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleNumber(KDbQuerySchema* query, int* number, int column, bool addLimitTo1) { return d->connection->querySingleNumber(query, number, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column, bool addLimitTo1) { return d->connection->querySingleNumber(query, number, params, column, addLimitTo1); } bool KDbConnectionProxy::queryStringList(const KDbEscapedString& sql, QStringList* list, int column) { return d->connection->queryStringList(sql, list, column); } bool KDbConnectionProxy::queryStringList(KDbQuerySchema* query, QStringList* list, int column) { return d->connection->queryStringList(query, list, column); } bool KDbConnectionProxy::queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column) { return d->connection->queryStringList(query, list, params, column); } tristate KDbConnectionProxy::resultExists(const KDbEscapedString& sql, bool addLimitTo1) { return d->connection->resultExists(sql, addLimitTo1); } tristate KDbConnectionProxy::isEmpty(KDbTableSchema* table) { return d->connection->isEmpty(table); } KDbEscapedString KDbConnectionProxy::recentSQLString() const { return d->connection->recentSQLString(); } //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args, ...) bool KDbConnectionProxy::insertRecord(KDbTableSchema* tableSchema args) \ { \ return d->connection->insertRecord(tableSchema, __VA_ARGS__); \ } #define H_INS_REC_ALL \ H_INS_REC(A a1, a1) \ H_INS_REC(A a1 A a2, a1, a2) \ H_INS_REC(A a1 A a2 A a3, a1, a2, a3) \ H_INS_REC(A a1 A a2 A a3 A a4, a1, a2, a3, a4) \ H_INS_REC(A a1 A a2 A a3 A a4 A a5, a1, a2, a3, a4, a5) \ H_INS_REC(A a1 A a2 A a3 A a4 A a5 A a6, a1, a2, a3, a4, a5, a6) \ H_INS_REC(A a1 A a2 A a3 A a4 A a5 A a6 A a7, a1, a2, a3, a4, a5, a6, a7) \ H_INS_REC(A a1 A a2 A a3 A a4 A a5 A a6 A a7 A a8, a1, a2, a3, a4, a5, a6, a7, a8) H_INS_REC_ALL #undef H_INS_REC #define H_INS_REC(args, ...) bool KDbConnectionProxy::insertRecord(KDbFieldList* fields args) \ { \ return d->connection->insertRecord(fields, __VA_ARGS__); \ } H_INS_REC_ALL #undef H_INS_REC_ALL #undef H_INS_REC #undef A bool KDbConnectionProxy::insertRecord(KDbTableSchema* tableSchema, const QList& values) { return d->connection->insertRecord(tableSchema, values); } bool KDbConnectionProxy::insertRecord(KDbFieldList* fields, const QList& values) { return d->connection->insertRecord(fields, values); } bool KDbConnectionProxy::createTable(KDbTableSchema* tableSchema, bool replaceExisting) { return d->connection->createTable(tableSchema, replaceExisting); } KDbTableSchema *KDbConnectionProxy::copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData) { return d->connection->copyTable(tableSchema, newData); } KDbTableSchema *KDbConnectionProxy::copyTable(const QString& tableName, const KDbObject &newData) { return d->connection->copyTable(tableName, newData); } tristate KDbConnectionProxy::dropTable(KDbTableSchema* tableSchema) { return d->connection->dropTable(tableSchema); } tristate KDbConnectionProxy::dropTable(const QString& tableName) { return d->connection->dropTable(tableName); } tristate KDbConnectionProxy::alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema) { return d->connection->alterTable(tableSchema, newTableSchema); } bool KDbConnectionProxy::alterTableName(KDbTableSchema* tableSchema, const QString& newName, bool replace) { return d->connection->alterTableName(tableSchema, newName, replace); } bool KDbConnectionProxy::dropQuery(KDbQuerySchema* querySchema) { return d->connection->dropQuery(querySchema); } bool KDbConnectionProxy::dropQuery(const QString& queryName) { return d->connection->dropQuery(queryName); } bool KDbConnectionProxy::removeObject(int objId) { return d->connection->removeObject(objId); } KDbField* KDbConnectionProxy::findSystemFieldName(const KDbFieldList& fieldlist) { return d->connection->findSystemFieldName(fieldlist); } QString KDbConnectionProxy::anyAvailableDatabaseName() { return d->connection->anyAvailableDatabaseName(); } void KDbConnectionProxy::setAvailableDatabaseName(const QString& dbName) { d->connection->setAvailableDatabaseName(dbName); } bool KDbConnectionProxy::useTemporaryDatabaseIfNeeded(QString* name) { return d->connection->useTemporaryDatabaseIfNeeded(name); } KDbSqlResult* KDbConnectionProxy::executeSQL(const KDbEscapedString& sql) { return d->connection->executeSQL(sql); } bool KDbConnectionProxy::executeVoidSQL(const KDbEscapedString& sql) { return d->connection->executeVoidSQL(sql); } bool KDbConnectionProxy::storeObjectData(KDbObject* object) { return d->connection->storeObjectData(object); } bool KDbConnectionProxy::storeNewObjectData(KDbObject* object) { return d->connection->storeNewObjectData(object); } tristate KDbConnectionProxy::loadObjectData(int id, KDbObject* object) { return d->connection->loadObjectData(id, object); } tristate KDbConnectionProxy::loadObjectData(int type, const QString& name, KDbObject* object) { return d->connection->loadObjectData(type, name, object); } tristate KDbConnectionProxy::loadDataBlock(int objectID, QString* dataString, const QString& dataID) { return d->connection->loadDataBlock(objectID, dataString, dataID); } bool KDbConnectionProxy::storeDataBlock(int objectID, const QString &dataString, const QString& dataID) { return d->connection->storeDataBlock(objectID, dataString, dataID); } bool KDbConnectionProxy::copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID) { return d->connection->copyDataBlock(sourceObjectID, destObjectID, dataID); } bool KDbConnectionProxy::removeDataBlock(int objectID, const QString& dataID) { return d->connection->removeDataBlock(objectID, dataID); } KDbPreparedStatement KDbConnectionProxy::prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames) { return d->connection->prepareStatement(type, fields, whereFieldNames); } bool KDbConnectionProxy::isInternalTableSchema(const QString& tableName) { return d->connection->isInternalTableSchema(tableName); } QString KDbConnectionProxy::escapeIdentifier(const QString& id) const { return d->connection->escapeIdentifier(id); } bool KDbConnectionProxy::drv_connect() { return d->connection->drv_connect(); } bool KDbConnectionProxy::drv_disconnect() { return d->connection->drv_disconnect(); } bool KDbConnectionProxy::drv_getServerVersion(KDbServerVersionInfo* version) { return d->connection->drv_getServerVersion(version); } tristate KDbConnectionProxy::drv_containsTable(const QString &tableName) { return d->connection->drv_containsTable(tableName); } bool KDbConnectionProxy::drv_createTable(const KDbTableSchema& tableSchema) { return d->connection->drv_createTable(tableSchema); } bool KDbConnectionProxy::drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) { return d->connection->drv_alterTableName(tableSchema, newName); } bool KDbConnectionProxy::drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) { return d->connection->drv_copyTableData(tableSchema, destinationTableSchema); } bool KDbConnectionProxy::drv_dropTable(const QString& tableName) { return d->connection->drv_dropTable(tableName); } tristate KDbConnectionProxy::dropTable(KDbTableSchema* tableSchema, bool alsoRemoveSchema) { return d->connection->dropTable(tableSchema, alsoRemoveSchema); } bool KDbConnectionProxy::setupObjectData(const KDbRecordData& data, KDbObject* object) { return d->connection->setupObjectData(data, object); } KDbField* KDbConnectionProxy::setupField(const KDbRecordData& data) { return d->connection->setupField(data); } KDbSqlResult* KDbConnectionProxy::drv_executeSQL(const KDbEscapedString& sql) { return d->connection->drv_executeSQL(sql); } bool KDbConnectionProxy::drv_executeVoidSQL(const KDbEscapedString& sql) { return d->connection->drv_executeVoidSQL(sql); } bool KDbConnectionProxy::drv_getDatabasesList(QStringList* list) { return d->connection->drv_getDatabasesList(list); } bool KDbConnectionProxy::drv_databaseExists(const QString &dbName, bool ignoreErrors) { return d->connection->drv_databaseExists(dbName, ignoreErrors); } bool KDbConnectionProxy::drv_createDatabase(const QString &dbName) { return d->connection->drv_createDatabase(dbName); } bool KDbConnectionProxy::drv_useDatabase(const QString &dbName, bool *cancelled, KDbMessageHandler* msgHandler) { return d->connection->drv_useDatabase(dbName, cancelled, msgHandler); } bool KDbConnectionProxy::drv_closeDatabase() { return d->connection->drv_closeDatabase(); } bool KDbConnectionProxy::drv_isDatabaseUsed() const { return d->connection->drv_isDatabaseUsed(); } bool KDbConnectionProxy::drv_dropDatabase(const QString &dbName) { return d->connection->drv_dropDatabase(dbName); } bool KDbConnectionProxy::drv_createTable(const QString& tableName) { return d->connection->drv_createTable(tableName); } KDbTransactionData* KDbConnectionProxy::drv_beginTransaction() { return d->connection->drv_beginTransaction(); } bool KDbConnectionProxy::drv_commitTransaction(KDbTransactionData* trans) { return d->connection->drv_commitTransaction(trans); } bool KDbConnectionProxy::drv_rollbackTransaction(KDbTransactionData* trans) { return d->connection->drv_rollbackTransaction(trans); } bool KDbConnectionProxy::drv_beforeInsert(const QString& tableName, KDbFieldList* fields) { return d->connection->drv_beforeInsert(tableName, fields); } bool KDbConnectionProxy::drv_afterInsert(const QString& tableName, KDbFieldList* fields) { return d->connection->drv_afterInsert(tableName, fields); } bool KDbConnectionProxy::drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) { return d->connection->drv_beforeUpdate(tableName, fields); } bool KDbConnectionProxy::drv_afterUpdate(const QString& tableName, KDbFieldList* fields) { return d->connection->drv_afterUpdate(tableName, fields); } bool KDbConnectionProxy::drv_setAutoCommit(bool on) { return d->connection->drv_setAutoCommit(on); } KDbPreparedStatementInterface* KDbConnectionProxy::prepareStatementInternal() { return d->connection->prepareStatementInternal(); } bool KDbConnectionProxy::beginAutoCommitTransaction(KDbTransactionGuard* tg) { return d->connection->beginAutoCommitTransaction(tg); } bool KDbConnectionProxy::commitAutoCommitTransaction(const KDbTransaction& trans) { return d->connection->commitAutoCommitTransaction(trans); } bool KDbConnectionProxy::rollbackAutoCommitTransaction(const KDbTransaction& trans) { return d->connection->rollbackAutoCommitTransaction(trans); } bool KDbConnectionProxy::checkConnected() { return d->connection->checkConnected(); } bool KDbConnectionProxy::checkIsDatabaseUsed() { return d->connection->checkIsDatabaseUsed(); } KDbTableSchema* KDbConnectionProxy::setupTableSchema(const KDbRecordData& data) { return d->connection->setupTableSchema(data); } KDbQuerySchema* KDbConnectionProxy::setupQuerySchema(const KDbRecordData& data) { return d->connection->setupQuerySchema(data); } bool KDbConnectionProxy::updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { return d->connection->updateRecord(query, data, buf, useRecordId); } bool KDbConnectionProxy::insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId) { return d->connection->insertRecord(query, data, buf, getRecordId); } bool KDbConnectionProxy::deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId) { return d->connection->deleteRecord(query, data, useRecordId); } bool KDbConnectionProxy::deleteAllRecords(KDbQuerySchema* query) { return d->connection->deleteAllRecords(query); } bool KDbConnectionProxy::checkIfColumnExists(KDbCursor *cursor, int column) { return d->connection->checkIfColumnExists(cursor, column); } tristate KDbConnectionProxy::querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, bool addLimitTo1) { return d->connection->querySingleRecordInternal(data, sql, query, params, addLimitTo1); } tristate KDbConnectionProxy::querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1) { return d->connection->querySingleStringInternal(sql, value, query, params, column, addLimitTo1); } tristate KDbConnectionProxy::querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1) { return d->connection->querySingleNumberInternal(sql, number, query, params, column, addLimitTo1); } bool KDbConnectionProxy::queryStringListInternal(const KDbEscapedString *sql, QStringList* list, KDbQuerySchema* query, const QList* params, int column, bool (*filterFunction)(const QString&)) { return d->connection->queryStringListInternal(sql, list, query, params, column, filterFunction); } KDbCursor* KDbConnectionProxy::executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params) { return d->connection->executeQueryInternal(sql, query, params); } bool KDbConnectionProxy::loadExtendedTableSchemaData(KDbTableSchema* tableSchema) { return d->connection->loadExtendedTableSchemaData(tableSchema); } bool KDbConnectionProxy::storeExtendedTableSchemaData(KDbTableSchema* tableSchema) { return d->connection->storeExtendedTableSchemaData(tableSchema); } bool KDbConnectionProxy::storeMainFieldSchema(KDbField *field) { return d->connection->storeMainFieldSchema(field); } diff --git a/src/KDbConnectionProxy.h b/src/KDbConnectionProxy.h index 3441a932..bdbe6485 100644 --- a/src/KDbConnectionProxy.h +++ b/src/KDbConnectionProxy.h @@ -1,397 +1,397 @@ /* This file is part of the KDE project Copyright (C) 2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTIONPROXY_H #define KDB_CONNECTIONPROXY_H #include //! The KDbConnectionProxy class gives access to protected (low-level) API of KDbConnection /** * The connection object specified in constructor of the proxy is called a parent connection. * All inherited methods of the KDbConnection API call equivalent methods of the parent * connection. The KDbConnectionProxy class also provides non-virtual methods that are * equivalent to KDbConnection ones. These KDbConnection's equivalent methods are called * by the proxy too. * * Example use of this class is Kexi's database database migration plugins when the source * database is only accessibly using low-level routines. */ class KDB_EXPORT KDbConnectionProxy : protected KDbConnection { public: //! Creates a proxy object for parent @a connection. //! @a connection must not be @c nullptr. //! It is owned by this proxy unless setConnectionIsOwned(false) is called. explicit KDbConnectionProxy(KDbConnection *connection); //! Deletes this proxy. Owned connection is closed and destroyed. ~KDbConnectionProxy(); //! @return parent connection for this proxy KDbConnection *parentConnection(); //! @overload KDbConnection *parentConnection() const KDbConnection *parentConnection() const; //! Control owhership of parent connection that is assigned to this proxy. //! Owned connection is closed and destroyed upon destruction of the KDbConnectionProxy //! object. void setParentConnectionIsOwned(bool set); KDbConnectionData data() const; KDbDriver* driver() const; bool connect(); bool isConnected() const; bool isDatabaseUsed() const; KDbConnectionOptions *options(); void clearResult(); KDbResult result() const; KDbResultable resultable() const; bool disconnect(); QStringList databaseNames(bool also_system_db = false); bool databaseExists(const QString &dbName, bool ignoreErrors = true); bool createDatabase(const QString &dbName); bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr); bool closeDatabase(); QString currentDatabase() const; bool dropDatabase(const QString &dbName = QString()); QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr); QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr); tristate containsTable(const QString &tableName); KDbServerVersionInfo serverVersion() const; KDbVersionInfo databaseVersion() const; KDbProperties databaseProperties() const; QList tableIds(bool* ok = nullptr); QList queryIds(bool* ok = nullptr); QList objectIds(int objectType, bool* ok = nullptr); KDbTransaction beginTransaction(); bool commitTransaction(KDbTransaction trans = KDbTransaction(), bool ignore_inactive = false); bool rollbackTransaction(KDbTransaction trans = KDbTransaction(), bool ignore_inactive = false); KDbTransaction defaultTransaction() const; void setDefaultTransaction(const KDbTransaction& trans); QList transactions(); bool autoCommit() const; bool setAutoCommit(bool on); KDbEscapedString escapeString(const QString& str) const Q_DECL_OVERRIDE; - KDbCursor* prepareQuery(const KDbEscapedString& sql, int cursor_options = 0) Q_DECL_OVERRIDE; + KDbCursor* prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE; - KDbCursor* prepareQuery(KDbQuerySchema* query, int cursor_options = 0) Q_DECL_OVERRIDE; + KDbCursor* prepareQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE; - KDbCursor* prepareQuery(KDbTableSchema* table, int cursor_options = 0); + KDbCursor* prepareQuery(KDbTableSchema* table, KDbCursor::Options options = KDbCursor::Option::None); - KDbCursor* executeQuery(const KDbEscapedString& sql, int cursor_options = 0); + KDbCursor* executeQuery(const KDbEscapedString& sql, KDbCursor::Options options = KDbCursor::Option::None); KDbCursor* executeQuery(KDbQuerySchema* query, const QList& params, - int cursor_options = 0); + KDbCursor::Options options = KDbCursor::Option::None); - KDbCursor* executeQuery(KDbQuerySchema* query, int cursor_options = 0); + KDbCursor* executeQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None); - KDbCursor* executeQuery(KDbTableSchema* table, int cursor_options = 0); + KDbCursor* executeQuery(KDbTableSchema* table, KDbCursor::Options options = KDbCursor::Option::None); bool deleteCursor(KDbCursor *cursor); KDbTableSchema* tableSchema(int tableId); KDbTableSchema* tableSchema(const QString& tableName); KDbQuerySchema* querySchema(int queryId); KDbQuerySchema* querySchema(const QString& queryName); bool setQuerySchemaObsolete(const QString& queryName); tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, bool addLimitTo1 = true); tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1 = true); tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, bool addLimitTo1 = true); tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, bool addLimitTo1 = true); tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, bool addLimitTo1 = true); tristate querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column = 0, bool addLimitTo1 = true); tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0, bool addLimitTo1 = true); tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, bool addLimitTo1 = true); tristate querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column = 0, bool addLimitTo1 = true); bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0); bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); bool queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column = 0); tristate resultExists(const KDbEscapedString& sql, bool addLimitTo1 = true); tristate isEmpty(KDbTableSchema* table); KDbEscapedString recentSQLString() const Q_DECL_OVERRIDE; //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args) bool insertRecord(KDbTableSchema* tableSchema args) #define H_INS_REC_ALL \ H_INS_REC(A); \ H_INS_REC(A A); \ H_INS_REC(A A A); \ H_INS_REC(A A A A); \ H_INS_REC(A A A A A); \ H_INS_REC(A A A A A A); \ H_INS_REC(A A A A A A A); \ H_INS_REC(A A A A A A A A) H_INS_REC_ALL; #undef H_INS_REC #define H_INS_REC(args) bool insertRecord(KDbFieldList* fields args) H_INS_REC_ALL; #undef H_INS_REC_ALL #undef H_INS_REC #undef A bool insertRecord(KDbTableSchema* tableSchema, const QList& values); bool insertRecord(KDbFieldList* fields, const QList& values); bool createTable(KDbTableSchema* tableSchema, bool replaceExisting = false); KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData); KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData); tristate dropTable(KDbTableSchema* tableSchema); tristate dropTable(const QString& tableName); tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema); bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, bool replace = false); bool dropQuery(KDbQuerySchema* querySchema); bool dropQuery(const QString& queryName); bool removeObject(int objId); KDbField* findSystemFieldName(const KDbFieldList& fieldlist); QString anyAvailableDatabaseName() Q_DECL_OVERRIDE; void setAvailableDatabaseName(const QString& dbName); bool useTemporaryDatabaseIfNeeded(QString* name); KDbSqlResult* executeSQL(const KDbEscapedString& sql) Q_REQUIRED_RESULT; bool executeVoidSQL(const KDbEscapedString& sql); bool storeObjectData(KDbObject* object); bool storeNewObjectData(KDbObject* object); tristate loadObjectData(int id, KDbObject* object); tristate loadObjectData(int type, const QString& name, KDbObject* object); tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString()); bool storeDataBlock(int objectID, const QString &dataString, const QString& dataID = QString()); bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString()); bool removeDataBlock(int objectID, const QString& dataID = QString()); KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames = QStringList()); bool isInternalTableSchema(const QString& tableName); QString escapeIdentifier(const QString& id) const Q_DECL_OVERRIDE; bool drv_connect() Q_DECL_OVERRIDE; bool drv_disconnect() Q_DECL_OVERRIDE; bool drv_getServerVersion(KDbServerVersionInfo* version) Q_DECL_OVERRIDE; tristate drv_containsTable(const QString &tableName) Q_DECL_OVERRIDE; bool drv_createTable(const KDbTableSchema& tableSchema) Q_DECL_OVERRIDE; bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) Q_DECL_OVERRIDE; bool drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) Q_DECL_OVERRIDE; bool drv_dropTable(const QString& tableName) Q_DECL_OVERRIDE; tristate dropTable(KDbTableSchema* tableSchema, bool alsoRemoveSchema); bool setupObjectData(const KDbRecordData& data, KDbObject* object); KDbField* setupField(const KDbRecordData& data); KDbSqlResult* drv_executeSQL(const KDbEscapedString& sql) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; bool drv_executeVoidSQL(const KDbEscapedString& sql) Q_DECL_OVERRIDE; bool drv_getDatabasesList(QStringList* list) Q_DECL_OVERRIDE; bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true) Q_DECL_OVERRIDE; bool drv_createDatabase(const QString &dbName = QString()) Q_DECL_OVERRIDE; bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) Q_DECL_OVERRIDE; bool drv_closeDatabase() Q_DECL_OVERRIDE; bool drv_isDatabaseUsed() const Q_DECL_OVERRIDE; bool drv_dropDatabase(const QString &dbName = QString()) Q_DECL_OVERRIDE; bool drv_createTable(const QString& tableName) Q_DECL_OVERRIDE; KDbTransactionData* drv_beginTransaction() Q_DECL_OVERRIDE; bool drv_commitTransaction(KDbTransactionData* trans) Q_DECL_OVERRIDE; bool drv_rollbackTransaction(KDbTransactionData* trans) Q_DECL_OVERRIDE; bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) Q_DECL_OVERRIDE; bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) Q_DECL_OVERRIDE; bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) Q_DECL_OVERRIDE; bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) Q_DECL_OVERRIDE; bool drv_setAutoCommit(bool on) Q_DECL_OVERRIDE; KDbPreparedStatementInterface* prepareStatementInternal() Q_DECL_OVERRIDE; bool beginAutoCommitTransaction(KDbTransactionGuard* tg); bool commitAutoCommitTransaction(const KDbTransaction& trans); bool rollbackAutoCommitTransaction(const KDbTransaction& trans); bool checkConnected(); bool checkIsDatabaseUsed(); KDbTableSchema* setupTableSchema(const KDbRecordData& data); KDbQuerySchema* setupQuerySchema(const KDbRecordData& data); bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false); bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false); bool deleteAllRecords(KDbQuerySchema* query); bool checkIfColumnExists(KDbCursor *cursor, int column); tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, bool addLimitTo1 = true); tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1); tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, bool addLimitTo1); bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list, KDbQuerySchema* query, const QList* params, int column, bool (*filterFunction)(const QString&)); KDbCursor* executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params); bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema); bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema); bool storeMainFieldSchema(KDbField *field); private: Q_DISABLE_COPY(KDbConnectionProxy) class Private; Private * const d; }; #endif diff --git a/src/KDbCursor.cpp b/src/KDbCursor.cpp index 668405bb..b4e26a8b 100644 --- a/src/KDbCursor.cpp +++ b/src/KDbCursor.cpp @@ -1,608 +1,608 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbCursor.h" #include "KDbConnection.h" #include "KDbDriver.h" #include "KDbDriverBehavior.h" #include "KDbError.h" #include "KDb.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbRecordData.h" #include "KDbRecordEditBuffer.h" #include "kdb_debug.h" #include #include class Q_DECL_HIDDEN KDbCursor::Private { public: Private() : opened(false) , atLast(false) , readAhead(false) , validRecord(false) , atBuffer(false) { } ~Private() { } bool containsRecordIdInfo; //!< true if result contains extra column for record id; //!< used only for PostgreSQL now //! @todo IMPORTANT: use something like QPointer conn; KDbConnection *conn; KDbEscapedString rawSql; bool opened; bool atLast; bool readAhead; bool validRecord; //!< true if valid record is currently retrieved @ current position //! Used by setOrderByColumnList() KDbQueryColumnInfo::Vector orderByColumnList; QList queryParameters; // bool atBuffer; //!< true if we already point to the buffer with curr_coldata // }; -KDbCursor::KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, int options) +KDbCursor::KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, Options options) : m_query(0) , m_options(options) , d(new Private) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String("Create cursor for raw SQL: ") + sql.toString()); #endif init(conn); d->rawSql = sql; } -KDbCursor::KDbCursor(KDbConnection* conn, KDbQuerySchema* query, int options) +KDbCursor::KDbCursor(KDbConnection* conn, KDbQuerySchema* query, Options options) : m_query(query) , m_options(options) , d(new Private) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QString::fromLatin1("Create cursor for query \"%1\":\n") .arg(KDb::iifNotEmpty(query->name(), QString::fromLatin1(""))) + KDbUtils::debugString(query)); #endif init(conn); } void KDbCursor::init(KDbConnection* conn) { Q_ASSERT(conn); d->conn = conn; d->conn->addCursor(this); m_afterLast = false; m_at = 0; m_records_in_buf = 0; m_buffering_completed = false; m_fetchResult = FetchInvalid; d->containsRecordIdInfo = (m_query && m_query->masterTable()) && d->conn->driver()->beh->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE == false; if (m_query) { //get list of all fields m_visibleFieldsExpanded = new KDbQueryColumnInfo::Vector(); *m_visibleFieldsExpanded = m_query->visibleFieldsExpanded( d->containsRecordIdInfo ? KDbQuerySchema::WithInternalFieldsAndRecordId : KDbQuerySchema::WithInternalFields); m_logicalFieldCount = m_visibleFieldsExpanded->count() - m_query->internalFields().count() - (d->containsRecordIdInfo ? 1 : 0); m_fieldCount = m_visibleFieldsExpanded->count(); m_fieldsToStoreInRecord = m_fieldCount; } else { m_visibleFieldsExpanded = 0; m_logicalFieldCount = 0; m_fieldCount = 0; m_fieldsToStoreInRecord = 0; } } KDbCursor::~KDbCursor() { #ifdef KDB_DEBUG_GUI #if 0 // too many details if (m_query) KDb::debugGUI(QLatin1String("~ Delete cursor for query")); else KDb::debugGUI(QLatin1String("~ Delete cursor: ") + m_rawSql.toString()); #endif #endif /* if (!m_query) kdbDebug() << "KDbCursor::~KDbCursor() '" << m_rawSql.toLatin1() << "'"; else kdbDebug() << "KDbCursor::~KDbCursor() ";*/ d->conn->takeCursor(this); delete m_visibleFieldsExpanded; delete d; } bool KDbCursor::readAhead() const { return d->readAhead; } KDbConnection* KDbCursor::connection() const { return d->conn; } KDbQuerySchema *KDbCursor::query() const { return m_query; } KDbEscapedString KDbCursor::rawSql() const { return d->rawSql; } -int KDbCursor::options() const +KDbCursor::Options KDbCursor::options() const { return m_options; } bool KDbCursor::isOpened() const { return d->opened; } bool KDbCursor::containsRecordIdInfo() const { return d->containsRecordIdInfo; } KDbRecordData* KDbCursor::storeCurrentRecord() const { KDbRecordData* data = new KDbRecordData(m_fieldsToStoreInRecord); if (!drv_storeCurrentRecord(data)) { delete data; return 0; } return data; } bool KDbCursor::storeCurrentRecord(KDbRecordData* data) const { Q_ASSERT(data); data->resize(m_fieldsToStoreInRecord); return drv_storeCurrentRecord(data); } bool KDbCursor::open() { if (d->opened) { if (!close()) return false; } if (!d->rawSql.isEmpty()) { m_result.setSql(d->rawSql); } else { if (!m_query) { kdbDebug() << "no query statement (or schema) defined!"; m_result = KDbResult(ERR_SQL_EXECUTION_ERROR, tr("No query statement or schema defined.")); return false; } KDbSelectStatementOptions options; options.alsoRetrieveRecordId = d->containsRecordIdInfo; /*get record Id if needed*/ KDbNativeStatementBuilder builder(d->conn); KDbEscapedString sql; if (!builder.generateSelectStatement(&sql, m_query, options, d->queryParameters) || sql.isEmpty()) { kdbDebug() << "no statement generated!"; m_result = KDbResult(ERR_SQL_EXECUTION_ERROR, tr("Could not generate query statement.")); return false; } m_result.setSql(sql); #ifdef KDB_DEBUG_GUI KDb::debugGUI(QString::fromLatin1("SQL for query \"%1\": ") .arg(KDb::iifNotEmpty(m_query->name(), QString::fromLatin1(""))) + m_result.sql().toString()); #endif } d->opened = drv_open(m_result.sql()); m_afterLast = false; //we are not @ the end m_at = 0; //we are before 1st rec if (!d->opened) { m_result.setCode(ERR_SQL_EXECUTION_ERROR); m_result.setMessage(tr("Error opening database cursor.")); return false; } d->validRecord = false; if (d->conn->driver()->beh->_1ST_ROW_READ_AHEAD_REQUIRED_TO_KNOW_IF_THE_RESULT_IS_EMPTY) { // kdbDebug() << "READ AHEAD:"; d->readAhead = getNextRecord(); //true if any record in this query // kdbDebug() << "READ AHEAD = " << d->readAhead; } m_at = 0; //we are still before 1st rec return !m_result.isError(); } bool KDbCursor::close() { if (!d->opened) { return true; } bool ret = drv_close(); clearBuffer(); d->opened = false; m_afterLast = false; d->readAhead = false; m_fieldCount = 0; m_fieldsToStoreInRecord = 0; m_logicalFieldCount = 0; m_at = -1; // kdbDebug() << ret; return ret; } bool KDbCursor::reopen() { if (!d->opened) { return open(); } return close() && open(); } bool KDbCursor::moveFirst() { if (!d->opened) { return false; } if (!d->readAhead) { - if (m_options & Buffered) { + if (m_options & KDbCursor::Option::Buffered) { if (m_records_in_buf == 0 && m_buffering_completed) { //eof and bof should now return true: m_afterLast = true; m_at = 0; return false; //buffering completed and there is no records! } if (m_records_in_buf > 0) { //set state as we would be before first rec: d->atBuffer = false; m_at = 0; //..and move to next, ie. 1st record m_afterLast = !getNextRecord(); return !m_afterLast; } } else if (!(d->conn->driver()->beh->_1ST_ROW_READ_AHEAD_REQUIRED_TO_KNOW_IF_THE_RESULT_IS_EMPTY)) { // not buffered m_at = 0; m_afterLast = !getNextRecord(); return !m_afterLast; } if (m_afterLast && m_at == 0) //failure if already no records return false; if (!reopen()) //try reopen return false; if (m_afterLast) //eof return false; } else { //we have a record already read-ahead: we now point @ that: m_at = 1; } //get first record m_afterLast = false; d->readAhead = false; //1st record had been read return d->validRecord; } bool KDbCursor::moveLast() { if (!d->opened) { return false; } if (m_afterLast || d->atLast) { return d->validRecord; //we already have valid last record retrieved } if (!getNextRecord()) { //at least next record must be retrieved m_afterLast = true; d->validRecord = false; d->atLast = false; return false; //no records } while (getNextRecord()) //move after last rec. ; m_afterLast = false; //cursor shows last record data d->atLast = true; return true; } bool KDbCursor::moveNext() { if (!d->opened || m_afterLast) { return false; } if (getNextRecord()) { return true; } return false; } bool KDbCursor::movePrev() { - if (!d->opened /*|| m_beforeFirst*/ || !(m_options & Buffered)) { + if (!d->opened /*|| m_beforeFirst*/ || !(m_options & KDbCursor::Option::Buffered)) { return false; } //we're after last record and there are records in the buffer //--let's move to last record if (m_afterLast && (m_records_in_buf > 0)) { drv_bufferMovePointerTo(m_records_in_buf - 1); m_at = m_records_in_buf; d->atBuffer = true; //now current record is stored in the buffer d->validRecord = true; m_afterLast = false; return true; } //we're at first record: go BOF if ((m_at <= 1) || (m_records_in_buf <= 1/*sanity*/)) { m_at = 0; d->atBuffer = false; d->validRecord = false; return false; } m_at--; if (d->atBuffer) {//we already have got a pointer to buffer drv_bufferMovePointerPrev(); //just move to prev record in the buffer } else {//we have no pointer //compute a place in the buffer that contain next record's data drv_bufferMovePointerTo(m_at - 1); d->atBuffer = true; //now current record is stored in the buffer } d->validRecord = true; m_afterLast = false; return true; } bool KDbCursor::isBuffered() const { - return m_options & Buffered; + return m_options & KDbCursor::Option::Buffered; } void KDbCursor::setBuffered(bool buffered) { if (!d->opened) { return; } if (isBuffered() == buffered) return; - m_options ^= Buffered; + m_options ^= KDbCursor::Option::Buffered; } void KDbCursor::clearBuffer() { if (!isBuffered() || m_fieldCount == 0) return; drv_clearBuffer(); m_records_in_buf = 0; d->atBuffer = false; } bool KDbCursor::getNextRecord() { m_fetchResult = FetchInvalid; //by default: invalid result of record fetching - if (m_options & Buffered) {//this cursor is buffered: + if (m_options & KDbCursor::Option::Buffered) {//this cursor is buffered: // kdbDebug() << "m_at < m_records_in_buf :: " << (long)m_at << " < " << m_records_in_buf; if (m_at < m_records_in_buf) {//we have next record already buffered: if (d->atBuffer) {//we already have got a pointer to buffer drv_bufferMovePointerNext(); //just move to next record in the buffer } else {//we have no pointer //compute a place in the buffer that contain next record's data drv_bufferMovePointerTo(m_at - 1 + 1); d->atBuffer = true; //now current record is stored in the buffer } } else {//we are after last retrieved record: we need to physically fetch next record: if (!d->readAhead) {//we have no record that was read ahead if (!m_buffering_completed) { //retrieve record only if we are not after //the last buffer's item (i.e. when buffer is not fully filled): // kdbDebug()<<"==== buffering: drv_getNextRecord() ===="; drv_getNextRecord(); } if (m_fetchResult != FetchOK) {//there is no record m_buffering_completed = true; //no more records for buffer // kdbDebug()<<"m_fetchResult != FetchOK ********"; d->validRecord = false; m_afterLast = true; m_at = -1; //position is invalid now and will not be used if (m_fetchResult == FetchError) { m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Could not fetch next record.")); return false; } return false; // in case of m_fetchResult = FetchEnd or m_fetchResult = FetchInvalid } //we have a record: store this record's values in the buffer drv_appendCurrentRecordToBuffer(); m_records_in_buf++; } else //we have a record that was read ahead: eat this d->readAhead = false; } } else {//we are after last retrieved record: we need to physically fetch next record: if (!d->readAhead) {//we have no record that was read ahead // kdbDebug()<<"==== no prefetched record ===="; drv_getNextRecord(); if (m_fetchResult != FetchOK) {//there is no record // kdbDebug()<<"m_fetchResult != FetchOK ********"; d->validRecord = false; m_afterLast = true; m_at = -1; if (m_fetchResult == FetchEnd) { return false; } m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Could not fetch next record.")); return false; } } else { //we have a record that was read ahead: eat this d->readAhead = false; } } m_at++; // if (m_data->curr_colname && m_data->curr_coldata) // for (int i=0;icurr_cols;i++) { // kdbDebug()<curr_colname[i]<<" == "<< m_data->curr_coldata[i]; // } // kdbDebug()<<"m_at == "<<(long)m_at; d->validRecord = true; return true; } bool KDbCursor::updateRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->updateRecord(m_query, data, buf, useRecordId); } bool KDbCursor::insertRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! if (!m_query) { clearResult(); return false; } return d->conn->insertRecord(m_query, data, buf, useRecordId); } bool KDbCursor::deleteRecord(KDbRecordData* data, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->deleteRecord(m_query, data, useRecordId); } bool KDbCursor::deleteAllRecords() { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->deleteAllRecords(m_query); } QDebug operator<<(QDebug dbg, const KDbCursor& cursor) { dbg.nospace() << "CURSOR("; if (!cursor.query()) { dbg.nospace() << "RAW SQL STATEMENT:" << cursor.rawSql().toString() << "\n"; } else { KDbNativeStatementBuilder builder(cursor.connection()); KDbEscapedString sql; QString sqlString; if (builder.generateSelectStatement(&sql, cursor.query())) { sqlString = sql.toString(); } else { sqlString = QLatin1String(""); } dbg.nospace() << "KDbQuerySchema:" << sqlString << "\n"; } if (cursor.isOpened()) { dbg.space() << "OPENED"; } else { dbg.space() << "NOT_OPENED"; } if (cursor.isBuffered()) { dbg.space() << "BUFFERED"; } else { dbg.space() << "NOT_BUFFERED"; } dbg.nospace() << "AT=" << cursor.at() << ")"; return dbg.space(); } void KDbCursor::setOrderByColumnList(const QStringList& columnNames) { Q_UNUSED(columnNames); //! @todo implement this: all field names should be found, exit otherwise // OK //! @todo if (!d->orderByColumnList) } /*! Convenience method, similar to setOrderBy(const QStringList&). */ void KDbCursor::setOrderByColumnList(const QString& column1, const QString& column2, const QString& column3, const QString& column4, const QString& column5) { Q_UNUSED(column1); Q_UNUSED(column2); Q_UNUSED(column3); Q_UNUSED(column4); Q_UNUSED(column5); //! @todo implement this, like above //! @todo add ORDER BY info to debugString() } KDbQueryColumnInfo::Vector KDbCursor::orderByColumnList() const { return d->orderByColumnList; } QList KDbCursor::queryParameters() const { return d->queryParameters; } void KDbCursor::setQueryParameters(const QList& params) { d->queryParameters = params; } //! @todo extraMessages #if 0 static const char *extraMessages[] = { QT_TRANSLATE_NOOP("KDbCursor", "No connection for cursor open operation specified.") }; #endif diff --git a/src/KDbCursor.h b/src/KDbCursor.h index 85e1dabe..62ff2dd8 100644 --- a/src/KDbCursor.h +++ b/src/KDbCursor.h @@ -1,333 +1,335 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CURSOR_H #define KDB_CURSOR_H #include #include #include "KDbResult.h" #include "KDbQueryColumnInfo.h" class KDbConnection; class KDbRecordData; class KDbQuerySchema; class KDbRecordEditBuffer; //! Provides database cursor functionality. /*! Cursor can be defined in two ways: -# by passing KDbQuerySchema object to KDbConnection::executeQuery() or KDbConnection::prepareQuery(); then query is defined for in engine-independent way -- this is recommended usage -# by passing raw query statement string to KDbConnection::executeQuery() or KDbConnection::prepareQuery(); then query may be defined for in engine-dependent way -- this is not recommended usage, but convenient when we can't or do not want to allocate KDbQuerySchema object, while we know that the query statement is syntactically and logically ok in our context. You can move cursor to next record with moveNext() and move back with movePrev(). The cursor is always positioned on record, not between records, with exception that after open() it is positioned before the first record (if any) -- then bof() equals true. The cursor can also be positioned after the last record (if any) with moveNext() -- then eof() equals true. For example, if you have four records, 1, 2, 3, 4, then after calling open(), moveNext(), moveNext(), moveNext(), movePrev() you are going through records: 1, 2, 3, 2. Cursor can be buffered or unbuferred. @warning Buffered cursors are not implemented! Buffering in this class is not related to any SQL engine capatibilities for server-side cursors (eg. like 'DECLARE CURSOR' statement) - buffered data is at client (application) side. Any record retrieved in buffered cursor will be stored inside an internal buffer and reused when needed. Unbuffered cursor always requires one record fetching from db connection at every step done with moveNext(), movePrev(), etc. Notes: - Do not use delete operator for KDbCursor objects - this will fail; use KDbConnection::deleteCursor() instead. - KDbQuerySchema object is not owned by KDbCursor object that uses it. */ class KDB_EXPORT KDbCursor: public KDbResultable { Q_DECLARE_TR_FUNCTIONS(KDbCursor) public: - //! KDbCursor options that describes its behavior - enum Options { - NoOptions = 0, + //! Options that describe behavior of database cursor + enum class Option { + None = 0, Buffered = 1 }; + Q_DECLARE_FLAGS(Options, Option) /*! @return connection used for the cursor */ KDbConnection* connection() const; /*! Opens the cursor using data provided on creation. The data might be either KDbQuerySchema or a raw SQL statement. */ bool open(); /*! Closes and then opens again the same cursor. If the cursor is not opened it is just opened and result of this open is returned. Otherwise, true is returned if cursor is successfully closed and then opened. */ bool reopen(); /*! Closes previously opened cursor. If the cursor is closed, nothing happens. */ virtual bool close(); /*! @return query schema used to define this cursor or 0 if the cursor is not defined by a query schema but by a raw SQL statement. */ KDbQuerySchema *query() const; //! @return query parameters assigned to this cursor QList queryParameters() const; //! Sets query parameters @a params for this cursor. void setQueryParameters(const QList& params); /*! @return raw query statement used to define this cursor or null string if raw statement instead (but KDbQuerySchema is defined instead). */ KDbEscapedString rawSql() const; - /*! @return logically or'd cursor's options, - selected from KDbCursor::Options enum. */ - int options() const; + /*! @return cursor options */ + Options options() const; /*! @return true if the cursor is opened. */ bool isOpened() const; /*! @return true if the cursor is buffered. */ bool isBuffered() const; /*! Sets this cursor to buffered type or not. See description of buffered and nonbuffered cursors in class description. This method only works if cursor is not opened (isOpened()==false). You can close already opened cursor and then switch this option on/off. */ void setBuffered(bool buffered); /*! Moves current position to the first record and retrieves it. @return true if the first record was retrieved. False could mean that there was an error or there is no record available. */ bool moveFirst(); /*! Moves current position to the last record and retrieves it. @return true if the last record was retrieved. False could mean that there was an error or there is no record available. */ virtual bool moveLast(); /*! Moves current position to the next record and retrieves it. */ virtual bool moveNext(); /*! Moves current position to the next record and retrieves it. Currently it's only supported for buffered cursors. */ virtual bool movePrev(); /*! @return true if current position is after last record. */ inline bool eof() const { return m_afterLast; } /*! @return true if current position is before first record. */ inline bool bof() const { return m_at == 0; } /*! @return current internal position of the cursor's query. We are counting records from 0. Value -1 means that cursor does not point to any valid record (this happens eg. after open(), close(), and after moving after last record or before first one. */ inline qint64 at() const { return readAhead() ? 0 : (m_at - 1); } /*! @return number of fields available for this cursor. This never includes ROWID column or other internal columns (e.g. lookup). */ inline int fieldCount() const { return m_query ? m_logicalFieldCount : m_fieldCount; } /*! @return true if ROWID information is available for each record. ROWID information is available if KDbDriverBehavior::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE == false for a KDb database driver and the master table has no primary key defined. Phisically, ROWID value is returned after last returned field, so data vector's length is expanded by one. */ bool containsRecordIdInfo() const; /*! @return a value stored in column number @a i (counting from 0). It has unspecified behavior if the cursor is not at valid record. Note for driver developers: If @a i is >= than m_fieldCount, null QVariant value should be returned. To return a value typically you can use a pointer to internal structure that contain current record data (buffered or unbuffered). */ virtual QVariant value(int i) = 0; /*! [PROTOTYPE] @return current record data or NULL if there is no current records. */ virtual const char ** recordData() const = 0; /*! Sets a list of columns for ORDER BY section of the query. Only works when the cursor has been created using KDbQuerySchema object (i.e. when query()!=0; does not work with raw statements). Each name on the list must be a field or alias present within the query and must not be covered by aliases. If one or more names cannot be found within the query, the method will have no effect. Any previous ORDER BY settings will be removed. The order list provided here has priority over a list defined in the KDbQuerySchema object itseld (using KDbQuerySchema::setOrderByColumnList()). The KDbQuerySchema object itself is not modifed by this method: only order of records retrieved by this cursor is affected. Use this method before calling open(). You can also call reopen() after calling this method to see effects of applying records order. */ //! @todo implement this void setOrderByColumnList(const QStringList& columnNames); /*! Convenience method, similar to setOrderByColumnList(const QStringList&). */ //! @todo implement this void setOrderByColumnList(const QString& column1, const QString& column2 = QString(), const QString& column3 = QString(), const QString& column4 = QString(), const QString& column5 = QString()); /*! @return a list of fields contained in ORDER BY section of the query. @see setOrderBy(const QStringList&) */ KDbQueryColumnInfo::Vector orderByColumnList() const; /*! Allocates a new KDbRecordData and stores data in it (makes a deep copy of each field). If the cursor is not at valid record, the result is undefined. @return newly created record data object or 0 on error. */ KDbRecordData* storeCurrentRecord() const; /*! Puts current record's data into @a data (makes a deep copy of each field). If the cursor is not at valid record, the result is undefined. @return true on success. */ bool storeCurrentRecord(KDbRecordData* data) const; bool updateRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); bool insertRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecrordId = false); bool deleteRecord(KDbRecordData* data, bool useRecordId = false); bool deleteAllRecords(); protected: /*! Cursor will operate on @a conn, raw SQL statement @a sql will be used to execute query. */ - KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, int options = NoOptions); + KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, Options options = KDbCursor::Option::None); /*! Cursor will operate on @a conn, @a query schema will be used to execute query. */ - KDbCursor(KDbConnection* conn, KDbQuerySchema* query, int options = NoOptions); + KDbCursor(KDbConnection* conn, KDbQuerySchema* query, Options options = KDbCursor::Option::None); virtual ~KDbCursor(); void init(KDbConnection* conn); /*! Internal: cares about proper flag setting depending on result of drv_getNextRecord() and depending on wherher a cursor is buffered. */ bool getNextRecord(); /*! Note for driver developers: this method should initialize engine-specific cursor's resources using an SQL statement @a sql. It is not required to store @a sql statement somewhere in your KDbCursor subclass (it is already stored in m_query or m_rawStatement, depending query type) - only pass it to proper engine's function. */ virtual bool drv_open(const KDbEscapedString& sql) = 0; virtual bool drv_close() = 0; virtual void drv_getNextRecord() = 0; /*! Stores currently fetched record's values in appropriate place of the buffer. Note for driver developers: This place can be computed using m_at. Do not change value of m_at or any other KDbCursor members, only change your internal structures like pointer to current record, etc. If your database engine's API function (for record fetching) do not allocates such a space, you want to allocate a space for current record. Otherwise, reuse existing structure, what could be more efficient. All functions like drv_appendCurrentRecordToBuffer() operates on the buffer, i.e. array of stored records. You are not forced to have any particular fixed structure for buffer item or buffer itself - the structure is internal and only methods like storeCurrentRecord() visible to public. */ virtual void drv_appendCurrentRecordToBuffer() = 0; /*! Moves pointer (that points to the buffer) -- to next item in this buffer. Note for driver developers: probably just execute "your_pointer++" is enough. */ virtual void drv_bufferMovePointerNext() = 0; /*! Like drv_bufferMovePointerNext() but execute "your_pointer--". */ virtual void drv_bufferMovePointerPrev() = 0; /*! Moves pointer (that points to the buffer) to a new place: @a at. */ virtual void drv_bufferMovePointerTo(qint64 at) = 0; /*! Clears cursor's buffer if this was allocated (only for buffered cursor type). Otherwise do nothing. For reimplementing. Default implementation does nothing. */ virtual void drv_clearBuffer() {} //! @internal clears buffer with reimplemented drv_clearBuffer(). */ void clearBuffer(); /*! Puts current record's data into @a data (makes a deep copy of each field). This method has unspecified behavior if the cursor is not at valid record. @return true on success. Note: For reimplementation in driver's code. Shortly, this method translates a record data from internal representation (probably also used in buffer) to simple public KDbRecordData representation. */ virtual bool drv_storeCurrentRecord(KDbRecordData* data) const = 0; KDbQuerySchema *m_query; bool m_afterLast; qint64 m_at; int m_fieldCount; //!< cached field count information int m_fieldsToStoreInRecord; //!< Used by storeCurrentRecord(), reimplement if needed //!< (e.g. PostgreSQL driver, when m_containsRecordIdInfo is true //!< sets m_fieldCount+1 here) int m_logicalFieldCount; //!< logical field count, i.e. without intrernal values like Record Id or lookup - int m_options; //!< cursor options that describes its behavior + KDbCursor::Options m_options; //!< cursor options that describes its behavior //! possible results of record fetching, used for m_fetchResult enum FetchResult { FetchInvalid, //!< used before starting the fetching, result is not known yet FetchError, //!< error of fetching FetchOK, //!< the data is fetched FetchEnd //!< at the end of data }; FetchResult m_fetchResult; //!< result of a record fetching // int m_records_in_buf; //!< number of records currently stored in the buffer bool m_buffering_completed; //!< true if we already have all records stored in the buffer // //! Useful e.g. for value(int) method to obtain access to schema definition. KDbQueryColumnInfo::Vector* m_visibleFieldsExpanded; private: bool readAhead() const; Q_DISABLE_COPY(KDbCursor) friend class CursorDeleter; class Private; Private * const d; }; //! Sends information about object @a cursor to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbCursor& cursor); +Q_DECLARE_OPERATORS_FOR_FLAGS(KDbCursor::Options) + #endif diff --git a/src/drivers/mysql/MysqlConnection.cpp b/src/drivers/mysql/MysqlConnection.cpp index 07fe71af..2348ec22 100644 --- a/src/drivers/mysql/MysqlConnection.cpp +++ b/src/drivers/mysql/MysqlConnection.cpp @@ -1,211 +1,211 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Joseph Wenninger Copyright (C) 2004-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "MysqlConnection.h" #include "MysqlDriver.h" #include "MysqlCursor.h" #include "MysqlPreparedStatement.h" #include "mysql_debug.h" #include "KDbConnectionData.h" #include "KDbVersionInfo.h" #include MysqlConnection::MysqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options) : KDbConnection(driver, connData, options) , d(new MysqlConnectionInternal(this)) { } MysqlConnection::~MysqlConnection() { destroy(); delete d; } bool MysqlConnection::drv_connect() { const bool ok = d->db_connect(data()); if (!ok) { storeResult(); //store error msg, if any - can be destroyed after disconnect() d->db_disconnect(); return false; } // Get lower_case_table_name value so we know if there's case sensitivity supported // See http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html int intLowerCaseTableNames = 0; tristate res = querySingleNumber(KDbEscapedString("SHOW VARIABLES LIKE 'lower_case_table_name'"), &intLowerCaseTableNames, 0/*col*/, false/* !addLimitTo1 */); if (res == false) // sanity return false; d->lowerCaseTableNames = intLowerCaseTableNames > 0; return true; } bool MysqlConnection::drv_getServerVersion(KDbServerVersionInfo* version) { // http://dev.mysql.com/doc/refman/5.1/en/mysql-get-server-info.html version->setString(QLatin1String(mysql_get_server_info(d->mysql))); // get the version info using 'version' built-in variable: //! @todo this is hardcoded for now; define api for retrieving variables and use this API... // http://dev.mysql.com/doc/refman/5.1/en/mysql-get-server-version.html QString versionString; tristate res = querySingleString(KDbEscapedString("SELECT @@version"), &versionString, /*column*/0, false /*!addLimitTo1*/); QRegularExpression versionRe(QLatin1String("^(\\d+)\\.(\\d+)\\.(\\d+)$")); QRegularExpressionMatch match = versionRe.match(versionString); if (res == false) // sanity return false; if (match.hasMatch()) { // (if querySingleString failed, the version will be 0.0.0... version->setMajor(match.captured(1).toInt()); version->setMinor(match.captured(2).toInt()); version->setRelease(match.captured(3).toInt()); } return true; } bool MysqlConnection::drv_disconnect() { return d->db_disconnect(); } -KDbCursor* MysqlConnection::prepareQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* MysqlConnection::prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options) { - return new MysqlCursor(this, sql, cursor_options); + return new MysqlCursor(this, sql, options); } -KDbCursor* MysqlConnection::prepareQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* MysqlConnection::prepareQuery(KDbQuerySchema* query, KDbCursor::Options options) { - return new MysqlCursor(this, query, cursor_options); + return new MysqlCursor(this, query, options); } bool MysqlConnection::drv_getDatabasesList(QStringList* list) { mysqlDebug(); list->clear(); MYSQL_RES *res = mysql_list_dbs(d->mysql, 0); if (res != 0) { MYSQL_ROW row; while ((row = mysql_fetch_row(res)) != 0) { *list << QString::fromUtf8(row[0]); } mysql_free_result(res); return true; } storeResult(); return false; } bool MysqlConnection::drv_databaseExists(const QString &dbName, bool ignoreErrors) { /* db names can be lower case in mysql */ const QString storedDbName(d->lowerCaseTableNames ? dbName.toLower() : dbName); const tristate result = resultExists( KDbEscapedString("SHOW DATABASES LIKE %1").arg(escapeString(storedDbName))); if (result == true) { return true; } if (!ignoreErrors) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("The database \"%1\" does not exist.").arg(storedDbName)); } return false; } bool MysqlConnection::drv_createDatabase(const QString &dbName) { const QString storedDbName(d->lowerCaseTableNames ? dbName.toLower() : dbName); mysqlDebug() << storedDbName; // mysql_create_db deprecated, use SQL here. // db names are lower case in mysql return drv_executeVoidSQL(KDbEscapedString("CREATE DATABASE %1").arg(escapeIdentifier(storedDbName))); } bool MysqlConnection::drv_useDatabase(const QString &dbName, bool *cancelled, KDbMessageHandler* msgHandler) { Q_UNUSED(cancelled); Q_UNUSED(msgHandler); //! @todo is here escaping needed? const QString storedDbName(d->lowerCaseTableNames ? dbName.toLower() : dbName); if (!d->useDatabase(storedDbName)) { storeResult(); return false; } return true; } bool MysqlConnection::drv_closeDatabase() { //! @todo free resources, as far as I know, mysql doesn't support that return true; } bool MysqlConnection::drv_dropDatabase(const QString &dbName) { //! @todo is here escaping needed? const QString storedDbName(d->lowerCaseTableNames ? dbName.toLower() : dbName); return drv_executeVoidSQL(KDbEscapedString("DROP DATABASE %1").arg(escapeIdentifier(storedDbName))); } KDbSqlResult* MysqlConnection::drv_executeSQL(const KDbEscapedString& sql) { if (!drv_executeVoidSQL(sql)) { return nullptr; } MYSQL_RES *data = mysql_use_result(d->mysql); // more optimal than mysql_store_result //! @todo use mysql_error() return new MysqlSqlResult(this, data); } bool MysqlConnection::drv_executeVoidSQL(const KDbEscapedString& sql) { if (!d->executeVoidSQL(sql)) { storeResult(); return false; } return true; } QString MysqlConnection::serverResultName() const { return MysqlConnectionInternal::serverResultName(d->mysql); } tristate MysqlConnection::drv_containsTable(const QString& tableName) { return resultExists(KDbEscapedString("SHOW TABLES LIKE %1") .arg(escapeString(tableName))); } KDbPreparedStatementInterface* MysqlConnection::prepareStatementInternal() { return new MysqlPreparedStatement(d); } void MysqlConnection::storeResult() { d->storeResult(&m_result); } diff --git a/src/drivers/mysql/MysqlConnection.h b/src/drivers/mysql/MysqlConnection.h index 25bae4e5..86cc04c5 100644 --- a/src/drivers/mysql/MysqlConnection.h +++ b/src/drivers/mysql/MysqlConnection.h @@ -1,80 +1,82 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Joseph Wenninger Copyright (C) 2004-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_MYSQLCONNECTION_H #define KDB_MYSQLCONNECTION_H #include #include "KDbConnection.h" class MysqlConnectionInternal; /*! @short Provides database connection, allowing queries and data modification. */ class MysqlConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(MysqlConnection) public: virtual ~MysqlConnection(); - KDbCursor* prepareQuery(const KDbEscapedString& sql, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; - KDbCursor* prepareQuery(KDbQuerySchema* query, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(const KDbEscapedString& sql, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; KDbPreparedStatementInterface* prepareStatementInternal() Q_DECL_OVERRIDE Q_REQUIRED_RESULT; protected: /*! Used by driver */ MysqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); virtual bool drv_connect(); virtual bool drv_getServerVersion(KDbServerVersionInfo* version); virtual bool drv_disconnect(); virtual bool drv_getDatabasesList(QStringList* list); //! reimplemented using "SHOW DATABASES LIKE..." because MySQL stores db names in lower case. virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true); virtual bool drv_createDatabase(const QString &dbName = QString()); virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = 0, KDbMessageHandler* msgHandler = 0); virtual bool drv_closeDatabase(); virtual bool drv_dropDatabase(const QString &dbName = QString()); virtual KDbSqlResult* drv_executeSQL(const KDbEscapedString& sql) Q_REQUIRED_RESULT; virtual bool drv_executeVoidSQL(const KDbEscapedString& sql); //! Implemented for KDbResultable virtual QString serverResultName() const; //! @todo move this somewhere to low level class (MIGRATION?) virtual tristate drv_containsTable(const QString &tableName); void storeResult(); MysqlConnectionInternal* const d; friend class MysqlDriver; friend class MysqlCursorData; friend class MysqlSqlResult; private: Q_DISABLE_COPY(MysqlConnection) }; #endif diff --git a/src/drivers/mysql/MysqlCursor.cpp b/src/drivers/mysql/MysqlCursor.cpp index 069e7a32..af6d4091 100644 --- a/src/drivers/mysql/MysqlCursor.cpp +++ b/src/drivers/mysql/MysqlCursor.cpp @@ -1,182 +1,181 @@ /* This file is part of the KDE project Copyright (C) 2003 Joseph Wenninger Copyright (C) 2005-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "MysqlCursor.h" #include "MysqlConnection.h" #include "MysqlConnection_p.h" #include "KDbError.h" #include "KDb.h" #include "KDbRecordData.h" #include #define BOOL bool -MysqlCursor::MysqlCursor(KDbConnection* conn, const KDbEscapedString& sql, int cursor_options) - : KDbCursor(conn, sql, cursor_options) +MysqlCursor::MysqlCursor(KDbConnection* conn, const KDbEscapedString& sql, + KDbCursor::Options options) + : KDbCursor(conn, sql, options | KDbCursor::Option::Buffered) , d(new MysqlCursorData(conn)) { - m_options |= Buffered; } -MysqlCursor::MysqlCursor(KDbConnection* conn, KDbQuerySchema* query, int options) - : KDbCursor(conn, query, options) +MysqlCursor::MysqlCursor(KDbConnection* conn, KDbQuerySchema* query, KDbCursor::Options options) + : KDbCursor(conn, query, options | KDbCursor::Option::Buffered) , d(new MysqlCursorData(conn)) { - m_options |= Buffered; } MysqlCursor::~MysqlCursor() { close(); delete d; } bool MysqlCursor::drv_open(const KDbEscapedString& sql) { if (mysql_real_query(d->mysql, sql.constData(), sql.length()) == 0) { if (mysql_errno(d->mysql) == 0) { //! @todo Add option somewhere so we can use more optimal mysql_num_rows(). //! In this case mysql_num_rows() does not work however. d->mysqlres = mysql_store_result(d->mysql); m_fieldCount = mysql_num_fields(d->mysqlres); m_fieldsToStoreInRecord = m_fieldCount; d->numRows = mysql_num_rows(d->mysqlres); m_records_in_buf = d->numRows; m_buffering_completed = true; return true; } } storeResult(); return false; } bool MysqlCursor::drv_close() { mysql_free_result(d->mysqlres); d->mysqlres = 0; d->mysqlrow = 0; d->lengths = 0; d->numRows = 0; return true; } void MysqlCursor::drv_getNextRecord() { if (at() >= d->numRows) { m_fetchResult = FetchEnd; } else if (at() < 0) { // control will reach here only when at() < 0 ( which is usually -1 ) // -1 is same as "1 beyond the End" m_fetchResult = FetchEnd; } else { // 0 <= at() < d->numRows d->lengths = mysql_fetch_lengths(d->mysqlres); m_fetchResult = FetchOK; } } // This isn't going to work right now as it uses d->mysqlrow QVariant MysqlCursor::value(int pos) { if (!d->mysqlrow || pos >= m_fieldCount || d->mysqlrow[pos] == 0) return QVariant(); KDbField *f = (m_visibleFieldsExpanded && pos < m_visibleFieldsExpanded->count()) ? m_visibleFieldsExpanded->at(pos)->field() : nullptr; //! @todo js: use MYSQL_FIELD::type here! bool ok; return KDb::cstringToVariant(d->mysqlrow[pos], f ? f->type() : KDbField::Text, &ok, d->lengths[pos]); } /* As with sqlite, the DB library returns all values (including numbers) as strings. So just put that string in a QVariant and let KDb deal with it. */ bool MysqlCursor::drv_storeCurrentRecord(KDbRecordData* data) const { // mysqlDebug() << "position is " << (long)m_at; if (d->numRows == 0) return false; if (!m_visibleFieldsExpanded) {//simple version: without types for (int i = 0; i < m_fieldCount; ++i) { (*data)[i] = QString::fromUtf8(d->mysqlrow[i], d->lengths[i]); } return true; } for (int i = 0; i < m_fieldCount; ++i) { KDbField *f = m_visibleFieldsExpanded->at(i)->field(); bool ok; (*data)[i] = KDb::cstringToVariant(d->mysqlrow[i], f ? f->type() : KDbField::Text, &ok, d->lengths[i]); if (!ok) { return false; } } return true; } void MysqlCursor::drv_appendCurrentRecordToBuffer() { } void MysqlCursor::drv_bufferMovePointerNext() { d->mysqlrow = mysql_fetch_row(d->mysqlres); d->lengths = mysql_fetch_lengths(d->mysqlres); } void MysqlCursor::drv_bufferMovePointerPrev() { mysql_data_seek(d->mysqlres, m_at - 1); d->mysqlrow = mysql_fetch_row(d->mysqlres); d->lengths = mysql_fetch_lengths(d->mysqlres); } void MysqlCursor::drv_bufferMovePointerTo(qint64 to) { mysql_data_seek(d->mysqlres, to); d->mysqlrow = mysql_fetch_row(d->mysqlres); d->lengths = mysql_fetch_lengths(d->mysqlres); } const char** MysqlCursor::recordData() const { //! @todo return 0; } QString MysqlCursor::serverResultName() const { return MysqlConnectionInternal::serverResultName(d->mysql); } void MysqlCursor::storeResult() { d->storeResult(&m_result); } diff --git a/src/drivers/mysql/MysqlCursor.h b/src/drivers/mysql/MysqlCursor.h index fc3d6741..ab8c5417 100644 --- a/src/drivers/mysql/MysqlCursor.h +++ b/src/drivers/mysql/MysqlCursor.h @@ -1,57 +1,58 @@ /* This file is part of the KDE project Copyright (C) 2003 Joseph Wenninger Copyright (C) 2005-2010 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_MYSQLCURSOR_H #define KDB_MYSQLCURSOR_H #include "KDbCursor.h" class KDbConnection; class MysqlCursorData; class MysqlCursor: public KDbCursor { public: MysqlCursor(KDbConnection* conn, const KDbEscapedString& sql, - int cursor_options = NoOptions); - MysqlCursor(KDbConnection* conn, KDbQuerySchema* query, int options = NoOptions); + KDbCursor::Options options = KDbCursor::Option::None); + MysqlCursor(KDbConnection* conn, KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None); virtual ~MysqlCursor(); virtual QVariant value(int pos); virtual const char** recordData() const; virtual bool drv_storeCurrentRecord(KDbRecordData* data) const; virtual bool drv_open(const KDbEscapedString& sql); virtual bool drv_close(); virtual void drv_getNextRecord(); virtual void drv_appendCurrentRecordToBuffer(); virtual void drv_bufferMovePointerNext(); virtual void drv_bufferMovePointerPrev(); virtual void drv_bufferMovePointerTo(qint64 to); //! Implemented for KDbResultable virtual QString serverResultName() const; private: void storeResult(); MysqlCursorData * const d; Q_DISABLE_COPY(MysqlCursor) }; #endif diff --git a/src/drivers/postgresql/PostgresqlConnection.cpp b/src/drivers/postgresql/PostgresqlConnection.cpp index 29dbbd65..873591c3 100644 --- a/src/drivers/postgresql/PostgresqlConnection.cpp +++ b/src/drivers/postgresql/PostgresqlConnection.cpp @@ -1,298 +1,296 @@ /* This file is part of the KDE project Copyright (C) 2003 Adam Pigg Copyright (C) 2010-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "PostgresqlConnection.h" #include "PostgresqlConnection_p.h" #include "PostgresqlPreparedStatement.h" #include "PostgresqlCursor.h" #include "postgresql_debug.h" #include "KDbConnectionData.h" #include "KDbError.h" #include "KDbGlobal.h" #include "KDbVersionInfo.h" #include #include #define MIN_SERVER_VERSION_MAJOR 7 #define MIN_SERVER_VERSION_MINOR 1 inline static QByteArray parameter(PGconn *conn, const char *paramName) { return PQparameterStatus(conn, paramName); } PostgresqlTransactionData::PostgresqlTransactionData(KDbConnection *conn) : KDbTransactionData(conn) { } PostgresqlTransactionData::~PostgresqlTransactionData() { } //================================================================================== PostgresqlConnection::PostgresqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options) : KDbConnection(driver, connData, options) , d(new PostgresqlConnectionInternal(this)) { } PostgresqlConnection::~PostgresqlConnection() { //delete m_trans; destroy(); delete d; } -KDbCursor* PostgresqlConnection::prepareQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* PostgresqlConnection::prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options) { - Q_UNUSED(cursor_options); - return new PostgresqlCursor(this, sql, 1); //Always used buffered cursor + return new PostgresqlCursor(this, sql, options); } -KDbCursor* PostgresqlConnection::prepareQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* PostgresqlConnection::prepareQuery(KDbQuerySchema* query, KDbCursor::Options options) { - Q_UNUSED(cursor_options); - return new PostgresqlCursor(this, query, 1);//Always used buffered cursor + return new PostgresqlCursor(this, query, options); } bool PostgresqlConnection::drv_connect() { return true; } bool PostgresqlConnection::drv_getServerVersion(KDbServerVersionInfo* version) { // http://www.postgresql.org/docs/8.4/static/libpq-status.html //postgresqlDebug() << "server_version:" << d->parameter("server_version"); version->setString(QString::fromLatin1(parameter(d->conn, "server_version"))); const int versionNumber = PQserverVersion(d->conn); if (versionNumber > 0) { version->setMajor(versionNumber / 10000); version->setMinor((versionNumber % 1000) / 100); version->setRelease(versionNumber % 100); } if ( version->major() < MIN_SERVER_VERSION_MAJOR || (version->major() == MIN_SERVER_VERSION_MAJOR && version->minor() < MIN_SERVER_VERSION_MINOR)) { postgresqlWarning() << QString::fromLatin1("PostgreSQL %d.%d is not supported and may not work. The minimum is %d.%d") .arg(version->major()).arg(version->minor()).arg(MIN_SERVER_VERSION_MAJOR).arg(MIN_SERVER_VERSION_MINOR); } return true; } bool PostgresqlConnection::drv_disconnect() { return true; } bool PostgresqlConnection::drv_getDatabasesList(QStringList* list) { return queryStringList(KDbEscapedString("SELECT datname FROM pg_database WHERE datallowconn = TRUE"), list); } bool PostgresqlConnection::drv_createDatabase(const QString &dbName) { return executeVoidSQL(KDbEscapedString("CREATE DATABASE ") + escapeIdentifier(dbName)); } QByteArray buildConnParameter(const QByteArray& key, const QVariant& value) { QByteArray result = key; //! @todo optimize result.replace('\\', "\\\\").replace('\'', "\\'"); return key + "='" + value.toString().toUtf8() + "' "; } bool PostgresqlConnection::drv_useDatabase(const QString &dbName, bool *cancelled, KDbMessageHandler* msgHandler) { Q_UNUSED(cancelled); Q_UNUSED(msgHandler); QByteArray conninfo; if (data().hostName().isEmpty() || 0 == QString::compare(data().hostName(), QLatin1String("localhost"), Qt::CaseInsensitive)) { if (!data().localSocketFileName().isEmpty()) { QFileInfo fileInfo(data().localSocketFileName()); if (fileInfo.exists()) { conninfo += buildConnParameter("host", fileInfo.absolutePath()); } } } else { const QHostAddress ip(data().hostName()); if (ip.isNull()) { conninfo += buildConnParameter("host", data().hostName()); } else { conninfo += buildConnParameter("hostaddr", ip.toString()); } } //Build up the connection string if (data().port() > 0) conninfo += buildConnParameter("port", data().port()); QString myDbName = dbName; if (myDbName.isEmpty()) myDbName = data().databaseName(); if (!myDbName.isEmpty()) conninfo += buildConnParameter("dbname", myDbName); if (!data().userName().isEmpty()) conninfo += buildConnParameter("user", data().userName()); if (!data().password().isEmpty()) conninfo += buildConnParameter("password", data().password()); //postgresqlDebug() << conninfo; //! @todo other parameters: connect_timeout, options, options, sslmode, sslcert, sslkey, sslrootcert, sslcrl, krbsrvname, gsslib, service // http://www.postgresql.org/docs/8.4/interactive/libpq-connect.html d->conn = PQconnectdb(conninfo.constData()); if (!d->connectionOK()) { PQfinish(d->conn); d->conn = 0; return false; } // pgsql 8.1 changed the default to no oids but we need them PGresult* result = PQexec(d->conn, "SET DEFAULT_WITH_OIDS TO ON"); int status = PQresultStatus(result); PQclear(result); // initialize encoding result = PQexec(d->conn, "SET CLIENT_ENCODING TO 'UNICODE'"); status = PQresultStatus(result); PQclear(result); d->unicode = status == PGRES_COMMAND_OK; result = PQexec(d->conn, "SET DATESTYLE TO 'ISO'"); status = PQresultStatus(result); if (status != PGRES_COMMAND_OK) { postgresqlWarning() << "Failed to set DATESTYLE to 'ISO':" << PQerrorMessage(d->conn); } //! @todo call on first use of SOUNDEX(), etc.; //! it's not possible now because we don't have connection context in KDbFunctionExpressionData if (!d->fuzzystrmatchExtensionCreated) { d->fuzzystrmatchExtensionCreated = drv_executeVoidSQL(KDbEscapedString("CREATE EXTENSION IF NOT EXISTS fuzzystrmatch")); } PQclear(result); return true; } bool PostgresqlConnection::drv_closeDatabase() { PQfinish(d->conn); d->conn = 0; return true; } bool PostgresqlConnection::drv_dropDatabase(const QString &dbName) { //postgresqlDebug() << dbName; //! @todo Maybe should check that dbname is no the currentdb if (executeVoidSQL(KDbEscapedString("DROP DATABASE ") + escapeIdentifier(dbName))) return true; return false; } KDbSqlResult* PostgresqlConnection::drv_executeSQL(const KDbEscapedString& sql) { PGresult* result = d->executeSQL(sql); const ExecStatusType status = PQresultStatus(result); if (status == PGRES_TUPLES_OK || status == PGRES_COMMAND_OK) { return new PostgresqlSqlResult(this, result, status); } storeResult(result, status); return nullptr; } bool PostgresqlConnection::drv_executeVoidSQL(const KDbEscapedString& sql) { PGresult* result = d->executeSQL(sql); const ExecStatusType status = PQresultStatus(result); d->storeResultAndClear(&m_result, &result, status); return status == PGRES_TUPLES_OK || status == PGRES_COMMAND_OK; } bool PostgresqlConnection::drv_isDatabaseUsed() const { return d->conn; } tristate PostgresqlConnection::drv_containsTable(const QString &tableName) { return resultExists(KDbEscapedString("SELECT 1 FROM pg_class WHERE relkind='r' AND relname LIKE %1") .arg(escapeString(tableName))); } QString PostgresqlConnection::serverResultName() const { if (m_result.code() >= 0 && m_result.code() <= PGRES_SINGLE_TUPLE) { return QString::fromLatin1(PQresStatus(ExecStatusType(m_result.code()))); } return QString(); } KDbPreparedStatementInterface* PostgresqlConnection::prepareStatementInternal() { return new PostgresqlPreparedStatement(d); } KDbEscapedString PostgresqlConnection::escapeString(const QByteArray& str) const { int error; d->escapingBuffer.resize(str.length() * 2 + 1); size_t count = PQescapeStringConn(d->conn, d->escapingBuffer.data(), str.constData(), str.length(), &error); d->escapingBuffer.resize(count); if (error != 0) { d->storeResult(const_cast(&m_result)); const_cast(m_result) = KDbResult(ERR_INVALID_ENCODING, PostgresqlConnection::tr("Escaping string failed. Invalid multibyte encoding.")); return KDbEscapedString(); } return KDbEscapedString("\'") + d->escapingBuffer + '\''; } KDbEscapedString PostgresqlConnection::escapeString(const QString& str) const { return escapeString(d->unicode ? str.toUtf8() : str.toLocal8Bit()); } void PostgresqlConnection::storeResult(PGresult *pgResult, ExecStatusType execStatus) { d->storeResultAndClear(&m_result, &pgResult, execStatus); } diff --git a/src/drivers/postgresql/PostgresqlConnection.h b/src/drivers/postgresql/PostgresqlConnection.h index bbe34503..e2fb468b 100644 --- a/src/drivers/postgresql/PostgresqlConnection.h +++ b/src/drivers/postgresql/PostgresqlConnection.h @@ -1,103 +1,105 @@ /* This file is part of the KDE project Copyright (C) 2003 Adam Pigg Copyright (C) 2010-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_POSTGRESQLCONNECTION_H #define KDB_POSTGRESQLCONNECTION_H #include "KDbConnection.h" #include class PostgresqlConnectionInternal; //! @internal class PostgresqlTransactionData : public KDbTransactionData { public: explicit PostgresqlTransactionData(KDbConnection *conn); ~PostgresqlTransactionData(); private: Q_DISABLE_COPY(PostgresqlTransactionData) }; class PostgresqlConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(PostgresqlConnection) public: virtual ~PostgresqlConnection(); //! @return a new query based on a query statement - KDbCursor* prepareQuery(const KDbEscapedString& sql, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(const KDbEscapedString& sql, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; //! @return a new query based on a query object - KDbCursor* prepareQuery(KDbQuerySchema* query, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; KDbPreparedStatementInterface* prepareStatementInternal() Q_DECL_OVERRIDE Q_REQUIRED_RESULT; /*! Connection-specific string escaping. */ virtual KDbEscapedString escapeString(const QString& str) const; virtual KDbEscapedString escapeString(const QByteArray& str) const; private: /*! Used by driver */ PostgresqlConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); //! @return true if currently connected to a database, ignoring the m_is_connected flag. virtual bool drv_isDatabaseUsed() const; //! Noop: we tell we are connected, but we wont actually connect until we use a database. virtual bool drv_connect(); virtual bool drv_getServerVersion(KDbServerVersionInfo* version); //! Noop: we tell we have disconnected, but it is actually handled by closeDatabase. virtual bool drv_disconnect(); //! @return a list of database names virtual bool drv_getDatabasesList(QStringList* list); //! Create a new database virtual bool drv_createDatabase(const QString &dbName = QString()); //! Uses database. Note that if data().localSocketFileName() is not empty, //! only directory path is used for connecting; the local socket's filename stays ".s.PGSQL.5432". virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = 0, KDbMessageHandler* msgHandler = 0); //! Close the database connection virtual bool drv_closeDatabase(); //! Drops the given database virtual bool drv_dropDatabase(const QString &dbName = QString()); //! Executes an SQL statement KDbSqlResult* drv_executeSQL(const KDbEscapedString& sql) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; bool drv_executeVoidSQL(const KDbEscapedString& sql) Q_DECL_OVERRIDE; //! Implemented for KDbResultable virtual QString serverResultName() const; //! @todo move this somewhere to low level class (MIGRATION?) virtual tristate drv_containsTable(const QString &tableName); void storeResult(PGresult *pgResult, ExecStatusType execStatus); PostgresqlConnectionInternal * const d; friend class PostgresqlDriver; friend class PostgresqlCursorData; friend class PostgresqlTransactionData; friend class PostgresqlSqlResult; Q_DISABLE_COPY(PostgresqlConnection) }; #endif diff --git a/src/drivers/postgresql/PostgresqlCursor.cpp b/src/drivers/postgresql/PostgresqlCursor.cpp index 2fa13dec..10f161c5 100644 --- a/src/drivers/postgresql/PostgresqlCursor.cpp +++ b/src/drivers/postgresql/PostgresqlCursor.cpp @@ -1,353 +1,353 @@ /* This file is part of the KDE project Copyright (C) 2003 Adam Pigg Copyright (C) 2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "PostgresqlCursor.h" #include "PostgresqlConnection.h" #include "PostgresqlConnection_p.h" #include "PostgresqlDriver.h" #include "postgresql_debug.h" #include "KDbError.h" #include "KDbGlobal.h" #include "KDbRecordData.h" // Constructor based on query statement -PostgresqlCursor::PostgresqlCursor(KDbConnection* conn, const KDbEscapedString& sql, int options) - : KDbCursor(conn, sql, options) +PostgresqlCursor::PostgresqlCursor(KDbConnection* conn, const KDbEscapedString& sql, + KDbCursor::Options options) + : KDbCursor(conn, sql, options | KDbCursor::Option::Buffered) , m_numRows(0) , d(new PostgresqlCursorData(conn)) { - m_options |= Buffered; } //================================================================================== //Constructor base on query object -PostgresqlCursor::PostgresqlCursor(KDbConnection* conn, KDbQuerySchema* query, int options) - : KDbCursor(conn, query, options) +PostgresqlCursor::PostgresqlCursor(KDbConnection* conn, KDbQuerySchema* query, + KDbCursor::Options options) + : KDbCursor(conn, query, options | KDbCursor::Option::Buffered) , m_numRows(0) , d(new PostgresqlCursorData(conn)) { - m_options |= Buffered; } //================================================================================== //Destructor PostgresqlCursor::~PostgresqlCursor() { close(); delete d; } //================================================================================== //Create a cursor result set bool PostgresqlCursor::drv_open(const KDbEscapedString& sql) { d->res = d->executeSQL(sql); d->resultStatus = PQresultStatus(d->res); if (d->resultStatus != PGRES_TUPLES_OK && d->resultStatus != PGRES_COMMAND_OK) { storeResultAndClear(&d->res, d->resultStatus); return false; } m_fieldsToStoreInRecord = PQnfields(d->res); m_fieldCount = m_fieldsToStoreInRecord - (containsRecordIdInfo() ? 1 : 0); m_numRows = PQntuples(d->res); m_records_in_buf = m_numRows; m_buffering_completed = true; // get real types for all fields PostgresqlDriver* drv = static_cast(connection()->driver()); m_realTypes.resize(m_fieldsToStoreInRecord); m_realLengths.resize(m_fieldsToStoreInRecord); for (int i = 0; i < int(m_fieldsToStoreInRecord); i++) { const int pqtype = PQftype(d->res, i); const int pqfmod = PQfmod(d->res, i); m_realTypes[i] = drv->pgsqlToKDbType(pqtype, pqfmod, &m_realLengths[i]); } return true; } //================================================================================== //Delete objects bool PostgresqlCursor::drv_close() { PQclear(d->res); return true; } //================================================================================== //Gets the next record...does not need to do much, just return fetchend if at end of result set void PostgresqlCursor::drv_getNextRecord() { if (at() >= qint64(m_numRows)) { m_fetchResult = FetchEnd; } else if (at() < 0) { // control will reach here only when at() < 0 ( which is usually -1 ) // -1 is same as "1 beyond the End" m_fetchResult = FetchEnd; } else { // 0 <= at() < m_numRows m_fetchResult = FetchOK; } } //================================================================================== //Check the current position is within boundaries #if 0 void PostgresqlCursor::drv_getPrevRecord() { if (at() < m_res->size() && at() >= 0) { m_fetchResult = FetchOK; } else if (at() >= m_res->size()) { m_fetchResult = FetchEnd; } else { m_fetchResult = FetchError; } } #endif //================================================================================== //Return the value for a given column for the current record QVariant PostgresqlCursor::value(int pos) { if (pos < m_fieldCount) return pValue(pos); else return QVariant(); } #if 0 inline QVariant pgsqlCStrToVariant(const pqxx::result::field& r) { switch (r.type()) { case BOOLOID: return QString::fromLatin1(r.c_str(), r.size()) == "true"; //!< @todo check formatting case INT2OID: case INT4OID: case INT8OID: return r.as(int()); case FLOAT4OID: case FLOAT8OID: case NUMERICOID: return r.as(double()); case DATEOID: return QString::fromUtf8(r.c_str(), r.size()); //!< @todo check formatting case TIMEOID: return QString::fromUtf8(r.c_str(), r.size()); //!< @todo check formatting case TIMESTAMPOID: return QString::fromUtf8(r.c_str(), r.size()); //!< @todo check formatting case BYTEAOID: return KDb::pgsqlByteaToByteArray(r.c_str(), r.size()); case BPCHAROID: case VARCHAROID: case TEXTOID: return QString::fromUtf8(r.c_str(), r.size()); //utf8? default: return QString::fromUtf8(r.c_str(), r.size()); //utf8? } } #endif static inline bool hasTimeZone(const QString& s) { return s.at(s.length() - 3) == QLatin1Char('+') || s.at(s.length() - 3) == QLatin1Char('-'); } static inline QVariant convertToKDbType(bool convert, const QVariant &value, KDbField::Type kdbType) { return (convert && kdbType != KDbField::InvalidType) ? KDbField::convertToType(value, kdbType) : value; } static inline QTime timeFromData(const char *data, int len) { if (len == 0) { return QTime(); } QString s(QString::fromLatin1(data, len)); if (hasTimeZone(s)) { s.chop(3); // skip timezone return QTime::fromString(s, Qt::ISODate); } return QTime::fromString(s, Qt::ISODate); } static inline QDateTime dateTimeFromData(const char *data, int len) { if (len < 10 /*ISO Date*/) { return QDateTime(); } QString s(QString::fromLatin1(data, len)); if (hasTimeZone(s)) { s.chop(3); // skip timezone if (s.isEmpty()) { return QDateTime(); } } if (s.at(s.length() - 3).isPunct()) { // fix ms, should be three digits s += QLatin1Char('0'); } return QDateTime::fromString(s, Qt::ISODate); } static inline QByteArray byteArrayFromData(const char *data) { size_t unescapedLen; unsigned char *unescapedData = PQunescapeBytea((const unsigned char*)data, &unescapedLen); const QByteArray result((const char*)unescapedData, unescapedLen); //! @todo avoid deep copy; QByteArray does not allow passing ownership of data; maybe copy PQunescapeBytea code? PQfreemem(unescapedData); return result; } //================================================================================== //Return the value for a given column for the current record - Private const version QVariant PostgresqlCursor::pValue(int pos) const { // postgresqlWarning() << "PostgresqlCursor::value - ERROR: requested position is greater than the number of fields"; const qint64 row = at(); KDbField *f = (m_visibleFieldsExpanded && pos < qMin(m_visibleFieldsExpanded->count(), m_fieldCount)) ? m_visibleFieldsExpanded->at(pos)->field() : nullptr; // postgresqlDebug() << "pos:" << pos; const KDbField::Type type = m_realTypes[pos]; const KDbField::Type kdbType = f ? f->type() : KDbField::InvalidType; // cache: evaluating type of expressions can be expensive if (PQgetisnull(d->res, row, pos) || kdbType == KDbField::Null) { return QVariant(); } const char *data = PQgetvalue(d->res, row, pos); int len = PQgetlength(d->res, row, pos); switch (type) { // from most to least frequently used types: case KDbField::Text: case KDbField::LongText: { const int maxLength = m_realLengths[pos]; if (maxLength > 0) { len = qMin(len, maxLength); } return convertToKDbType(!KDbField::isTextType(kdbType), d->unicode ? QString::fromUtf8(data, len) : QString::fromLatin1(data, len), kdbType); } case KDbField::Integer: return convertToKDbType(!KDbField::isIntegerType(kdbType), atoi(data), // the fastest way kdbType); case KDbField::Boolean: return convertToKDbType(kdbType != KDbField::Boolean, bool(data[0] == 't'), kdbType); case KDbField::BigInteger: return convertToKDbType(kdbType != KDbField::BigInteger, (data[0] == '-') ? QByteArray::fromRawData(data, len).toLongLong() : QByteArray::fromRawData(data, len).toULongLong(), kdbType); case KDbField::Double: //! @todo support equivalent of QSql::NumericalPrecisionPolicy, especially for NUMERICOID return convertToKDbType(!KDbField::isFPNumericType(kdbType), QByteArray::fromRawData(data, len).toDouble(), kdbType); case KDbField::Date: return convertToKDbType(kdbType != KDbField::Date, (len == 0) ? QVariant(QDate()) : QVariant(QDate::fromString(QLatin1String(QByteArray::fromRawData(data, len)), Qt::ISODate)), kdbType); case KDbField::Time: return convertToKDbType(kdbType != KDbField::Time, timeFromData(data, len), kdbType); case KDbField::DateTime: return convertToKDbType(kdbType != KDbField::DateTime, dateTimeFromData(data, len), kdbType); case KDbField::BLOB: return convertToKDbType(kdbType != KDbField::BLOB, byteArrayFromData(data), kdbType); default: postgresqlWarning() << "PostgresqlCursor::pValue() data type?"; } return QVariant(); } //================================================================================== //Return the current record as a char** const char** PostgresqlCursor::recordData() const { //! @todo return 0; } //================================================================================== //Store the current record in [data] bool PostgresqlCursor::drv_storeCurrentRecord(KDbRecordData* data) const { // postgresqlDebug() << "POSITION IS" << (long)m_at; for (int i = 0; i < m_fieldsToStoreInRecord; i++) (*data)[i] = pValue(i); return true; } //================================================================================== // /*void PostgresqlCursor::drv_clearServerResult() { //! @todo PostgresqlCursor: stuff with server results }*/ //================================================================================== //Add the current record to the internal buffer //Implementation required but no need in this driver //Result set is a buffer so do not need another void PostgresqlCursor::drv_appendCurrentRecordToBuffer() { } //================================================================================== //Move internal pointer to internal buffer +1 //Implementation required but no need in this driver void PostgresqlCursor::drv_bufferMovePointerNext() { } //================================================================================== //Move internal pointer to internal buffer -1 //Implementation required but no need in this driver void PostgresqlCursor::drv_bufferMovePointerPrev() { } //================================================================================== //Move internal pointer to internal buffer to N //Implementation required but no need in this driver void PostgresqlCursor::drv_bufferMovePointerTo(qint64 to) { Q_UNUSED(to); } void PostgresqlCursor::storeResultAndClear(PGresult **pgResult, ExecStatusType execStatus) { d->storeResultAndClear(&m_result, pgResult, execStatus); } diff --git a/src/drivers/postgresql/PostgresqlCursor.h b/src/drivers/postgresql/PostgresqlCursor.h index af03b695..74607e7b 100644 --- a/src/drivers/postgresql/PostgresqlCursor.h +++ b/src/drivers/postgresql/PostgresqlCursor.h @@ -1,64 +1,65 @@ /* This file is part of the KDE project Copyright (C) 2003 Adam Pigg Copyright (C) 2010 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_POSTGRESQLCURSOR_H #define KDB_POSTGRESQLCURSOR_H #include "KDbCursor.h" #include "KDbField.h" #include class KDbConnection; class PostgresqlCursorData; class PostgresqlCursor: public KDbCursor { public: explicit PostgresqlCursor(KDbConnection* conn, const KDbEscapedString& sql, - int options = NoOptions); - PostgresqlCursor(KDbConnection* conn, KDbQuerySchema* query, int options = NoOptions); + KDbCursor::Options options = KDbCursor::Option::None); + PostgresqlCursor(KDbConnection* conn, KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None); virtual ~PostgresqlCursor(); virtual QVariant value(int pos); virtual const char** recordData() const; virtual bool drv_storeCurrentRecord(KDbRecordData* data) const; virtual bool drv_open(const KDbEscapedString& sql); virtual bool drv_close(); virtual void drv_getNextRecord(); virtual void drv_appendCurrentRecordToBuffer(); virtual void drv_bufferMovePointerNext(); virtual void drv_bufferMovePointerPrev(); virtual void drv_bufferMovePointerTo(qint64 to); void storeResultAndClear(PGresult **pgResult, ExecStatusType execStatus); private: QVariant pValue(int pos)const; unsigned long m_numRows; QVector m_realTypes; QVector m_realLengths; PostgresqlCursorData * const d; Q_DISABLE_COPY(PostgresqlCursor) }; #endif diff --git a/src/drivers/sqlite/SqliteConnection.cpp b/src/drivers/sqlite/SqliteConnection.cpp index c87f191b..dcb515ee 100644 --- a/src/drivers/sqlite/SqliteConnection.cpp +++ b/src/drivers/sqlite/SqliteConnection.cpp @@ -1,412 +1,412 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "SqliteConnection.h" #include "SqliteConnection_p.h" #include "SqliteCursor.h" #include "SqlitePreparedStatement.h" #include "SqliteFunctions.h" #include "sqlite_debug.h" #include #include "KDbConnectionData.h" #include "KDbConnectionOptions.h" #include "KDbUtils.h" #include "KDbUtils_p.h" #include "KDbVersionInfo.h" #include #include #include SqliteConnection::SqliteConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options) : KDbConnection(driver, connData, options) , d(new SqliteConnectionInternal(this)) { QByteArray propertyName = "extraSqliteExtensionPaths"; KDbUtils::Property extraSqliteExtensionPathsProperty = this->options()->property(propertyName); if (extraSqliteExtensionPathsProperty.isNull()) { this->options()->insert(propertyName, QStringList()); } this->options()->setCaption(propertyName, SqliteConnection::tr("Extra paths for SQLite plugins")); } SqliteConnection::~SqliteConnection() { destroy(); delete d; } void SqliteConnection::storeResult() { d->storeResult(&m_result); } bool SqliteConnection::drv_connect() { return true; } bool SqliteConnection::drv_getServerVersion(KDbServerVersionInfo* version) { version->setString(QLatin1String(SQLITE_VERSION)); //defined in sqlite3.h QRegularExpression re(QLatin1String("^(\\d+)\\.(\\d+)\\.(\\d+)$")); QRegularExpressionMatch match = re.match(version->string()); if (match.hasMatch()) { version->setMajor(match.captured(1).toInt()); version->setMinor(match.captured(2).toInt()); version->setRelease(match.captured(3).toInt()); } return true; } bool SqliteConnection::drv_disconnect() { return true; } bool SqliteConnection::drv_getDatabasesList(QStringList* list) { //this is one-db-per-file database list->append(data().databaseName()); return true; } tristate SqliteConnection::drv_containsTable(const QString &tableName) { return resultExists(KDbEscapedString("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE %1") .arg(escapeString(tableName))); } #if 0 // TODO bool SqliteConnection::drv_getTablesList(QStringList* list) { KDbCursor *cursor; if (!(cursor = executeQuery(KDbEscapedString("SELECT name FROM sqlite_master WHERE type='table'")))) { sqliteWarning() << "!executeQuery()"; return false; } list->clear(); cursor->moveFirst(); while (!cursor->eof() && !cursor->result().isError()) { *list += cursor->value(0).toString(); cursor->moveNext(); } if (cursor->result().isError()) { deleteCursor(cursor); return false; } return deleteCursor(cursor); } #endif bool SqliteConnection::drv_createDatabase(const QString &dbName) { Q_UNUSED(dbName); return drv_useDatabaseInternal(0, 0, true/*create if missing*/); } bool SqliteConnection::drv_useDatabase(const QString &dbName, bool *cancelled, KDbMessageHandler* msgHandler) { Q_UNUSED(dbName); return drv_useDatabaseInternal(cancelled, msgHandler, false/*do not create if missing*/); } bool SqliteConnection::drv_useDatabaseInternal(bool *cancelled, KDbMessageHandler* msgHandler, bool createIfMissing) { //! @todo add option (command line or in kdbrc?) //! @todo int exclusiveFlag = KDbConnection::isReadOnly() ? SQLITE_OPEN_READONLY : SQLITE_OPEN_WRITE_LOCKED; // <-- shared read + (if !r/o): exclusive write int openFlags = 0; if (options()->isReadOnly()) { openFlags |= SQLITE_OPEN_READONLY; } else { openFlags |= SQLITE_OPEN_READWRITE; if (createIfMissing) { openFlags |= SQLITE_OPEN_CREATE; } } //! @todo add option // int allowReadonly = 1; // const bool wasReadOnly = KDbConnection::isReadOnly(); //sqliteDebug() << data().databaseName(); int res = sqlite3_open_v2( /* unicode expected since SQLite 3.1 */ QDir::toNativeSeparators(data().databaseName()).toUtf8().constData(), &d->data, openFlags, /*exclusiveFlag, allowReadonly *//* If 1 and locking fails, try opening in read-only mode */ 0 ); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); } storeResult(); if (!m_result.isError()) { // Set the secure-delete on, so SQLite overwrites deleted content with zeros. // The default setting is determined by the SQLITE_SECURE_DELETE compile-time option but we overwrite it here. // Works with 3.6.23. Earlier version just ignore this pragma. // See http://www.sqlite.org/pragma.html#pragma_secure_delete //! @todo add connection flags to the driver and global setting to control the "secure delete" pragma if (!drv_executeVoidSQL(KDbEscapedString("PRAGMA secure_delete = on"))) { drv_closeDatabaseSilently(); return false; } // Load ICU extension for unicode collations if (!findAndLoadExtension(QLatin1String("kdb_sqlite_icu"))) { drv_closeDatabaseSilently(); return false; } // load ROOT collation for use as default collation if (!drv_executeVoidSQL(KDbEscapedString("SELECT icu_load_collation('', '')"))) { drv_closeDatabaseSilently(); return false; } if (!createCustomSQLiteFunctions(d->data)) { drv_closeDatabaseSilently(); return false; } } //! @todo check exclusive status Q_UNUSED(cancelled); Q_UNUSED(msgHandler); //! @todo removed in kdb - reenable? /* if (d->res == SQLITE_OK && cancelled && !wasReadOnly && allowReadonly && isReadOnly()) { //opened as read only, ask if (KDbMessageHandler::Continue != askQuestion( KDbMessageHandler::WarningContinueCancel, futureTr("Do you want to open file \"%1\" as read-only?\n\n" "The file is probably already open on this or another computer. " "Could not gain exclusive access for writing the file.") .arg(QDir::fromNativeSeparators(data()->databaseName())), futureTr("Opening As Read-Only"), KDbMessageHandler::Continue, KDbMessageHandler::KDbGuiItem() .setProperty("text", futureTr("Open As Read-Only")) .setProperty("icon", "document-open"), KDbMessageHandler::KDbGuiItem(), "askBeforeOpeningFileReadOnly", KDbMessageHandler::Notify, msgHandler) { clearError(); if (!drv_closeDatabase()) return false; *cancelled = true; return false; } } if (d->res == SQLITE_CANTOPEN_WITH_LOCKED_READWRITE) { setError(ERR_ACCESS_RIGHTS, futureTr("The file is probably already open on this or another computer.\n\n" "Could not gain exclusive access for reading and writing the file. " "Check the file's permissions and whether it is already opened and locked by another application.")); } else if (d->res == SQLITE_CANTOPEN_WITH_LOCKED_WRITE) { setError(ERR_ACCESS_RIGHTS, futureTr("The file is probably already open on this or another computer.\n\n" "Could not gain exclusive access for writing the file. " "Check the file's permissions and whether it is already opened and locked by another application.")); }*/ return res == SQLITE_OK; } void SqliteConnection::drv_closeDatabaseSilently() { KDbResult result = this->result(); // save drv_closeDatabase(); m_result = result; } bool SqliteConnection::drv_closeDatabase() { if (!d->data) return false; const int res = sqlite3_close(d->data); if (SQLITE_OK == res) { d->data = 0; return true; } if (SQLITE_BUSY == res) { #if 0 //this is ANNOYING, needs fixing (by closing cursors or waiting) setError(ERR_CLOSE_FAILED, futureTr("Could not close busy database.")); #else return true; #endif } return false; } bool SqliteConnection::drv_dropDatabase(const QString &dbName) { Q_UNUSED(dbName); // Each database is one single SQLite file. const QString filename = data().databaseName(); if (QFile::exists(filename) && !QFile::remove(filename)) { m_result = KDbResult(ERR_ACCESS_RIGHTS, SqliteConnection::tr("Could not delete file \"%1\". " "Check the file's permissions and whether it is already " "opened and locked by another application.") .arg(QDir::fromNativeSeparators(filename))); return false; } return true; } -KDbCursor* SqliteConnection::prepareQuery(const KDbEscapedString& sql, int cursor_options) +KDbCursor* SqliteConnection::prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options) { - return new SqliteCursor(this, sql, cursor_options); + return new SqliteCursor(this, sql, options); } -KDbCursor* SqliteConnection::prepareQuery(KDbQuerySchema* query, int cursor_options) +KDbCursor* SqliteConnection::prepareQuery(KDbQuerySchema* query, KDbCursor::Options options) { - return new SqliteCursor(this, query, cursor_options); + return new SqliteCursor(this, query, options); } KDbSqlResult* SqliteConnection::drv_executeSQL(const KDbEscapedString& sql) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String("ExecuteSQL (SQLite): ") + sql.toString()); #endif sqlite3_stmt *prepared_st = nullptr; const int res = sqlite3_prepare( d->data, /* Database handle */ sql.constData(), /* SQL statement, UTF-8 encoded */ sql.length(), /* Length of zSql in bytes. */ &prepared_st, /* OUT: Statement handle */ nullptr/*const char **pzTail*/ /* OUT: Pointer to unused portion of zSql */ ); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(); #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String(" Failure")); #endif return nullptr; } #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String(" Success")); #endif return new SqliteSqlResult(this, prepared_st); } bool SqliteConnection::drv_executeVoidSQL(const KDbEscapedString& sql) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String("ExecuteVoidSQL (SQLite): ") + sql.toString()); #endif char *errmsg_p = nullptr; const int res = sqlite3_exec( d->data, sql.constData(), nullptr/*callback*/, nullptr, &errmsg_p); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); } if (errmsg_p) { clearResult(); m_result.setServerMessage(QLatin1String(errmsg_p)); sqlite3_free(errmsg_p); } else { storeResult(); } #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String( res == SQLITE_OK ? " Success" : " Failure")); #endif return res == SQLITE_OK; } QString SqliteConnection::serverResultName() const { return SqliteConnectionInternal::serverResultName(m_result.serverErrorCode()); } KDbPreparedStatementInterface* SqliteConnection::prepareStatementInternal() { return new SqlitePreparedStatement(d); } bool SqliteConnection::findAndLoadExtension(const QString & name) { QStringList pluginPaths; foreach (const QString& path, KDb::libraryPaths()) { pluginPaths += path + QLatin1String("/sqlite3"); } pluginPaths += options()->property("extraSqliteExtensionPaths").value().toStringList(); foreach (const QString& path, pluginPaths) { if (loadExtension(path + QLatin1Char('/') + name + QLatin1String(KDB_SHARED_LIB_EXTENSION))) { return true; } } clearResult(); m_result = KDbResult(ERR_CANNOT_LOAD_OBJECT, SqliteConnection::tr("Could not load SQLite plugin \"%1\".").arg(name)); return false; } bool SqliteConnection::loadExtension(const QString& path) { bool tempEnable = false; clearResult(); QFileInfo fileInfo(path); if (!fileInfo.exists()) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, SqliteConnection::tr("Could not find SQLite plugin file \"%1\".").arg(path)); //sqliteWarning() << "SqliteConnection::loadExtension(): Could not find SQLite extension"; return false; } if (!d->extensionsLoadingEnabled()) { tempEnable = true; d->setExtensionsLoadingEnabled(true); } char *errmsg_p = 0; int res = sqlite3_load_extension(d->data, QDir::toNativeSeparators(path).toUtf8().constData(), 0, &errmsg_p); bool ok = res == SQLITE_OK; if (!ok) { m_result.setServerErrorCode(res); m_result = KDbResult(ERR_CANNOT_LOAD_OBJECT, SqliteConnection::tr("Could not load SQLite extension \"%1\".").arg(path)); sqliteWarning() << "SqliteConnection::loadExtension(): Could not load SQLite extension" << path << ":" << errmsg_p; if (errmsg_p) { m_result.setServerMessage(QLatin1String(errmsg_p)); sqlite3_free(errmsg_p); } } if (tempEnable) { d->setExtensionsLoadingEnabled(false); } return ok; } diff --git a/src/drivers/sqlite/SqliteConnection.h b/src/drivers/sqlite/SqliteConnection.h index 6e10e154..27444e97 100644 --- a/src/drivers/sqlite/SqliteConnection.h +++ b/src/drivers/sqlite/SqliteConnection.h @@ -1,121 +1,123 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONN_SQLITE_H #define KDB_CONN_SQLITE_H #include #include "KDbConnection.h" class SqliteConnectionInternal; class KDbDriver; /*! @brief SQLite-specific connection Following connection options are supported (see KDbConnectionOptions): - extraSqliteExtensionPaths (read/write, QStringList): adds extra seach paths for SQLite extensions. Set them before KDbConnection::useDatabase() is called. Absolute paths are recommended. */ class SqliteConnection : public KDbConnection { Q_DECLARE_TR_FUNCTIONS(SqliteConnection) public: virtual ~SqliteConnection(); - KDbCursor* prepareQuery(const KDbEscapedString& sql, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; - KDbCursor* prepareQuery(KDbQuerySchema* query, int cursor_options = 0) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(const KDbEscapedString& sql, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; + KDbCursor* prepareQuery(KDbQuerySchema* query, + KDbCursor::Options options = KDbCursor::Option::None) Q_DECL_OVERRIDE Q_REQUIRED_RESULT; KDbPreparedStatementInterface* prepareStatementInternal() Q_DECL_OVERRIDE Q_REQUIRED_RESULT; protected: /*! Used by driver */ SqliteConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); virtual bool drv_connect(); virtual bool drv_getServerVersion(KDbServerVersionInfo* version); virtual bool drv_disconnect(); virtual bool drv_getDatabasesList(QStringList* list); #if 0 // TODO //! @todo move this somewhere to low level class (MIGRATION?) virtual bool drv_getTablesList(QStringList* list); #endif //! @todo move this somewhere to low level class (MIGRATION?) virtual tristate drv_containsTable(const QString &tableName); /*! Creates new database using connection. Note: Do not pass @a dbName arg because for file-based engine (that has one database per connection) it is defined during connection. */ virtual bool drv_createDatabase(const QString &dbName = QString()); /*! Opens existing database using connection. Do not pass @a dbName arg because for file-based engine (that has one database per connection) it is defined during connection. If you pass it, database file name will be changed. */ virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = 0, KDbMessageHandler* msgHandler = 0); virtual bool drv_closeDatabase(); /*! Drops database from the server using connection. After drop, database shouldn't be accessible anymore, so database file is just removed. See note from drv_useDatabase(). */ virtual bool drv_dropDatabase(const QString &dbName = QString()); virtual KDbSqlResult* drv_executeSQL(const KDbEscapedString& sql); virtual bool drv_executeVoidSQL(const KDbEscapedString& sql); //! Implemented for KDbResultable virtual QString serverResultName() const; void storeResult(); virtual tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field, const QString& propertyName, const QVariant& value); //! for drv_changeFieldProperty() tristate changeFieldType(KDbTableSchema *table, KDbField *field, KDbField::Type type); SqliteConnectionInternal* d; private: bool drv_useDatabaseInternal(bool *cancelled, KDbMessageHandler* msgHandler, bool createIfMissing); //! Closes database without altering stored result number and message void drv_closeDatabaseSilently(); //! Finds a native SQLite extension @a name in the search path and loads it. //! Path and filename extension should not be provided. //! @return true on success bool findAndLoadExtension(const QString & name); //! Loads extension from plugin at @a path (absolute path is recommended) //! @return true on success bool loadExtension(const QString& path); friend class SqliteDriver; friend class SqliteCursor; friend class SqliteSqlResult; Q_DISABLE_COPY(SqliteConnection) }; #endif diff --git a/src/drivers/sqlite/SqliteCursor.cpp b/src/drivers/sqlite/SqliteCursor.cpp index 6cbbecc6..c62f8688 100644 --- a/src/drivers/sqlite/SqliteCursor.cpp +++ b/src/drivers/sqlite/SqliteCursor.cpp @@ -1,342 +1,343 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "SqliteCursor.h" #include "SqliteConnection.h" #include "SqliteConnection_p.h" #include "sqlite_debug.h" #include "KDbDriver.h" #include "KDbError.h" #include "KDbRecordData.h" #include "KDbUtils.h" #include #include #include //! safer interpretations of boolean values for SQLite static bool sqliteStringToBool(const QString& s) { return 0 == s.compare(QLatin1String("yes"), Qt::CaseInsensitive) || (0 != s.compare(QLatin1String("no"), Qt::CaseInsensitive) && s != QLatin1String("0")); } //---------------------------------------------------- class SqliteCursorData : public SqliteConnectionInternal { public: explicit SqliteCursorData(SqliteConnection* conn) : SqliteConnectionInternal(conn) , prepared_st_handle(0) , utail(0) , curr_coldata(0) , curr_colname(0) , cols_pointers_mem_size(0) { data_owned = false; } /* void fetchRowDataIfNeeded() { if (!rowDataReadyToFetch) return true; rowDataReadyToFetch = false; m_fieldCount = sqlite3_data_count(data); for (int i=0; i records; //!< buffer data inline QVariant getValue(KDbField *f, int i) { int type = sqlite3_column_type(prepared_st_handle, i); if (type == SQLITE_NULL) { return QVariant(); } else if (!f || type == SQLITE_TEXT) { //! @todo support for UTF-16 QString text(QString::fromUtf8( (const char*)sqlite3_column_text(prepared_st_handle, i), sqlite3_column_bytes(prepared_st_handle, i))); if (!f) { return text; } const KDbField::Type t = f->type(); // cache: evaluating type of expressions can be expensive if (KDbField::isTextType(t)) { return text; } else if (t == KDbField::Date) { return QDate::fromString(text, Qt::ISODate); } else if (t == KDbField::Time) { //QDateTime - a hack needed because QVariant(QTime) has broken isNull() return KDbUtils::stringToHackedQTime(text); } else if (t == KDbField::DateTime) { if (text.length() > 10) { text[10] = QLatin1Char('T'); //for ISODate compatibility } return QDateTime::fromString(text, Qt::ISODate); } else if (t == KDbField::Boolean) { return sqliteStringToBool(text); } else { return QVariant(); //!< @todo } } else if (type == SQLITE_INTEGER) { const KDbField::Type t = f->type(); // cache: evaluating type of expressions can be expensive if (t == KDbField::BigInteger) { return QVariant(qint64(sqlite3_column_int64(prepared_st_handle, i))); } else if (KDbField::isIntegerType(t)) { return QVariant(sqlite3_column_int(prepared_st_handle, i)); } else if (t == KDbField::Boolean) { return sqlite3_column_int(prepared_st_handle, i) != 0; } else if (KDbField::isFPNumericType(t)) { //WEIRD, YEAH? return QVariant(double(sqlite3_column_int(prepared_st_handle, i))); } else { return QVariant(); //!< @todo } } else if (type == SQLITE_FLOAT) { const KDbField::Type t = f->type(); // cache: evaluating type of expressions can be expensive if (KDbField::isFPNumericType(t)) { return QVariant(sqlite3_column_double(prepared_st_handle, i)); } else if (t == KDbField::BigInteger) { return QVariant(qint64(sqlite3_column_int64(prepared_st_handle, i))); } else if (KDbField::isIntegerType(t)) { return QVariant(int(sqlite3_column_double(prepared_st_handle, i))); } else { return QVariant(); //!< @todo } } else if (type == SQLITE_BLOB) { if (f && f->type() == KDbField::BLOB) { //! @todo efficient enough? return QByteArray((const char*)sqlite3_column_blob(prepared_st_handle, i), sqlite3_column_bytes(prepared_st_handle, i)); } else return QVariant(); //!< @todo } return QVariant(); } Q_DISABLE_COPY(SqliteCursorData) }; -SqliteCursor::SqliteCursor(SqliteConnection* conn, const KDbEscapedString& sql, int options) +SqliteCursor::SqliteCursor(SqliteConnection* conn, const KDbEscapedString& sql, + Options options) : KDbCursor(conn, sql, options) , d(new SqliteCursorData(conn)) { d->data = static_cast(conn)->d->data; } -SqliteCursor::SqliteCursor(SqliteConnection* conn, KDbQuerySchema* query, int options) +SqliteCursor::SqliteCursor(SqliteConnection* conn, KDbQuerySchema* query, Options options) : KDbCursor(conn, query, options) , d(new SqliteCursorData(conn)) { d->data = static_cast(conn)->d->data; } SqliteCursor::~SqliteCursor() { close(); delete d; } bool SqliteCursor::drv_open(const KDbEscapedString& sql) { //! @todo decode if (! d->data) { // this may as example be the case if SqliteConnection::drv_useDatabase() // wasn't called before. Normaly sqlite_compile/sqlite3_prepare // should handle it, but it crashes in in sqlite3SafetyOn at util.c:786 sqliteWarning() << "SqliteCursor::drv_open(): Database handle undefined."; return false; } int res = sqlite3_prepare( d->data, /* Database handle */ sql.constData(), /* SQL statement, UTF-8 encoded */ sql.length(), /* Length of zSql in bytes. */ &d->prepared_st_handle, /* OUT: Statement handle */ 0/*const char **pzTail*/ /* OUT: Pointer to unused portion of zSql */ ); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(); return false; } if (isBuffered()) { //! @todo manage size dynamically d->records.resize(128); } return true; } bool SqliteCursor::drv_close() { int res = sqlite3_finalize(d->prepared_st_handle); if (res != SQLITE_OK) { m_result.setServerErrorCode(res); storeResult(); return false; } return true; } void SqliteCursor::drv_getNextRecord() { int res = sqlite3_step(d->prepared_st_handle); if (res == SQLITE_ROW) { m_fetchResult = FetchOK; m_fieldCount = sqlite3_data_count(d->prepared_st_handle); //#else //for SQLITE3 data fetching is delayed. Now we even do not take field count information // // -- just set a flag that we've a data not fetched but available m_fieldsToStoreInRecord = m_fieldCount; } else { if (res == SQLITE_DONE) { m_fetchResult = FetchEnd; } else { m_result.setServerErrorCode(res); m_fetchResult = FetchError; } } //debug /* if ((int)m_result == (int)FetchOK && d->curr_coldata) { for (int i=0;icurr_colname[i]<<" "<< d->curr_colname[m_fieldCount+i] << " = " << (d->curr_coldata[i] ? QString::fromLocal8Bit(d->curr_coldata[i]) : "(NULL)"); } // sqliteDebug() << m_fieldCount << "col(s) fetched"; }*/ } void SqliteCursor::drv_appendCurrentRecordToBuffer() { // sqliteDebug(); if (!d->curr_coldata) return; if (!d->cols_pointers_mem_size) d->cols_pointers_mem_size = m_fieldCount * sizeof(char*); const char **record = (const char**)malloc(d->cols_pointers_mem_size); const char **src_col = d->curr_coldata; const char **dest_col = record; for (int i = 0; i < m_fieldCount; i++, src_col++, dest_col++) { // sqliteDebug() << i <<": '" << *src_col << "'"; // sqliteDebug() << "src_col: " << src_col; *dest_col = *src_col ? strdup(*src_col) : 0; } d->records[m_records_in_buf] = record; // sqliteDebug() << "ok."; } void SqliteCursor::drv_bufferMovePointerNext() { d->curr_coldata++; //move to next record in the buffer } void SqliteCursor::drv_bufferMovePointerPrev() { d->curr_coldata--; //move to prev record in the buffer } //compute a place in the buffer that contain next record's data //and move internal buffer pointer to that place void SqliteCursor::drv_bufferMovePointerTo(qint64 at) { d->curr_coldata = d->records.at(at); } void SqliteCursor::drv_clearBuffer() { if (d->cols_pointers_mem_size > 0) { const int records_in_buf = m_records_in_buf; const char ***r_ptr = d->records.data(); for (int i = 0; i < records_in_buf; i++, r_ptr++) { const char **field_data = *r_ptr; for (int col = 0; col < m_fieldCount; col++, field_data++) { free((void*)*field_data); //free field memory } free(*r_ptr); //free pointers to fields array } } m_records_in_buf = 0; d->cols_pointers_mem_size = 0; d->records.clear(); } //! @todo /* const char *** SqliteCursor::bufferData() { if (!isBuffered()) return 0; return m_records.data(); }*/ const char ** SqliteCursor::recordData() const { return d->curr_coldata; } bool SqliteCursor::drv_storeCurrentRecord(KDbRecordData* data) const { if (!m_visibleFieldsExpanded) {//simple version: without types for (int i = 0; i < m_fieldCount; i++) { (*data)[i] = QString::fromUtf8( (const char*)sqlite3_column_text(d->prepared_st_handle, i), sqlite3_column_bytes(d->prepared_st_handle, i)); } return true; } for (int i = 0; i < m_fieldCount; ++i) { KDbField *f = m_visibleFieldsExpanded->at(i)->field(); // sqliteDebug() << "col=" << (col ? *col : 0); (*data)[i] = d->getValue(f, i); } return true; } QVariant SqliteCursor::value(int i) { if (i < 0 || i > (m_fieldCount - 1)) //range checking return QVariant(); //! @todo allow disable range checking! - performance reasons KDbField *f = (m_visibleFieldsExpanded && i < m_visibleFieldsExpanded->count()) ? m_visibleFieldsExpanded->at(i)->field() : nullptr; return d->getValue(f, i); //, i==m_logicalFieldCount/*ROWID*/); } QString SqliteCursor::serverResultName() const { return SqliteConnectionInternal::serverResultName(m_result.serverErrorCode()); } void SqliteCursor::storeResult() { d->storeResult(&m_result); } diff --git a/src/drivers/sqlite/SqliteCursor.h b/src/drivers/sqlite/SqliteCursor.h index 0b28aa7e..15244623 100644 --- a/src/drivers/sqlite/SqliteCursor.h +++ b/src/drivers/sqlite/SqliteCursor.h @@ -1,82 +1,83 @@ /* This file is part of the KDE project Copyright (C) 2003-2010 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_SQLITECURSOR_H #define KDB_SQLITECURSOR_H #include #include "KDbCursor.h" class SqliteCursorData; class SqliteConnection; /*! */ class SqliteCursor : public KDbCursor { public: virtual ~SqliteCursor(); virtual QVariant value(int i); /*! [PROTOTYPE] @return internal buffer data. */ //! @todo virtual const char *** bufferData() /*! [PROTOTYPE] @return current record data or NULL if there is no current records. */ virtual const char ** recordData() const; virtual bool drv_storeCurrentRecord(KDbRecordData* data) const; //! Implemented for KDbResultable virtual QString serverResultName() const; protected: /*! KDbCursor will operate on @a conn, raw @a sql statement will be used to execute query. */ - SqliteCursor(SqliteConnection* conn, const KDbEscapedString& sql, int options = NoOptions); + SqliteCursor(SqliteConnection* conn, const KDbEscapedString& sql, + Options options = KDbCursor::Option::None); /*! KDbCursor will operate on @a conn, @a query schema will be used to execute query. */ SqliteCursor(SqliteConnection* conn, KDbQuerySchema* query, - int options = NoOptions); + Options options = KDbCursor::Option::None); virtual bool drv_open(const KDbEscapedString& sql); virtual bool drv_close(); virtual void drv_getNextRecord(); virtual void drv_appendCurrentRecordToBuffer(); virtual void drv_bufferMovePointerNext(); virtual void drv_bufferMovePointerPrev(); virtual void drv_bufferMovePointerTo(qint64 at); //! @todo virtual void drv_storeCurrentRecord(); //PROTOTYPE: /*! Method called when cursor's buffer need to be cleared (only for buffered cursor type), eg. in close(). */ virtual void drv_clearBuffer(); void storeResult(); SqliteCursorData * const d; friend class SqliteConnection; Q_DISABLE_COPY(SqliteCursor) }; #endif diff --git a/tests/features/main.cpp b/tests/features/main.cpp index a8efcb2a..8cfd7495 100644 --- a/tests/features/main.cpp +++ b/tests/features/main.cpp @@ -1,352 +1,352 @@ /* This file is part of the KDE project Copyright (C) 2003-2010 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; QByteArray prgname; QString db_name; QString drv_id; QString test_name; -int cursor_options = 0; +KDbCursor::Options cursor_options; bool db_name_required = true; KDbConnectionData conn_data; //! @todo IMPORTANT: replace QPointer conn; KDbConnection* conn = 0; //! @todo IMPORTANT: replace QPointer driver; KDbDriver* driver; QApplication *app = 0; #include "dbcreation_test.h" #include "cursors_test.h" #include "schema_test.h" #include "tables_test.h" #ifndef NO_GUI # include "tableview_test.h" #endif #include "parser_test.h" #include "dr_prop_test.h" static int finish(int code) { qDebug() << "main:" << test_name << "test:" << (code==0?"PASSED":"ERROR"); if (code != 0 && conn) { qDebug() << "main:" << conn->result(); conn->disconnect(); delete conn; } return code; } //! @return true if option @a option or @a shortOption is found //! Removes the option. static bool takeOption(QStringList &args, const QString &option, const QString &shortOption = QString()) { return args.removeOne(QLatin1String("-") + (shortOption.isEmpty() ? option : shortOption)) || args.removeOne(QLatin1String("--") + option); } //! @return next element after option @a option or @a shortOption, what should mean parameter //! Removes option and its argument. static QString takeOptionWithArg(QStringList &args, const QString &option, const QString &shortOption = QString()) { int index = args.indexOf(QLatin1String("-") + (shortOption.isEmpty() ? option : shortOption)); if (index == -1) index = args.indexOf(QLatin1String("--") + option); if (index == -1) return QString(); args.removeAt(index); return args.takeAt(index); // option's argument } #define APPNAME "kdbfeaturestest" static void showHelp() { QTextStream s(stdout); s << APPNAME ", version " KDB_VERSION_STRING "\n" "\nA set of tests for the KDb library API." "\nEvery test is mostly driver-independent." "\n (c) 2003-2016, Kexi Team" "\n (c) 2003-2006, OpenOffice Software LLC." "\n" "\nUsage: " APPNAME " --test [options]" "\n driver_id [db_name] [sql_statement]" "\n" "\nOptions:" "\n --help Displays this help and exits" "\n --buffered-cursors Optional switch: turns cursors used in any" "\n tests to be buffered" "\n -h, --host Host name to use when connecting" "\n to server backends" "\n -p, --password Password to use when connecting to server" "\n backends" "\n -P, --port Port number to use when connecting to server" "\n backends" "\n --query-params Query parameters separated by '|' character" "\n that will be passed to query statement" "\n to replace [...] placeholders" "\n -t, --test Specifies test to execute; required" "\n Available tests:" "\n - cursors: test for cursors behavior" "\n - schema: test for db schema retrieving" "\n - dbcreation: test for new db creation" "\n - tables: test for tables creation and data" "\n inserting" //"\n - tableview: test for KexiDataTableView data-aware //"\n widget "\n - parser: test for parsing sql statements," "\n returns debug string for a given" "\n sql statement or error message" "\n - dr_prop: shows properties of selected" "\n driver" "\n -u, --user User name to use when connecting to servers" "\n backends" "\n" "\nNotes:" "\n1. 'dr_prop' requires argument" "\n2. 'parser' test requires , and " "\n arguments" "\n3. All other tests require and arguments" "\n4. 'tables' test automatically runs 'dbcreation' test" "\n is removed if already exists" "\n5. must be a valid database created using KDb," "\n e.g. using the \"tables\" test" "\n" "\nArguments:" "\n driver_id Driver ID, e.g. org.kde.kdb.sqlite;" "\n if a word without \".\" is used," "\n \"org.kde.kdb.\" will be prepended" "\n db_name Database name" "\n sql_statement Optional SQL statement (for parser test)" "\n" "\nExamples:" "\n " APPNAME " -t dr_prop sqlite" "\n Shows properties of the SQLite driver" "\n " APPNAME " -p PASSWORD -u USER -t tables mysql mysqltest" "\n Creates database \"mysqltest\" with test" "\n tables and datas" "\n " APPNAME " -p PASSWORD -u USER -t tables -h myhost.org \\" "\n postgresql pgsqltest" "\n Creates database \"pgsqltest\" with test" "\n tables and data on host \"myhost.org\"" "\n"; } int main(int argc, char** argv) { // int minargs = 2; #ifndef NO_GUI bool gui = false; #endif QFileInfo info = QFileInfo(argv[0]); prgname = info.baseName().toLatin1(); QStringList args; for (int i=1; iisFileBased()) { qDebug() << "main: MIME types for" << driver->metaData()->id() << ":" << driver->metaData()->mimeTypes(); } const bool bufCursors = takeOption(args, "buffered-cursors"); QString queryParams = takeOptionWithArg(args, "query-params"); //open connection if (args.count() >= 2) db_name = args[1]; if (db_name_required && db_name.isEmpty()) { qDebug() << prgname << ": database name?"; return finish(1); } conn_data.setDatabaseName(db_name); if (!db_name.isEmpty() ) { //additional switches: if (bufCursors) { - cursor_options |= KDbCursor::Buffered; + cursor_options |= KDbCursor::Option::Buffered; } conn = driver->createConnection(conn_data); if (!conn || driver->result().isError()) { qDebug() << driver->result(); return finish(1); } qDebug() << "main: KDbConnection object created."; if (!conn->connect()) { qDebug() << conn->result(); return finish(1); } qDebug() << "main: KDbConnection::connect() OK."; } //start test: int r = 0; if (test_name == "cursors") r = cursorsTest(); else if (test_name == "schema") r = schemaTest(); else if (test_name == "dbcreation") r = dbCreationTest(); else if (test_name == "tables") r = tablesTest(conn); #ifndef NO_GUI else if (test_name == "tableview") r = tableViewTest(); #endif else if (test_name == "parser") { QStringList params; if (!queryParams.isEmpty()) params = queryParams.split("|"); r = parserTest(KDbEscapedString(args[2]), params); } else if (test_name == "dr_prop") r = drPropTest(); else { qWarning() << "No such test:" << test_name; qWarning() << "Available tests are:" << tests; // usage(); return finish(1); } #ifndef NO_GUI if (app && r == 0 && gui) app->exec(); #endif if (r) qDebug() << "RECENT SQL STATEMENT: " << conn->recentSQLString(); if (conn && !conn->disconnect()) r = 1; // qDebug() << "!!! KDbTransaction::globalcount == " << KDbTransaction::globalCount(); // qDebug() << "!!! KDbTransactionData::globalcount == " << KDbTransactionData::globalCount(); delete app; return finish(r); }