diff --git a/src/KDb.cpp b/src/KDb.cpp index 61dd4c63..672601bb 100644 --- a/src/KDb.cpp +++ b/src/KDb.cpp @@ -1,2228 +1,2230 @@ /* This file is part of the KDE project Copyright (C) 2004-2016 Jarosław Staniek Copyright (c) 2006, 2007 Thomas Braxton Copyright (c) 1999 Preston Brown Copyright (c) 1997 Matthias Kalle Dalheimer 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 "KDb.h" #include "KDb_p.h" #include "KDbConnectionData.h" #include "KDbConnection.h" #include "KDbCursor.h" #include "KDbDriverManager.h" #include "KDbDriverBehavior.h" #include "KDbLookupFieldSchema.h" #include "KDbMessageHandler.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbRecordData.h" #include "KDbSqlResult.h" #include "KDbTableOrQuerySchema.h" #include "KDbVersionInfo.h" #include "kdb_debug.h" #include "transliteration/transliteration_table.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include Q_DECLARE_METATYPE(KDbField::Type) class ConnectionTestDialog; class ConnectionTestThread : public QThread { Q_OBJECT public: ConnectionTestThread(ConnectionTestDialog *dlg, const KDbConnectionData& connData); void run() override; Q_SIGNALS: void error(const QString& msg, const QString& details); protected: void emitError(const KDbResultable& KDbResultable); ConnectionTestDialog* m_dlg; KDbConnectionData m_connData; KDbDriver *m_driver; private: Q_DISABLE_COPY(ConnectionTestThread) }; class ConnectionTestDialog : public QProgressDialog // krazy:exclude=qclasses { Q_OBJECT public: ConnectionTestDialog(const KDbConnectionData& data, KDbMessageHandler* msgHandler, QWidget* parent = nullptr); ~ConnectionTestDialog() override; int exec() override; public Q_SLOTS: void error(const QString& msg, const QString& details); protected Q_SLOTS: void slotTimeout(); void reject() override; protected: QPointer m_thread; KDbConnectionData m_connData; QTimer m_timer; KDbMessageHandler* m_msgHandler; int m_elapsedTime; bool m_error; QString m_msg; QString m_details; bool m_stopWaiting; private: Q_DISABLE_COPY(ConnectionTestDialog) }; ConnectionTestThread::ConnectionTestThread(ConnectionTestDialog* dlg, const KDbConnectionData& connData) : m_dlg(dlg), m_connData(connData) { connect(this, SIGNAL(error(QString,QString)), dlg, SLOT(error(QString,QString)), Qt::QueuedConnection); // try to load driver now because it's not supported in different thread KDbDriverManager manager; m_driver = manager.driver(m_connData.driverId()); if (manager.result().isError()) { emitError(*manager.resultable()); m_driver = nullptr; } } void ConnectionTestThread::emitError(const KDbResultable& KDbResultable) { QString msg; QString details; KDb::getHTMLErrorMesage(KDbResultable, &msg, &details); emit error(msg, details); } void ConnectionTestThread::run() { if (!m_driver) { return; } QScopedPointer conn(m_driver->createConnection(m_connData)); if (conn.isNull() || m_driver->result().isError()) { emitError(*m_driver); return; } if (!conn->connect() || conn->result().isError()) { emitError(*conn); return; } // SQL database backends like PostgreSQL require executing "USE database" // if we really want to know connection to the server succeeded. QString tmpDbName; if (!conn->useTemporaryDatabaseIfNeeded(&tmpDbName)) { emitError(*conn); return; } if (!tmpDbName.isEmpty()) { if (!conn->closeDatabase()) { emitError(*conn); } } emitError(KDbResultable()); } ConnectionTestDialog::ConnectionTestDialog(const KDbConnectionData& data, KDbMessageHandler* msgHandler, QWidget* parent) : QProgressDialog(parent) , m_thread(new ConnectionTestThread(this, data)) , m_connData(data) , m_msgHandler(msgHandler) , m_elapsedTime(0) , m_error(false) , m_stopWaiting(false) { setWindowTitle(tr("Test Connection", "Dialog's title: testing database connection")); setLabelText(tr("Testing connection to \"%1\" database server...") .arg(data.toUserVisibleString())); setModal(true); setRange(0, 0); //to show busy indicator connect(&m_timer, SIGNAL(timeout()), this, SLOT(slotTimeout())); adjustSize(); resize(250, height()); } ConnectionTestDialog::~ConnectionTestDialog() { if (m_thread->isRunning()) { m_thread->terminate(); } m_thread->deleteLater(); } int ConnectionTestDialog::exec() { //kdbDebug() << "tid:" << QThread::currentThread() << "this_thread:" << thread(); m_timer.start(20); m_thread->start(); const int res = QProgressDialog::exec(); // krazy:exclude=qclasses m_thread->wait(); m_timer.stop(); return res; } void ConnectionTestDialog::slotTimeout() { //kdbDebug() << "tid:" << QThread::currentThread() << "this_thread:" << thread(); kdbDebug() << m_error; bool notResponding = false; if (m_elapsedTime >= 1000*5) {//5 seconds m_stopWaiting = true; notResponding = true; } kdbDebug() << m_elapsedTime << m_stopWaiting << notResponding; if (m_stopWaiting) { m_timer.disconnect(this); m_timer.stop(); reject(); kdbDebug() << "after reject"; QString message; QString details; KDbMessageHandler::MessageType type; if (m_error) { message = tr("Test connection to \"%1\" database server failed.") .arg(m_connData.toUserVisibleString()); details = m_msg; if (!m_details.isEmpty()) { details += QLatin1Char('\n') + m_details; } type = KDbMessageHandler::Sorry; m_error = false; } else if (notResponding) { message = tr("Test connection to \"%1\" database server failed. The server is not responding.") .arg(m_connData.toUserVisibleString()); type = KDbMessageHandler::Sorry; } else { message = tr("Test connection to \"%1\" database server established successfully.") .arg(m_connData.toUserVisibleString()), type = KDbMessageHandler::Information; } if (m_msgHandler) { m_msgHandler->showErrorMessage(type, message, details, tr("Test Connection")); } return; } m_elapsedTime += 20; setValue(m_elapsedTime); } void ConnectionTestDialog::error(const QString& msg, const QString& details) { //kdbDebug() << "tid:" << QThread::currentThread() << "this_thread:" << thread(); kdbDebug() << msg << details; m_stopWaiting = true; m_msg = msg; m_details = details; m_error = !msg.isEmpty() || !details.isEmpty(); if (m_error) { kdbDebug() << "ERR!"; } } void ConnectionTestDialog::reject() { if (m_thread->isRunning()) { m_thread->terminate(); } m_timer.disconnect(this); m_timer.stop(); QProgressDialog::reject(); // krazy:exclude=qclasses } // ---- //! @return hex digit converted to integer (0 to 15), 0xFF on failure inline static unsigned char hexDigitToInt(char digit) { if (digit >= '0' && digit <= '9') { return digit - '0'; } if (digit >= 'a' && digit <= 'f') { return digit - 'a' + 10; } if (digit >= 'A' && digit <= 'F') { return digit - 'A' + 10; } return 0xFF; } //! Converts textual representation @a data of a hex number (@a length digits) to a byte array @a array //! @return true on success and false if @a data contains characters that are not hex digits. //! true is returned for empty @a data as well. inline static bool hexToByteArrayInternal(const char* data, int length, QByteArray *array) { Q_ASSERT(length >= 0); Q_ASSERT(data || length == 0); array->resize(length / 2 + length % 2); for(int i = 0; length > 0; --length, ++data, ++i) { unsigned char d1 = hexDigitToInt(data[0]); unsigned char d2; if (i == 0 && (length % 2) == 1) { // odd number of digits; no leading 0 d2 = d1; d1 = 0; } else { --length; ++data; d2 = hexDigitToInt(data[0]); } if (d1 == 0xFF || d2 == 0xFF) { return false; } (*array)[i] = (d1 << 4) + d2; } return true; } KDbVersionInfo KDb::version() { return KDbVersionInfo( KDB_VERSION_MAJOR, KDB_VERSION_MINOR, KDB_VERSION_PATCH); } bool KDb::deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname, KDbField::Type keytype, const QVariant &keyval) { Q_ASSERT(conn); return conn->executeSql(KDbEscapedString("DELETE FROM %1 WHERE %2=%3") .arg(conn->escapeIdentifier(tableName)) .arg(conn->escapeIdentifier(keyname)) .arg(conn->driver()->valueToSQL(keytype, keyval))); } bool KDb::deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2) { Q_ASSERT(conn); return conn->executeSql(KDbEscapedString("DELETE FROM %1 WHERE %2=%3 AND %4=%5") .arg(conn->escapeIdentifier(tableName)) .arg(conn->escapeIdentifier(keyname1)) .arg(conn->driver()->valueToSQL(keytype1, keyval1)) .arg(conn->escapeIdentifier(keyname2)) .arg(conn->driver()->valueToSQL(keytype2, keyval2))); } bool KDb::deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2, const QString &keyname3, KDbField::Type keytype3, const QVariant& keyval3) { Q_ASSERT(conn); return conn->executeSql(KDbEscapedString("DELETE FROM %1 WHERE %2=%3 AND %4=%5 AND %6=%7") .arg(conn->escapeIdentifier(tableName)) .arg(conn->escapeIdentifier(keyname1)) .arg(conn->driver()->valueToSQL(keytype1, keyval1)) .arg(conn->escapeIdentifier(keyname2)) .arg(conn->driver()->valueToSQL(keytype2, keyval2)) .arg(conn->escapeIdentifier(keyname3)) .arg(conn->driver()->valueToSQL(keytype3, keyval3))); } bool KDb::deleteAllRecords(KDbConnection* conn, const QString &tableName) { Q_ASSERT(conn); return conn->executeSql(KDbEscapedString("DELETE FROM %1") .arg(conn->escapeIdentifier(tableName))); } -KDB_EXPORT quint64 KDb::lastInsertedAutoIncValue(QSharedPointer *result, +KDB_EXPORT quint64 KDb::lastInsertedAutoIncValue(QSharedPointer result, const QString &autoIncrementFieldName, const QString &tableName, quint64 *recordId) { - Q_ASSERT(result); - const quint64 foundRecordId = (*result)->lastInsertRecordId(); + if (!result) { + return std::numeric_limits::max(); + } + const quint64 foundRecordId = result->lastInsertRecordId(); if (recordId) { *recordId = foundRecordId; } - return KDb::lastInsertedAutoIncValue((*result)->connection(), + return KDb::lastInsertedAutoIncValue(result->connection(), foundRecordId, autoIncrementFieldName, tableName); } KDB_EXPORT quint64 KDb::lastInsertedAutoIncValue(KDbConnection *conn, const quint64 recordId, const QString &autoIncrementFieldName, const QString &tableName) { const KDbDriverBehavior *behavior = KDbDriverBehavior::get(conn->driver()); if (behavior->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE) { return recordId; } KDbRecordData rdata; if (recordId == std::numeric_limits::max() || true != conn->querySingleRecord( KDbEscapedString("SELECT ") + escapeIdentifier(tableName) + '.' + escapeIdentifier(autoIncrementFieldName) + " FROM " + escapeIdentifier(tableName) + " WHERE " + behavior->ROW_ID_FIELD_NAME + '=' + KDbEscapedString::number(recordId), &rdata)) { return std::numeric_limits::max(); } return rdata[0].toULongLong(); } bool KDb::isEmptyValue(KDbField::Type type, const QVariant &value) { if (KDbField::isTextType(type)) { return value.toString().isEmpty() && !value.toString().isNull(); } else if (type == KDbField::BLOB) { return value.toByteArray().isEmpty() && !value.toByteArray().isNull(); } return value.isNull(); } KDbEscapedString KDb::sqlWhere(KDbDriver *drv, KDbField::Type t, const QString& fieldName, const QVariant& value) { if (value.isNull()) return KDbEscapedString(fieldName) + " is NULL"; return KDbEscapedString(fieldName) + '=' + drv->valueToSQL(t, value); } //! Cache struct TypeCache { TypeCache() { for (KDbField::Type t = KDbField::InvalidType; t <= KDbField::LastType; t = KDbField::Type(int(t) + 1)) { const KDbField::TypeGroup tg = KDbField::typeGroup(t); QList list; QStringList name_list, str_list; if (tlist.contains(tg)) { list = tlist.value(tg); name_list = nlist.value(tg); str_list = slist.value(tg); } list += t; name_list += KDbField::typeName(t); str_list += KDbField::typeString(t); tlist[ tg ] = list; nlist[ tg ] = name_list; slist[ tg ] = str_list; } def_tlist[ KDbField::InvalidGroup ] = KDbField::InvalidType; def_tlist[ KDbField::TextGroup ] = KDbField::Text; def_tlist[ KDbField::IntegerGroup ] = KDbField::Integer; def_tlist[ KDbField::FloatGroup ] = KDbField::Double; def_tlist[ KDbField::BooleanGroup ] = KDbField::Boolean; def_tlist[ KDbField::DateTimeGroup ] = KDbField::Date; def_tlist[ KDbField::BLOBGroup ] = KDbField::BLOB; } QHash< KDbField::TypeGroup, QList > tlist; QHash< KDbField::TypeGroup, QStringList > nlist; QHash< KDbField::TypeGroup, QStringList > slist; QHash< KDbField::TypeGroup, KDbField::Type > def_tlist; }; Q_GLOBAL_STATIC(TypeCache, KDb_typeCache) const QList KDb::fieldTypesForGroup(KDbField::TypeGroup typeGroup) { return KDb_typeCache->tlist.value(typeGroup); } QStringList KDb::fieldTypeNamesForGroup(KDbField::TypeGroup typeGroup) { return KDb_typeCache->nlist.value(typeGroup); } QStringList KDb::fieldTypeStringsForGroup(KDbField::TypeGroup typeGroup) { return KDb_typeCache->slist.value(typeGroup); } KDbField::Type KDb::defaultFieldTypeForGroup(KDbField::TypeGroup typeGroup) { return (typeGroup <= KDbField::LastTypeGroup) ? KDb_typeCache->def_tlist.value(typeGroup) : KDbField::InvalidType; } void KDb::getHTMLErrorMesage(const KDbResultable& resultable, QString *msg, QString *details) { Q_ASSERT(msg); Q_ASSERT(details); const KDbResult result(resultable.result()); if (!result.isError()) return; //lower level message is added to the details, if there is alread message specified if (!result.messageTitle().isEmpty()) *msg += QLatin1String("

") + result.messageTitle(); if (msg->isEmpty()) *msg = QLatin1String("

") + result.message(); else *details += QLatin1String("

") + result.message(); if (!result.serverMessage().isEmpty()) *details += QLatin1String("

") + kdb::tr("Message from server:") + QLatin1String(" ") + result.serverMessage(); if (!result.recentSqlString().isEmpty()) *details += QLatin1String("

") + kdb::tr("SQL statement:") + QString::fromLatin1(" %1").arg(result.recentSqlString().toString()); int serverErrorCode = 0; QString serverResultName; if (result.isError()) { serverErrorCode = result.serverErrorCode(); serverResultName = resultable.serverResultName(); } if ( !details->isEmpty() && ( !result.serverMessage().isEmpty() || !result.recentSqlString().isEmpty() || !serverResultName.isEmpty() || serverErrorCode != 0) ) { *details += (QLatin1String("

") + kdb::tr("Server result code:") + QLatin1String(" ") + QString::number(serverErrorCode)); if (!serverResultName.isEmpty()) { *details += QString::fromLatin1(" (%1)").arg(serverResultName); } } else { if (!serverResultName.isEmpty()) { *details += (QLatin1String("

") + kdb::tr("Server result:") + QLatin1String(" ") + serverResultName); } } if (!details->isEmpty() && !details->startsWith(QLatin1String(""))) { if (!details->startsWith(QLatin1String("

"))) details->prepend(QLatin1String("

")); } } void KDb::getHTMLErrorMesage(const KDbResultable& resultable, QString *msg) { Q_ASSERT(msg); getHTMLErrorMesage(resultable, msg, msg); } void KDb::getHTMLErrorMesage(const KDbResultable& resultable, KDbResultInfo *info) { Q_ASSERT(info); getHTMLErrorMesage(resultable, &info->message, &info->description); } tristate KDb::idForObjectName(KDbConnection* conn, int *id, const QString& objName, int objType) { Q_ASSERT(conn); Q_ASSERT(id); return conn->querySingleNumber( KDbEscapedString("SELECT o_id FROM kexi__objects WHERE o_name=%1 AND o_type=%2") .arg(conn->escapeString(objName)).arg(objType), id); } //----------------------------------------- void KDb::connectionTestDialog(QWidget* parent, const KDbConnectionData& data, KDbMessageHandler* msgHandler) { ConnectionTestDialog dlg(data, msgHandler, parent); dlg.exec(); } int KDb::recordCount(KDbConnection* conn, const KDbEscapedString& sql) { int count = -1; //will be changed only on success of querySingleNumber() conn->querySingleNumber(KDbEscapedString("SELECT COUNT() FROM (") + sql + ") AS kdb__subquery", &count); return count; } int KDb::recordCount(const KDbTableSchema& tableSchema) { //! @todo does not work with non-SQL data sources if (!tableSchema.connection()) { kdbWarning() << "no tableSchema.connection()"; return -1; } int count = -1; //will be changed only on success of querySingleNumber() tableSchema.connection()->querySingleNumber( KDbEscapedString("SELECT COUNT(*) FROM ") + tableSchema.connection()->escapeIdentifier(tableSchema.name()), &count ); return count; } int KDb::recordCount(KDbQuerySchema* querySchema, const QList& params) { //! @todo does not work with non-SQL data sources if (!querySchema->connection()) { kdbWarning() << "no querySchema->connection()"; return -1; } int count = -1; //will be changed only on success of querySingleNumber() KDbNativeStatementBuilder builder(querySchema->connection()); KDbEscapedString subSql; if (!builder.generateSelectStatement(&subSql, querySchema, params)) { return -1; } tristate result = querySchema->connection()->querySingleNumber( KDbEscapedString("SELECT COUNT(*) FROM (") + subSql + ") AS kdb__subquery", &count ); return true == result ? count : -1; } int KDb::recordCount(KDbTableOrQuerySchema* tableOrQuery, const QList& params) { if (tableOrQuery->table()) return recordCount(*tableOrQuery->table()); if (tableOrQuery->query()) return recordCount(tableOrQuery->query(), params); return -1; } int KDb::fieldCount(KDbTableOrQuerySchema* tableOrQuery) { if (tableOrQuery->table()) return tableOrQuery->table()->fieldCount(); if (tableOrQuery->query()) return tableOrQuery->query()->fieldsExpanded().count(); return -1; } bool KDb::splitToTableAndFieldParts(const QString& string, QString *tableName, QString *fieldName, SplitToTableAndFieldPartsOptions option) { Q_ASSERT(tableName); Q_ASSERT(fieldName); const int id = string.indexOf(QLatin1Char('.')); if (option & SetFieldNameIfNoTableName && id == -1) { tableName->clear(); *fieldName = string; return !fieldName->isEmpty(); } if (id <= 0 || id == int(string.length() - 1)) return false; *tableName = string.left(id); *fieldName = string.mid(id + 1); return !tableName->isEmpty() && !fieldName->isEmpty(); } bool KDb::supportsVisibleDecimalPlacesProperty(KDbField::Type type) { //! @todo add check for decimal type as well return KDbField::isFPNumericType(type); } inline static QString numberToString(double value, int decimalPlaces, const QLocale *locale) { //! @todo round? QString result; if (decimalPlaces == 0) { result = locale ? locale->toString(qlonglong(value)) : QString::number(qlonglong(value)); } else { const int realDecimalPlaces = decimalPlaces < 0 ? 10 : decimalPlaces; result = locale ? locale->toString(value, 'f', realDecimalPlaces) : QString::number(value, 'f', realDecimalPlaces); if (decimalPlaces < 0) { // cut off zeros int i = result.length() - 1; while (i > 0 && result[i] == QLatin1Char('0')) { i--; } if (result[i].isDigit()) {// last digit ++i; } result.truncate(i); } } return result; } QString KDb::numberToString(double value, int decimalPlaces) { return ::numberToString(value, decimalPlaces, nullptr); } QString KDb::numberToLocaleString(double value, int decimalPlaces, const QLocale *locale) { if (locale) { return ::numberToString(value, decimalPlaces, locale); } QLocale defaultLocale; return ::numberToString(value, decimalPlaces, &defaultLocale); } KDbField::Type KDb::intToFieldType(int type) { if (type < int(KDbField::InvalidType) || type > int(KDbField::LastType)) { kdbWarning() << "invalid type" << type; return KDbField::InvalidType; } return static_cast(type); } KDbField::TypeGroup KDb::intToFieldTypeGroup(int typeGroup) { if (typeGroup < int(KDbField::InvalidGroup) || typeGroup > int(KDbField::LastTypeGroup)) { kdbWarning() << "invalid type group" << typeGroup; return KDbField::InvalidGroup; } return static_cast(typeGroup); } static bool setIntToFieldType(KDbField *field, const QVariant& value) { Q_ASSERT(field); bool ok; const int intType = value.toInt(&ok); if (!ok || KDbField::InvalidType == KDb::intToFieldType(intType)) {//for sanity kdbWarning() << "invalid type"; return false; } field->setType((KDbField::Type)intType); return true; } //! @internal for KDb::isBuiltinTableFieldProperty() struct KDb_BuiltinFieldProperties { KDb_BuiltinFieldProperties() { #define ADD(name) set.insert(name) ADD("type"); ADD("primaryKey"); ADD("indexed"); ADD("autoIncrement"); ADD("unique"); ADD("notNull"); ADD("allowEmpty"); ADD("unsigned"); ADD("name"); ADD("caption"); ADD("description"); ADD("maxLength"); ADD("maxLengthIsDefault"); ADD("precision"); ADD("defaultValue"); ADD("defaultWidth"); ADD("visibleDecimalPlaces"); //! @todo always update this when new builtins appear! #undef ADD } QSet set; }; //! for KDb::isBuiltinTableFieldProperty() Q_GLOBAL_STATIC(KDb_BuiltinFieldProperties, KDb_builtinFieldProperties) bool KDb::isBuiltinTableFieldProperty(const QByteArray& propertyName) { return KDb_builtinFieldProperties->set.contains(propertyName); } static QVariant visibleColumnValue(const KDbLookupFieldSchema *lookup) { if (!lookup || lookup->visibleColumns().count() == 1) { if (lookup) { const QList visibleColumns = lookup->visibleColumns(); if (!visibleColumns.isEmpty()) { return visibleColumns.first(); } } return QVariant(); } QList variantList; const QList visibleColumns(lookup->visibleColumns()); for(int column : visibleColumns) { variantList.append(column); } return variantList; } void KDb::getProperties(const KDbLookupFieldSchema *lookup, QMap *values) { Q_ASSERT(values); KDbLookupFieldSchemaRecordSource recordSource; if (lookup) { recordSource = lookup->recordSource(); } values->insert("rowSource", lookup ? recordSource.name() : QVariant()); values->insert("rowSourceType", lookup ? recordSource.typeName() : QVariant()); values->insert("rowSourceValues", (lookup && !recordSource.values().isEmpty()) ? recordSource.values() : QVariant()); values->insert("boundColumn", lookup ? lookup->boundColumn() : QVariant()); values->insert("visibleColumn", visibleColumnValue(lookup)); QList variantList; if (lookup) { const QList columnWidths = lookup->columnWidths(); for(const QVariant& variant : columnWidths) { variantList.append(variant); } } values->insert("columnWidths", lookup ? variantList : QVariant()); values->insert("showColumnHeaders", lookup ? lookup->columnHeadersVisible() : QVariant()); values->insert("listRows", lookup ? lookup->maxVisibleRecords() : QVariant()); values->insert("limitToList", lookup ? lookup->limitToList() : QVariant()); values->insert("displayWidget", lookup ? int(lookup->displayWidget()) : QVariant()); } void KDb::getFieldProperties(const KDbField &field, QMap *values) { Q_ASSERT(values); values->clear(); // normal values values->insert("type", field.type()); const KDbField::Constraints constraints = field.constraints(); values->insert("primaryKey", constraints.testFlag(KDbField::PrimaryKey)); values->insert("indexed", constraints.testFlag(KDbField::Indexed)); values->insert("autoIncrement", KDbField::isAutoIncrementAllowed(field.type()) && constraints.testFlag(KDbField::AutoInc)); values->insert("unique", constraints.testFlag(KDbField::Unique)); values->insert("notNull", constraints.testFlag(KDbField::NotNull)); values->insert("allowEmpty", !constraints.testFlag(KDbField::NotEmpty)); const KDbField::Options options = field.options(); values->insert("unsigned", options.testFlag(KDbField::Unsigned)); values->insert("name", field.name()); values->insert("caption", field.caption()); values->insert("description", field.description()); values->insert("maxLength", field.maxLength()); values->insert("maxLengthIsDefault", field.maxLengthStrategy() & KDbField::DefaultMaxLength); values->insert("precision", field.precision()); values->insert("defaultValue", field.defaultValue()); //! @todo IMPORTANT: values->insert("defaultWidth", field.defaultWidth()); if (KDb::supportsVisibleDecimalPlacesProperty(field.type())) { values->insert("visibleDecimalPlaces", field.defaultValue()); } // insert lookup-related values KDbLookupFieldSchema *lookup = field.table()->lookupFieldSchema(field); KDb::getProperties(lookup, values); } static bool containsLookupFieldSchemaProperties(const QMap& values) { for (QMap::ConstIterator it(values.constBegin()); it != values.constEnd(); ++it) { if (KDb::isLookupFieldSchemaProperty(it.key())) { return true; } } return false; } bool KDb::setFieldProperties(KDbField *field, const QMap& values) { Q_ASSERT(field); QMap::ConstIterator it; if ((it = values.find("type")) != values.constEnd()) { if (!setIntToFieldType(field, *it)) return false; } #define SET_BOOLEAN_FLAG(flag, value) { \ constraints |= KDbField::flag; \ if (!value) \ constraints ^= KDbField::flag; \ } KDbField::Constraints constraints = field->constraints(); bool ok = true; if ((it = values.find("primaryKey")) != values.constEnd()) SET_BOOLEAN_FLAG(PrimaryKey, (*it).toBool()); if ((it = values.find("indexed")) != values.constEnd()) SET_BOOLEAN_FLAG(Indexed, (*it).toBool()); if ((it = values.find("autoIncrement")) != values.constEnd() && KDbField::isAutoIncrementAllowed(field->type())) SET_BOOLEAN_FLAG(AutoInc, (*it).toBool()); if ((it = values.find("unique")) != values.constEnd()) SET_BOOLEAN_FLAG(Unique, (*it).toBool()); if ((it = values.find("notNull")) != values.constEnd()) SET_BOOLEAN_FLAG(NotNull, (*it).toBool()); if ((it = values.find("allowEmpty")) != values.constEnd()) SET_BOOLEAN_FLAG(NotEmpty, !(*it).toBool()); field->setConstraints(constraints); KDbField::Options options; if ((it = values.find("unsigned")) != values.constEnd()) { options |= KDbField::Unsigned; if (!(*it).toBool()) options ^= KDbField::Unsigned; } field->setOptions(options); if ((it = values.find("name")) != values.constEnd()) field->setName((*it).toString()); if ((it = values.find("caption")) != values.constEnd()) field->setCaption((*it).toString()); if ((it = values.find("description")) != values.constEnd()) field->setDescription((*it).toString()); if ((it = values.find("maxLength")) != values.constEnd()) field->setMaxLength((*it).isNull() ? 0/*default*/ : (*it).toInt(&ok)); if (!ok) return false; if ((it = values.find("maxLengthIsDefault")) != values.constEnd() && (*it).toBool()) { field->setMaxLengthStrategy(KDbField::DefaultMaxLength); } if ((it = values.find("precision")) != values.constEnd()) field->setPrecision((*it).isNull() ? 0/*default*/ : (*it).toInt(&ok)); if (!ok) return false; if ((it = values.find("defaultValue")) != values.constEnd()) field->setDefaultValue(*it); //! @todo IMPORTANT: defaultWidth #if 0 if ((it = values.find("defaultWidth")) != values.constEnd()) field.setDefaultWidth((*it).isNull() ? 0/*default*/ : (*it).toInt(&ok)); if (!ok) return false; #endif // -- extended properties if ((it = values.find("visibleDecimalPlaces")) != values.constEnd() && KDb::supportsVisibleDecimalPlacesProperty(field->type())) field->setVisibleDecimalPlaces((*it).isNull() ? -1/*default*/ : (*it).toInt(&ok)); if (!ok) return false; if (field->table() && containsLookupFieldSchemaProperties(values)) { KDbLookupFieldSchema *lookup = field->table()->lookupFieldSchema(*field); QScopedPointer createdLookup; if (!lookup) { // create lookup if needed createdLookup.reset(lookup = new KDbLookupFieldSchema()); } if (lookup->setProperties(values)) { if (createdLookup) { if (field->table()->setLookupFieldSchema(field->name(), lookup)) { createdLookup.take(); // ownership passed lookup = nullptr; } } } } return true; #undef SET_BOOLEAN_FLAG } //! @internal for isExtendedTableProperty() struct KDb_ExtendedProperties { KDb_ExtendedProperties() { #define ADD(name) set.insert( name ) ADD("visibledecimalplaces"); ADD("rowsource"); ADD("rowsourcetype"); ADD("rowsourcevalues"); ADD("boundcolumn"); ADD("visiblecolumn"); ADD("columnwidths"); ADD("showcolumnheaders"); ADD("listrows"); ADD("limittolist"); ADD("displaywidget"); #undef ADD } QSet set; }; //! for isExtendedTableProperty() Q_GLOBAL_STATIC(KDb_ExtendedProperties, KDb_extendedProperties) bool KDb::isExtendedTableFieldProperty(const QByteArray& propertyName) { return KDb_extendedProperties->set.contains(QByteArray(propertyName).toLower()); } //! @internal for isLookupFieldSchemaProperty() struct KDb_LookupFieldSchemaProperties { KDb_LookupFieldSchemaProperties() { QMap tmp; KDb::getProperties(nullptr, &tmp); for (QMap::ConstIterator it(tmp.constBegin()); it != tmp.constEnd(); ++it) { set.insert(it.key().toLower()); } } QSet set; }; //! for isLookupFieldSchemaProperty() Q_GLOBAL_STATIC(KDb_LookupFieldSchemaProperties, KDb_lookupFieldSchemaProperties) bool KDb::isLookupFieldSchemaProperty(const QByteArray& propertyName) { return KDb_lookupFieldSchemaProperties->set.contains(propertyName.toLower()); } bool KDb::setFieldProperty(KDbField *field, const QByteArray& propertyName, const QVariant& value) { Q_ASSERT(field); #define SET_BOOLEAN_FLAG(flag, value) { \ constraints |= KDbField::flag; \ if (!value) \ constraints ^= KDbField::flag; \ field->setConstraints( constraints ); \ return true; \ } #define GET_INT(method) { \ const int ival = value.toInt(&ok); \ if (!ok) \ return false; \ field->method( ival ); \ return true; \ } if (propertyName.isEmpty()) return false; bool ok; if (KDb::isExtendedTableFieldProperty(propertyName)) { //a little speedup: identify extended property in O(1) if ("visibleDecimalPlaces" == propertyName && KDb::supportsVisibleDecimalPlacesProperty(field->type())) { GET_INT(setVisibleDecimalPlaces); } else if (KDb::isLookupFieldSchemaProperty(propertyName)) { if (!field->table()) { kdbWarning() << "Could not set" << propertyName << "property - no table assigned for field"; } else { KDbLookupFieldSchema *lookup = field->table()->lookupFieldSchema(*field); const bool createLookup = !lookup; if (createLookup) // create lookup if needed lookup = new KDbLookupFieldSchema(); if (lookup->setProperty(propertyName, value)) { if (createLookup) field->table()->setLookupFieldSchema(field->name(), lookup); return true; } if (createLookup) delete lookup; // not set, delete } } } else {//non-extended if ("type" == propertyName) return setIntToFieldType(field, value); KDbField::Constraints constraints = field->constraints(); if ("primaryKey" == propertyName) SET_BOOLEAN_FLAG(PrimaryKey, value.toBool()); if ("indexed" == propertyName) SET_BOOLEAN_FLAG(Indexed, value.toBool()); if ("autoIncrement" == propertyName && KDbField::isAutoIncrementAllowed(field->type())) SET_BOOLEAN_FLAG(AutoInc, value.toBool()); if ("unique" == propertyName) SET_BOOLEAN_FLAG(Unique, value.toBool()); if ("notNull" == propertyName) SET_BOOLEAN_FLAG(NotNull, value.toBool()); if ("allowEmpty" == propertyName) SET_BOOLEAN_FLAG(NotEmpty, !value.toBool()); KDbField::Options options; if ("unsigned" == propertyName) { options |= KDbField::Unsigned; if (!value.toBool()) options ^= KDbField::Unsigned; field->setOptions(options); return true; } if ("name" == propertyName) { if (value.toString().isEmpty()) return false; field->setName(value.toString()); return true; } if ("caption" == propertyName) { field->setCaption(value.toString()); return true; } if ("description" == propertyName) { field->setDescription(value.toString()); return true; } if ("maxLength" == propertyName) GET_INT(setMaxLength); if ("maxLengthIsDefault" == propertyName) { field->setMaxLengthStrategy(KDbField::DefaultMaxLength); } if ("precision" == propertyName) GET_INT(setPrecision); if ("defaultValue" == propertyName) { field->setDefaultValue(value); return true; } //! @todo IMPORTANT: defaultWidth #if 0 if ("defaultWidth" == propertyName) GET_INT(setDefaultWidth); #endif // last chance that never fails: custom field property field->setCustomProperty(propertyName, value); } kdbWarning() << "property" << propertyName << "not found!"; return false; #undef SET_BOOLEAN_FLAG #undef GET_INT } int KDb::loadIntPropertyValueFromDom(const QDomNode& node, bool* ok) { QByteArray valueType = node.nodeName().toLatin1(); if (valueType.isEmpty() || valueType != "number") { if (ok) *ok = false; return 0; } const QString text(QDomNode(node).toElement().text()); int val = text.toInt(ok); return val; } QString KDb::loadStringPropertyValueFromDom(const QDomNode& node, bool* ok) { QByteArray valueType = node.nodeName().toLatin1(); if (valueType != "string") { if (ok) *ok = false; return QString(); } if (ok) *ok = true; return QDomNode(node).toElement().text(); } QVariant KDb::loadPropertyValueFromDom(const QDomNode& node, bool* ok) { QByteArray valueType = node.nodeName().toLatin1(); if (valueType.isEmpty()) { if (ok) *ok = false; return QVariant(); } if (ok) *ok = true; const QString text(QDomNode(node).toElement().text()); bool _ok; if (valueType == "string") { return text; } else if (valueType == "cstring") { return text.toLatin1(); } else if (valueType == "number") { // integer or double if (text.indexOf(QLatin1Char('.')) != -1) { double val = text.toDouble(&_ok); if (_ok) return val; } else { const int val = text.toInt(&_ok); if (_ok) return val; const qint64 valLong = text.toLongLong(&_ok); if (_ok) return valLong; } } else if (valueType == "bool") { return text.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0 || text == QLatin1String("1"); } else { //! @todo add more QVariant types kdbWarning() << "KDb::loadPropertyValueFromDom(): unknown type '" << valueType << "'"; } if (ok) *ok = false; return QVariant(); } QDomElement KDb::saveNumberElementToDom(QDomDocument *doc, QDomElement *parentEl, const QString& elementName, int value) { Q_ASSERT(doc); Q_ASSERT(parentEl); QDomElement el(doc->createElement(elementName)); parentEl->appendChild(el); QDomElement numberEl(doc->createElement(QLatin1String("number"))); el.appendChild(numberEl); numberEl.appendChild(doc->createTextNode(QString::number(value))); return el; } QDomElement KDb::saveBooleanElementToDom(QDomDocument *doc, QDomElement *parentEl, const QString& elementName, bool value) { Q_ASSERT(doc); Q_ASSERT(parentEl); QDomElement el(doc->createElement(elementName)); parentEl->appendChild(el); QDomElement numberEl(doc->createElement(QLatin1String("bool"))); el.appendChild(numberEl); numberEl.appendChild(doc->createTextNode( value ? QLatin1String("true") : QLatin1String("false"))); return el; } //! @internal Used in KDb::emptyValueForFieldType() struct KDb_EmptyValueForFieldTypeCache { KDb_EmptyValueForFieldTypeCache() : values(int(KDbField::LastType) + 1) { #define ADD(t, value) values.insert(t, value); ADD(KDbField::Byte, 0); ADD(KDbField::ShortInteger, 0); ADD(KDbField::Integer, 0); ADD(KDbField::BigInteger, 0); ADD(KDbField::Boolean, false); ADD(KDbField::Float, 0.0); ADD(KDbField::Double, 0.0); //! @todo ok? we have no better defaults ADD(KDbField::Text, QLatin1String(" ")); ADD(KDbField::LongText, QLatin1String(" ")); ADD(KDbField::BLOB, QByteArray()); #undef ADD } QVector values; }; //! Used in KDb::emptyValueForFieldType() Q_GLOBAL_STATIC(KDb_EmptyValueForFieldTypeCache, KDb_emptyValueForFieldTypeCache) QVariant KDb::emptyValueForFieldType(KDbField::Type type) { const QVariant val(KDb_emptyValueForFieldTypeCache->values.at( (type <= KDbField::LastType) ? type : KDbField::InvalidType)); if (!val.isNull()) return val; else { //special cases if (type == KDbField::Date) return QDate::currentDate(); if (type == KDbField::DateTime) return QDateTime::currentDateTime(); if (type == KDbField::Time) return QTime::currentTime(); } kdbWarning() << "no value for type" << KDbField::typeName(type); return QVariant(); } //! @internal Used in KDb::notEmptyValueForFieldType() struct KDb_NotEmptyValueForFieldTypeCache { KDb_NotEmptyValueForFieldTypeCache() : values(int(KDbField::LastType) + 1) { #define ADD(t, value) values.insert(t, value); // copy most of the values for (int i = int(KDbField::InvalidType) + 1; i <= KDbField::LastType; i++) { if (i == KDbField::Date || i == KDbField::DateTime || i == KDbField::Time) continue; //'current' value will be returned if (i == KDbField::Text || i == KDbField::LongText) { ADD(i, QVariant(QLatin1String(""))); continue; } if (i == KDbField::BLOB) { //! @todo blobs will contain other MIME types too QByteArray ba; //! @todo port to Qt4 #if 0 QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); QPixmap pm(SmallIcon("document-new")); pm.save(&buffer, "PNG"/*! @todo default? */); #endif ADD(i, ba); continue; } ADD(i, KDb::emptyValueForFieldType((KDbField::Type)i)); } #undef ADD } QVector values; }; //! Used in KDb::notEmptyValueForFieldType() Q_GLOBAL_STATIC(KDb_NotEmptyValueForFieldTypeCache, KDb_notEmptyValueForFieldTypeCache) QVariant KDb::notEmptyValueForFieldType(KDbField::Type type) { const QVariant val(KDb_notEmptyValueForFieldTypeCache->values.at( (type <= KDbField::LastType) ? type : KDbField::InvalidType)); if (!val.isNull()) return val; else { //special cases if (type == KDbField::Date) return QDate::currentDate(); if (type == KDbField::DateTime) return QDateTime::currentDateTime(); if (type == KDbField::Time) return QTime::currentTime(); } kdbWarning() << "no value for type" << KDbField::typeName(type); return QVariant(); } //! @internal @return nestimated new length after escaping of string @a string template inline static int estimatedNewLength(const T &string, bool addQuotes) { if (string.length() < 10) return string.length() * 2 + (addQuotes ? 2 : 0); return string.length() * 3 / 2; } //! @internal @return @a string string with applied KDbSQL identifier escaping. //! If @a addQuotes is true, '"' characer is prepended and appended. template inline static T escapeIdentifier(const T& string, bool addQuotes) { const Latin1CharType quote('"'); // create Latin1StringType escapedQuote("\"\""); T newString; newString.reserve(estimatedNewLength(string, addQuotes)); if (addQuotes) { newString.append(quote); } for (int i = 0; i < string.length(); i++) { const CharType c = string.at(i); if (c == quote) newString.append(escapedQuote); else newString.append(c); } if (addQuotes) { newString.append(quote); } newString.squeeze(); return newString; } QString KDb::escapeIdentifier(const QString& string) { return ::escapeIdentifier(string, false); } QByteArray KDb::escapeIdentifier(const QByteArray& string) { return ::escapeIdentifier(string, false); } QString KDb::escapeIdentifierAndAddQuotes(const QString& string) { return ::escapeIdentifier(string, true); } QByteArray KDb::escapeIdentifierAndAddQuotes(const QByteArray& string) { return ::escapeIdentifier(string, true); } QString KDb::escapeString(const QString& string) { const QLatin1Char quote('\''); // find out the length ot the destination string // create QString newString(quote); newString.reserve(estimatedNewLength(string, true)); for (int i = 0; i < string.length(); i++) { const QChar c = string.at(i); const ushort unicode = c.unicode(); if (unicode == quote) newString.append(QLatin1String("''")); else if (unicode == '\t') newString.append(QLatin1String("\\t")); else if (unicode == '\\') newString.append(QLatin1String("\\\\")); else if (unicode == '\n') newString.append(QLatin1String("\\n")); else if (unicode == '\r') newString.append(QLatin1String("\\r")); else if (unicode == '\0') newString.append(QLatin1String("\\0")); else newString.append(c); } newString.append(QLatin1Char(quote)); return newString; } //! @see handleHex() const int CODE_POINT_DIGITS = std::numeric_limits::max(); //! @see handleHex() const int MAX_CODE_POINT_VALUE = 0x10FFFF; //! @internal Decodes hex of length @a digits for handleXhh(), handleUxxxx() and handleUcodePoint() //! If @a digits is CODE_POINT_DIGITS, any number of hex digits is decoded until '}' character //! is found (error if not found), and the function succeeds when the resulting number //! is not larger than MAX_CODE_POINT_VALUE. //! If @a digits is smaller than CODE_POINT_DIGITS the function succeeds only if exactly @a digits //! number of digits has been found. //! @return -1 on error (when invalid character found or on missing character //! or if the resulting number is too large) //! @see KDb::unescapeString() static int handleHex(QString *result, int *from, int stringLen, int *errorPosition, int digits) { int digit = 0; for (int i=0; i= stringLen) { // unfinished if (errorPosition) { *errorPosition = *from; } return -1; } ++(*from); if (digits == CODE_POINT_DIGITS && (*result)[*from] == QLatin1Char('}')) { // special case: code point character decoded if (i == 0) { if (errorPosition) { *errorPosition = *from; } return -1; } return digit; } const unsigned char d = hexDigitToInt((*result)[*from].toLatin1()); if (d == 0xFF) { // unfinished or wrong character if (errorPosition) { *errorPosition = *from; } return -1; } digit = (digit << 4) + d; if (digits == CODE_POINT_DIGITS) { if (digit > MAX_CODE_POINT_VALUE) { // special case: exceeded limit of code point if (errorPosition) { *errorPosition = *from; } return -1; } } } return digit; } //! @internal Handles \xhh format for handleEscape() //! Assumption: the @a *from points to "x" in the "\x" //! @see KDb::unescapeString() static bool handleXhh(QString *result, int *from, int to, int stringLen, int *errorPosition) { const int intDigit = handleHex(result, from, stringLen, errorPosition, 2); if (intDigit == -1) { return false; } (*result)[to] = QChar(static_cast(intDigit), 0); return true; } //! @internal Handles \uxxxx format for handleEscape() //! Assumption: the @a *from points to the "u" in the "\u". //! @see KDb::unescapeString() static bool handleUxxxx(QString *result, int *from, int to, int stringLen, int *errorPosition) { const int intDigit = handleHex(result, from, stringLen, errorPosition, 4); if (intDigit == -1) { return false; } (*result)[to] = QChar(static_cast(intDigit)); return true; } //! @internal Handles \u{xxxxxx} format for handleEscape() //! Assumption: the @a *from points to the "{" in the "\u{". //! @see KDb::unescapeString() static bool handleUcodePoint(QString *result, int *from, int to, int stringLen, int *errorPosition) { const int intDigit = handleHex(result, from, stringLen, errorPosition, CODE_POINT_DIGITS); if (intDigit == -1) { return false; } (*result)[to] = QChar(intDigit); return true; } //! @internal Handles escaped character @a c2 for KDb::unescapeString() //! Updates @a result //! @return true on success static bool handleEscape(QString *result, int *from, int *to, int stringLen, int *errorPosition) { const QCharRef c2 = (*result)[*from]; if (c2 == QLatin1Char('x')) { // \xhh if (!handleXhh(result, from, *to, stringLen, errorPosition)) { return false; } } else if (c2 == QLatin1Char('u')) { // \u if ((*from + 1) >= stringLen) { // unfinished if (errorPosition) { *errorPosition = *from; } return false; } ++(*from); const QCharRef c3 = (*result)[*from]; if (c3 == QLatin1Char('{')) { // \u{ if (!handleUcodePoint(result, from, *to, stringLen, errorPosition)) { return false; } } else { --(*from); if (!handleUxxxx(result, from, *to, stringLen, errorPosition)) { return false; } } #define _RULE(in, out) \ } else if (c2 == QLatin1Char(in)) { \ (*result)[*to] = QLatin1Char(out); _RULE('0', '\0') _RULE('b', '\b') _RULE('f', '\f') _RULE('n', '\n') _RULE('r', '\r') _RULE('t', '\t') _RULE('v', '\v') #undef _RULE } else { // \ ' " ? % _ and any other without special meaning can be escaped: just skip "\" (*result)[*to] = c2; } return true; } QString KDb::unescapeString(const QString& string, char quote, int *errorPosition) { if (quote != '\'' && quote != '\"') { if (errorPosition) { *errorPosition = 0; } return QString(); } const QLatin1Char quoteChar(quote); if (string.isEmpty() || (!string.contains(QLatin1Char('\\')) && !string.contains(quoteChar))) { if (errorPosition) { *errorPosition = -1; } return string; // optimization: there are no escapes and quotes } QString result(string); const int stringLen = string.length(); int from = 0; int to = 0; bool doubleQuoteExpected = false; while (from < stringLen) { const QCharRef c = result[from]; if (doubleQuoteExpected) { if (c == quoteChar) { result[to] = c; doubleQuoteExpected = false; } else { // error: missing second quote if (errorPosition) { *errorPosition = from - 1; // -1 because error is at prev. char } return QString(); } } else if (c == quoteChar) { doubleQuoteExpected = true; ++from; continue; } else if (c == QLatin1Char('\\')) { // escaping if ((from + 1) >= stringLen) { // ignore unfinished '\' break; } ++from; if (!handleEscape(&result, &from, &to, stringLen, errorPosition)) { return QString(); } } else { // normal character: skip result[to] = result[from]; } ++from; ++to; } if (doubleQuoteExpected) { // error: string ends with a single quote if (errorPosition) { *errorPosition = from - 1; } return QString(); } if (errorPosition) { *errorPosition = -1; } result.truncate(to); return result; } //! @return hex digit '0'..'F' for integer number 0..15 inline static char intToHexDigit(unsigned char val) { return (val < 10) ? ('0' + val) : ('A' + (val - 10)); } QString KDb::escapeBLOB(const QByteArray& array, BLOBEscapingType type) { const int size = array.size(); if (size == 0 && type == BLOBEscape0xHex) return QString(); int escaped_length = size * 2; if (type == BLOBEscape0xHex || type == BLOBEscapeOctal) escaped_length += 2/*0x or X'*/; else if (type == BLOBEscapeXHex) escaped_length += 3; //X' + ' else if (type == BLOBEscapeByteaHex) escaped_length += (4 + 8); // E'\x + '::bytea QString str; str.reserve(escaped_length); if (str.capacity() < escaped_length) { kdbWarning() << "no enough memory (cannot allocate" << escaped_length << "chars)"; return QString(); } if (type == BLOBEscapeXHex) str = QString::fromLatin1("X'"); else if (type == BLOBEscape0xHex) str = QString::fromLatin1("0x"); else if (type == BLOBEscapeOctal) str = QString::fromLatin1("'"); else if (type == BLOBEscapeByteaHex) str = QString::fromLatin1("E'\\\\x"); int new_length = str.length(); //after X' or 0x, etc. if (type == BLOBEscapeOctal) { // only escape nonprintable characters as in Table 8-7: // http://www.postgresql.org/docs/8.1/interactive/datatype-binary.html // i.e. escape for bytes: < 32, >= 127, 39 ('), 92(\). for (int i = 0; i < size; i++) { const unsigned char val = array[i]; if (val < 32 || val >= 127 || val == 39 || val == 92) { str[new_length++] = '\\'; str[new_length++] = '\\'; str[new_length++] = '0' + val / 64; str[new_length++] = '0' + (val % 64) / 8; str[new_length++] = '0' + val % 8; } else { str[new_length++] = val; } } } else { for (int i = 0; i < size; i++) { const unsigned char val = array[i]; str[new_length++] = intToHexDigit(val / 16); str[new_length++] = intToHexDigit(val % 16); } } if (type == BLOBEscapeXHex || type == BLOBEscapeOctal) { str[new_length++] = '\''; } else if (type == BLOBEscapeByteaHex) { str[new_length++] = '\''; str[new_length++] = ':'; str[new_length++] = ':'; str[new_length++] = 'b'; str[new_length++] = 'y'; str[new_length++] = 't'; str[new_length++] = 'e'; str[new_length++] = 'a'; } return str; } QByteArray KDb::pgsqlByteaToByteArray(const char* data, int length) { if (!data) { return QByteArray(); } QByteArray array; int output = 0; if (length < 0) { length = qstrlen(data); } for (int pass = 0; pass < 2; pass++) {//2 passes to avoid allocating buffer twice: // 0: count #of chars; 1: copy data const char* s = data; const char* end = s + length; if (pass == 1) { //kdbDebug() << "processBinaryData(): real size == " << output; array.resize(output); output = 0; } for (int input = 0; s < end; output++) { // kdbDebug()<<(int)s[0]<<" "<<(int)s[1]<<" "<<(int)s[2]<<" "<<(int)s[3]<<" "<<(int)s[4]; if (s[0] == '\\' && (s + 1) < end) { //special cases as in http://www.postgresql.org/docs/8.1/interactive/datatype-binary.html if (s[1] == '\'') {// \' if (pass == 1) array[output] = '\''; s += 2; } else if (s[1] == '\\') { // 2 backslashes if (pass == 1) array[output] = '\\'; s += 2; } else if ((input + 3) < length) {// \\xyz where xyz are 3 octal digits if (pass == 1) array[output] = char((int(s[1] - '0') * 8 + int(s[2] - '0')) * 8 + int(s[3] - '0')); s += 4; } else { kdbWarning() << "no octal value after backslash"; s++; } } else { if (pass == 1) array[output] = s[0]; s++; } // kdbDebug()< KDb::stringListToIntList(const QStringList &list, bool *ok) { QList result; foreach (const QString &item, list) { int val = item.toInt(ok); if (ok && !*ok) { return QList(); } result.append(val); } if (ok) { *ok = true; } return result; } // Based on KConfigGroupPrivate::serializeList() from kconfiggroup.cpp (kdelibs 4) QString KDb::serializeList(const QStringList &list) { QString value; if (!list.isEmpty()) { QStringList::ConstIterator it = list.constBegin(); const QStringList::ConstIterator end = list.constEnd(); value = QString(*it).replace(QLatin1Char('\\'), QLatin1String("\\\\")) .replace(QLatin1Char(','), QLatin1String("\\,")); while (++it != end) { // In the loop, so it is not done when there is only one element. // Doing it repeatedly is a pretty cheap operation. value.reserve(4096); value += QLatin1Char(',') + QString(*it).replace(QLatin1Char('\\'), QLatin1String("\\\\")) .replace(QLatin1Char(','), QLatin1String("\\,")); } // To be able to distinguish an empty list from a list with one empty element. if (value.isEmpty()) value = QLatin1String("\\0"); } return value; } // Based on KConfigGroupPrivate::deserializeList() from kconfiggroup.cpp (kdelibs 4) QStringList KDb::deserializeList(const QString &data) { if (data.isEmpty()) return QStringList(); if (data == QLatin1String("\\0")) return QStringList(QString()); QStringList value; QString val; val.reserve(data.size()); bool quoted = false; for (int p = 0; p < data.length(); p++) { if (quoted) { val += data[p]; quoted = false; } else if (data[p].unicode() == QLatin1Char('\\')) { quoted = true; } else if (data[p].unicode() == QLatin1Char(',')) { val.squeeze(); // release any unused memory value.append(val); val.clear(); val.reserve(data.size() - p); } else { val += data[p]; } } value.append(val); return value; } QList KDb::deserializeIntList(const QString &data, bool *ok) { return KDb::stringListToIntList( KDb::deserializeList(data), ok); } QString KDb::variantToString(const QVariant& v) { if (v.type() == QVariant::ByteArray) { return KDb::escapeBLOB(v.toByteArray(), KDb::BLOBEscapeHex); } else if (v.type() == QVariant::StringList) { return serializeList(v.toStringList()); } return v.toString(); } QVariant KDb::stringToVariant(const QString& s, QVariant::Type type, bool* ok) { if (s.isNull()) { if (ok) *ok = true; return QVariant(); } switch (type) { case QVariant::Invalid: if (ok) *ok = false; return QVariant(); case QVariant::ByteArray: {//special case: hex string const int len = s.length(); QByteArray ba; ba.resize(len / 2 + len % 2); for (int i = 0; i < (len - 1); i += 2) { bool _ok; int c = s.midRef(i, 2).toInt(&_ok, 16); if (!_ok) { if (ok) *ok = _ok; kdbWarning() << "Error in digit" << i; return QVariant(); } ba[i/2] = (char)c; } if (ok) *ok = true; return ba; } case QVariant::StringList: *ok = true; return KDb::deserializeList(s); default:; } QVariant result(s); if (!result.convert(type)) { if (ok) *ok = false; return QVariant(); } if (ok) *ok = true; return result; } bool KDb::isDefaultValueAllowed(const KDbField &field) { return !field.isUniqueKey(); } void KDb::getLimitsForFieldType(KDbField::Type type, qlonglong *minValue, qlonglong *maxValue, Signedness signedness) { Q_ASSERT(minValue); Q_ASSERT(maxValue); switch (type) { case KDbField::Byte: //! @todo always ok? *minValue = signedness == KDb::Signed ? -0x80 : 0; *maxValue = signedness == KDb::Signed ? 0x7F : 0xFF; break; case KDbField::ShortInteger: *minValue = signedness == KDb::Signed ? -0x8000 : 0; *maxValue = signedness == KDb::Signed ? 0x7FFF : 0xFFFF; break; case KDbField::Integer: case KDbField::BigInteger: //!< @todo cannot return anything larger? default: *minValue = signedness == KDb::Signed ? qlonglong(-0x07FFFFFFF) : qlonglong(0); *maxValue = signedness == KDb::Signed ? qlonglong(0x07FFFFFFF) : qlonglong(0x0FFFFFFFF); } } KDbField::Type KDb::maximumForIntegerFieldTypes(KDbField::Type t1, KDbField::Type t2) { if (!KDbField::isIntegerType(t1) || !KDbField::isIntegerType(t2)) return KDbField::InvalidType; if (t1 == t2) return t2; if (t1 == KDbField::ShortInteger && t2 != KDbField::Integer && t2 != KDbField::BigInteger) return t1; if (t1 == KDbField::Integer && t2 != KDbField::BigInteger) return t1; if (t1 == KDbField::BigInteger) return t1; return KDb::maximumForIntegerFieldTypes(t2, t1); //swap } QString KDb::simplifiedFieldTypeName(KDbField::Type type) { if (KDbField::isNumericType(type)) return KDbField::tr("Number"); //simplify else if (type == KDbField::BLOB) //! @todo support names of other BLOB subtypes return KDbField::tr("Image"); //simplify return KDbField::typeGroupName(KDbField::typeGroup(type)); } QString KDb::defaultFileBasedDriverMimeType() { return QLatin1String("application/x-kexiproject-sqlite3"); } QString KDb::defaultFileBasedDriverId() { return QLatin1String("org.kde.kdb.sqlite"); } // Try to convert from string to type T template QVariant convert(T (QString::*ConvertToT)(bool*,int) const, const char *data, int size, qlonglong minValue, qlonglong maxValue, bool *ok) { T v = (QString::fromLatin1(data, size).*ConvertToT)(ok, 10); if (*ok) { *ok = minValue <= v && v <= maxValue; } return KDb::iif(*ok, QVariant(v)); } QVariant KDb::cstringToVariant(const char* data, KDbField::Type type, bool *ok, int length, KDb::Signedness signedness) { bool tempOk; bool *thisOk = ok ? ok : &tempOk; if (type < KDbField::Byte || type > KDbField::LastType) { *thisOk = false; return QVariant(); } if (!data) { // NULL value *thisOk = true; return QVariant(); } // from most to least frequently used types: if (KDbField::isTextType(type)) { *thisOk = true; //! @todo use KDbDriverBehavior::TEXT_TYPE_MAX_LENGTH for Text type? return QString::fromUtf8(data, length); } if (KDbField::isIntegerType(type)) { qlonglong minValue, maxValue; const bool isUnsigned = signedness == KDb::Unsigned; KDb::getLimitsForFieldType(type, &minValue, &maxValue, signedness); switch (type) { case KDbField::Byte: // Byte here too, minValue/maxValue will take care of limits case KDbField::ShortInteger: return isUnsigned ? convert(&QString::toUShort, data, length, minValue, maxValue, thisOk) : convert(&QString::toShort, data, length, minValue, maxValue, thisOk); case KDbField::Integer: return isUnsigned ? convert(&QString::toUInt, data, length, minValue, maxValue, thisOk) : convert(&QString::toInt, data, length, minValue, maxValue, thisOk); case KDbField::BigInteger: return convert(&QString::toLongLong, data, length, minValue, maxValue, thisOk); default: qFatal("Unsupported integer type %d", type); } } if (KDbField::isFPNumericType(type)) { const QVariant result(QString::fromLatin1(data, length).toDouble(thisOk)); return KDb::iif(*thisOk, result); } if (type == KDbField::BLOB) { *thisOk = length >= 0; return *thisOk ? QVariant(QByteArray(data, length)) : QVariant(); } // the default //! @todo date/time? QVariant result(QString::fromUtf8(data, length)); if (!result.convert(KDbField::variantType(type))) { *thisOk = false; return QVariant(); } *thisOk = true; return result; } QStringList KDb::libraryPaths() { QStringList result; foreach (const QString& path, qApp->libraryPaths()) { const QString dir(path + QLatin1Char('/') + QLatin1String(KDB_BASE_NAME_LOWER)); if (QDir(dir).exists() && QDir(dir).isReadable()) { result += dir; } } return result; } QString KDb::temporaryTableName(KDbConnection *conn, const QString &baseName) { Q_ASSERT(conn); if (!conn) { return QString(); } while (true) { QString name = QLatin1String("tmp__") + baseName; for (int i = 0; i < 10; ++i) { name += QString::number(int(double(qrand()) / RAND_MAX * 0x10), 16); } const tristate res = conn->containsTable(name); if (~res) { return QString(); } else if (res == false) { return name; } } } QString KDb::sqlite3ProgramPath() { QString path = KDbUtils::findExe(QLatin1String("sqlite3")); if (path.isEmpty()) { kdbWarning() << "Could not find program \"sqlite3\""; } return path; } bool KDb::importSqliteFile(const QString &inputFileName, const QString &outputFileName) { const QString sqlite_app = KDb::sqlite3ProgramPath(); if (sqlite_app.isEmpty()) { return false; } QFileInfo fi(inputFileName); if (!fi.isReadable()) { kdbWarning() << "No readable input file" << fi.absoluteFilePath(); return false; } QFileInfo fo(outputFileName); if (QFile(fo.absoluteFilePath()).exists()) { if (!QFile::remove(fo.absoluteFilePath())) { kdbWarning() << "Could not remove output file" << fo.absoluteFilePath(); return false; } } kdbDebug() << inputFileName << fi.absoluteDir().path() << fo.absoluteFilePath(); QProcess p; p.start(sqlite_app, QStringList() << fo.absoluteFilePath()); if (!p.waitForStarted()) { kdbWarning() << "Failed to start program" << sqlite_app; return false; } QByteArray line(".read " + QFile::encodeName(fi.absoluteFilePath())); if (p.write(line) != line.length() || !p.waitForBytesWritten()) { kdbWarning() << "Failed to send \".read\" command to program" << sqlite_app; return false; } p.closeWriteChannel(); if (!p.waitForFinished()) { kdbWarning() << "Failed to finish program" << sqlite_app; return false; } return true; } //--------- bool KDb::isIdentifier(const QString& s) { int i; const int sLength = s.length(); for (i = 0; i < sLength; i++) { const char c = s.at(i).toLower().toLatin1(); if (c == 0 || !(c == '_' || (c >= 'a' && c <= 'z') || (i > 0 && c >= '0' && c <= '9'))) break; } return i > 0 && i == sLength; } bool KDb::isIdentifier(const QByteArray& s) { int i; const int sLength = s.length(); for (i = 0; i < sLength; i++) { const char c = s.at(i); if (c == 0 || !(c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (i > 0 && c >= '0' && c <= '9'))) { break; } } return i > 0 && i == sLength; } static inline QString charToIdentifier(const QChar& c) { if (c.unicode() >= TRANSLITERATION_TABLE_SIZE) return QLatin1String("_"); const char *const s = transliteration_table[c.unicode()]; return s ? QString::fromLatin1(s) : QLatin1String("_"); } QString KDb::stringToIdentifier(const QString &s) { if (s.isEmpty()) return QString(); QString r, id = s.simplified(); if (id.isEmpty()) return QString(); r.reserve(id.length()); id.replace(QLatin1Char(' '), QLatin1String("_")); const QChar c = id[0]; const char ch = c.toLatin1(); QString add; bool wasUnderscore = false; if (ch >= '0' && ch <= '9') { r += QLatin1Char('_') + c; } else { add = charToIdentifier(c); r += add; wasUnderscore = add == QLatin1String("_"); } const int idLength = id.length(); for (int i = 1; i < idLength; i++) { add = charToIdentifier(id.at(i)); if (wasUnderscore && add == QLatin1String("_")) continue; wasUnderscore = add == QLatin1String("_"); r += add; } return r; } QString KDb::identifierExpectedMessage(const QString &valueName, const QVariant& v) { return QLatin1String("

") + kdb::tr("Value of \"%1\" field must be an identifier.") .arg(valueName) + QLatin1String("

") + kdb::tr("\"%1\" is not a valid identifier.").arg(v.toString()) + QLatin1String("

"); } //-------------------------------------------------------------------------------- #ifdef KDB_DEBUG_GUI static KDb::DebugGUIHandler s_debugGUIHandler = 0; void KDb::setDebugGUIHandler(KDb::DebugGUIHandler handler) { s_debugGUIHandler = handler; } void KDb::debugGUI(const QString& text) { if (s_debugGUIHandler) s_debugGUIHandler(text); } static KDb::AlterTableActionDebugGUIHandler s_alterTableActionDebugHandler = 0; void KDb::setAlterTableActionDebugHandler(KDb::AlterTableActionDebugGUIHandler handler) { s_alterTableActionDebugHandler = handler; } void KDb::alterTableActionDebugGUI(const QString& text, int nestingLevel) { if (s_alterTableActionDebugHandler) s_alterTableActionDebugHandler(text, nestingLevel); } #endif // KDB_DEBUG_GUI #include "KDb.moc" diff --git a/src/KDb.h b/src/KDb.h index b099469f..a352e319 100644 --- a/src/KDb.h +++ b/src/KDb.h @@ -1,739 +1,739 @@ /* This file is part of the KDE project Copyright (C) 2004-2016 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_H #define KDB_H #include #include #include #include "KDbGlobal.h" #include "KDbField.h" #include "KDbTableSchema.h" class QDomNode; class QDomElement; class QDomDocument; class KDbConnection; class KDbConnectionData; class KDbDriver; class KDbEscapedString; class KDbLookupFieldSchema; class KDbMessageHandler; class KDbQuerySchema; class KDbResultable; class KDbResultInfo; class KDbSqlResult; class KDbTableOrQuerySchema; class KDbVersionInfo; class tristate; namespace KDb { //! @return runtime information about version of the KDb library. //! @see KDbConnection::databaseVersion() KDbConnection::serverVersion() KDbDriverMetaData::version() KDB_EXPORT KDbVersionInfo version(); //! @overload bool deleteRecord(KDbConnection*, const KDbTableSchema&, const QString &, KDbField::Type, const QVariant &) KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname, KDbField::Type keytype, const QVariant &keyval); //! Deletes records using one generic criteria. inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString &keyname, KDbField::Type keytype, const QVariant &keyval) { return deleteRecords(conn, table.name(), keyname, keytype, keyval); } //! @overload bool deleteRecords(KDbConnection*, const QString&, const QString&, KDbField::Type, const QVariant&); inline bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname, const QString &keyval) { return deleteRecords(conn, tableName, keyname, KDbField::Text, keyval); } //! @overload bool deleteRecords(KDbConnection*, const QString&, const QString&, const QString&); inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString &keyname, const QString &keyval) { return deleteRecords(conn, table.name(), keyname, keyval); } //! @overload bool deleteRecords(KDbConnection*, const KDbTableSchema&, const QString&, const QString&); inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString& keyname, int keyval) { return deleteRecords(conn, table, keyname, KDbField::Integer, keyval); } //! @overload bool deleteRecords(KDbConnection*, const KDbTableSchema&, const QString&, int); inline bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString& keyname, int keyval) { return deleteRecords(conn, tableName, keyname, KDbField::Integer, keyval); } //! Deletes records with two generic criterias. KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2); //! Deletes records with three generic criterias. KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2, const QString &keyname3, KDbField::Type keytype3, const QVariant& keyval3); //! Deletes all records from table @a tableName. KDB_EXPORT bool deleteAllRecords(KDbConnection* conn, const QString &tableName); //! @overload bool deleteAllRecords(KDbConnection*, const QString&); inline bool deleteAllRecords(KDbConnection* conn, const KDbTableSchema &table) { return KDb::deleteAllRecords(conn, table.name()); } -/*! @return autoincrement field's @a autoIncrementFieldName value - of last inserted record for result @a result. - - Simply, method internally fetches values of the last inserted record and returns selected - field's value. The field belong to @a tableName table. - Requirements: the field must be of integer type, there must be a record inserted using query - for which the @a result is returned. - On error std::numeric_limits::max() is returned. - Last inserted record is identified by a magical record identifier, usually called ROWID - (PostgreSQL has it as well as SQLite; see - KDbDriverBehavior::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE). - ROWID's value will be assigned back to @a recordId if this pointer is not null. -*/ -KDB_EXPORT quint64 lastInsertedAutoIncValue(QSharedPointer *result, +/** + * Returns value of last inserted record for an autoincrement field + * + * This method internally fetches values of the last inserted record for which @a result was + * returned and returns selected field's value. The field belong to @a tableName table. + * The field must be of integer type, there must be a record inserted using query for which the @a + * result is returned. + * std::numeric_limits::max() is returned on error or if @a result is null. + * The last inserted record is identified by a magical record identifier, usually called ROWID + * (PostgreSQL has it as well as SQLite; + * see KDbDriverBehavior::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE). + * ROWID's value will be assigned back to @a recordId if this pointer is not @c nullptr. + */ +KDB_EXPORT quint64 lastInsertedAutoIncValue(QSharedPointer result, const QString &autoIncrementFieldName, const QString &tableName, quint64 *recordId = nullptr); /** * @overload * * Accepts @a recordId that can be obtained from KDbPreparedStatement::lastInsertRecordId() * or KDbSqlResult::lastInsertRecordId(). */ KDB_EXPORT quint64 lastInsertedAutoIncValue(KDbConnection *conn, const quint64 recordId, const QString &autoIncrementFieldName, const QString &tableName); /** @overload */ -inline quint64 lastInsertedAutoIncValue(QSharedPointer *result, +inline quint64 lastInsertedAutoIncValue(QSharedPointer result, const QString &autoIncrementFieldName, const KDbTableSchema &table, quint64 *recordId = nullptr) { return lastInsertedAutoIncValue(result, autoIncrementFieldName, table.name(), recordId); } /*! @return list of field types for field type group @a typeGroup. */ KDB_EXPORT const QList fieldTypesForGroup(KDbField::TypeGroup typeGroup); /*! @return list of translated field type names for field type group @a typeGroup. */ KDB_EXPORT QStringList fieldTypeNamesForGroup(KDbField::TypeGroup typeGroup); /*! @return list of (nontranslated) field type names for field type group @a typeGroup. */ KDB_EXPORT QStringList fieldTypeStringsForGroup(KDbField::TypeGroup typeGroup); /*! @return default field type for field type group @a typeGroup, for example, KDbField::Integer for KDbField::IntegerGroup. It is used e.g. in KexiAlterTableDialog, to properly fill 'type' property when user selects type group for a field. */ KDB_EXPORT KDbField::Type defaultFieldTypeForGroup(KDbField::TypeGroup typeGroup); /*! @return a slightly simplified field type name type @a type. For KDbField::BLOB type it returns a translated "Image" string or other, depending on the mime type. For numbers (either floating-point or integer) it returns a translated "Number" string. For other types KDbField::typeGroupName() is returned. */ //! @todo support names of other BLOB subtypes KDB_EXPORT QString simplifiedFieldTypeName(KDbField::Type type); /*! @return true if value @a value represents an empty (but not null) value. - Case 1: If field type @a type is of any text type (KDbField::isTextType(type) == true) then the function returns true if @a value casted to a QString value is empty and not null. - Case 2: If field type @a type is KDbField::BLOB then the function returns if @a value casted to a QByteArray value is empty and not null. - Case 3: If field type @a type is of any other type then the function returns true if value.isNull(). @see KDbField::hasEmptyProperty() */ KDB_EXPORT bool isEmptyValue(KDbField::Type type, const QVariant &value); /*! Sets string pointed by @a msg to an error message retrieved from @a resultable, and string pointed by @a details to details of this error (server message and result number). Does nothing if @a result is empty. In this case @a msg and @a details strings are not overwritten. If the string pointed by @a msg is not empty, @a result message is appended to the string pointed by @a details. */ KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg, QString *details); /*! This methods works like above, but appends both a message and a description to string pointed by @a msg. */ KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg); /*! This methods works like above, but works on @a result's members instead. */ KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, KDbResultInfo *info); /*! Function useful for building WHERE parts of SQL statements. Constructs an SQL string like "fielname = value" for specific @a drv driver, field type @a t, @a fieldName and @a value. If @a value is null, "fieldname is NULL" string is returned. */ KDB_EXPORT KDbEscapedString sqlWhere(KDbDriver *drv, KDbField::Type t, const QString& fieldName, const QVariant& value); /*! Find an identifier for object @a objName of type @a objType. On success true is returned and *id is set to the value of the identifier. On failure false is returned. If there is no such object, @c cancelled value is returned. */ KDB_EXPORT tristate idForObjectName(KDbConnection* conn, int *id, const QString& objName, int objType); //! @todo perhaps use quint64 here? /*! @return number of records that can be retrieved after executing @a sql statement within a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. -1 is returned if error occurred. */ KDB_EXPORT int recordCount(KDbConnection* conn, const KDbEscapedString& sql); //! @todo perhaps use quint64 here? /*! @return number of records that can be retrieved from @a tableSchema. The table must be created or retrieved using a KDbConnection object, i.e. tableSchema.connection() must not return 0. For SQL data sources it does not fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. -1 is returned if error occurred. */ KDB_EXPORT int recordCount(const KDbTableSchema& tableSchema); /*! @overload in rowCount(const KDbTableSchema& tableSchema) Operates on a query schema. @a params are optional values of parameters that will be inserted into places marked with [] before execution of the query. */ //! @todo perhaps use quint64 here? KDB_EXPORT int recordCount(KDbQuerySchema* querySchema, const QList& params = QList()); /*! @overload int rowCount(KDbQuerySchema& querySchema, const QList& params) Operates on a table or query schema. @a params are optional values of parameters that will be inserted into places marked with [] before execution of the query. */ //! @todo perhaps use quint64 here? KDB_EXPORT int recordCount(KDbTableOrQuerySchema* tableOrQuery, const QList& params = QList()); /*! @return a number of columns that can be retrieved from table or query schema. In case of query, expanded fields are counted. Can return -1 if @a tableOrQuery has neither table or query assigned. */ KDB_EXPORT int fieldCount(KDbTableOrQuerySchema* tableOrQuery); /*! shows connection test dialog with a progress bar indicating connection testing (within a second thread). @a data is used to perform a (temporary) test connection. @a msgHandler is used to display errors. On successful connecting, a message is displayed. After testing, temporary connection is closed. */ KDB_EXPORT void connectionTestDialog(QWidget* parent, const KDbConnectionData& data, KDbMessageHandler* msgHandler); //! Used in splitToTableAndFieldParts(). enum SplitToTableAndFieldPartsOptions { FailIfNoTableOrFieldName = 0, //!< default value for splitToTableAndFieldParts() SetFieldNameIfNoTableName = 1 //!< see splitToTableAndFieldParts() }; /*! Splits @a string like "table.field" into "table" and "field" parts. On success, a table name is passed to @a tableName and a field name is passed to @a fieldName. The function fails if either: - @a string is empty, or - @a string does not contain '.' character and @a option is FailIfNoTableOrFieldName (the default), or - '.' character is the first of last character of @a string (in this case table name or field name could become empty what is not allowed). If @a option is SetFieldNameIfNoTableName and @a string does not contain '.', @a string is passed to @a fieldName and @a tableName is set to QString() without failure. If function fails, @a tableName and @a fieldName remain unchanged. @return true on success. */ KDB_EXPORT bool splitToTableAndFieldParts(const QString& string, QString *tableName, QString *fieldName, SplitToTableAndFieldPartsOptions option = FailIfNoTableOrFieldName); /*! @return true if @a type supports "visibleDecimalPlaces" property. */ KDB_EXPORT bool supportsVisibleDecimalPlacesProperty(KDbField::Type type); /*! @return string constructed by converting @a value. * If @a decimalPlaces is < 0, all meaningful fractional digits are returned (up to 10). * If @a automatically is 0, just integer part is returned. * If @a automatically is > 0, fractional part should take exactly N digits: if the fractional part is shorter than N, additional zeros are appended. Examples: * numberToString(12.345, 6) == "12.345000" * numberToString(12.345, 0) == "12" * numberToString(12.345, -1) == "12.345" * numberToString(12.0, -1) == "12" * numberToString(0.0, -1) == "0" @note No rounding is performed @note No thousands group separator is used. Decimal symbol is '.'. @see KDb::numberToLocaleString() KDbField::visibleDecimalPlaces() */ KDB_EXPORT QString numberToString(double value, int decimalPlaces); /*! Like KDb::numberToString() but formats the string using locale.toString(). If @a locale if @c nullptr, desault QLocale is used. @see KDb::numberToString() KDbField::visibleDecimalPlaces() */ KDB_EXPORT QString numberToLocaleString(double value, int decimalPlaces, const QLocale *locale = nullptr); //! @return true if @a propertyName is a builtin field property. KDB_EXPORT bool isBuiltinTableFieldProperty(const QByteArray& propertyName); //! @return true if @a propertyName is an extended field property. KDB_EXPORT bool isExtendedTableFieldProperty(const QByteArray& propertyName); //! @return true if @a propertyName is belongs to lookup field's schema. KDB_EXPORT bool isLookupFieldSchemaProperty(const QByteArray& propertyName); /*! @return type of field for integer value @a type. If @a type cannot be casted to KDbField::Type or is not normal type, i.e. @a type > KDbField::LastType (e.g. KDbField::Null), KDbField::InvalidType is returned. This can be used when type information is deserialized from a string or QVariant. @see KDbField::typesCount() KDbField::specialTypesCount() */ KDB_EXPORT KDbField::Type intToFieldType(int type); /*! @return type group of field for integer value @a typeGroup. If @a typeGroup cannot be casted to KDbField::TypeGroup, KDbField::InvalidGroup is returned. This can be used when type information is deserialized from a string or QVariant. @see KDbField::typeGroupsCount() */ KDB_EXPORT KDbField::TypeGroup intToFieldTypeGroup(int typeGroup); /*! Gets property values for the lookup schema @a lookup. @a values is cleared before filling. This function is used e.g. for altering table design. */ KDB_EXPORT void getProperties(const KDbLookupFieldSchema *lookup, QMap *values); /*! Gets property values for @a field. Properties from extended schema are included. @a values is cleared before filling. The same number of properties in the same order is returned. This function is used e.g. for altering table design. */ KDB_EXPORT void getFieldProperties(const KDbField &field, QMap *values); /*! Sets property values for @a field. @return true if all the values are valid and allowed. On failure contents of @a field is undefined. Properties from extended schema are also supported. This function is used e.g. by KDbAlterTableHandler when property information comes in form of text. */ KDB_EXPORT bool setFieldProperties(KDbField *field, const QMap& values); /*! Sets property value for @a field. @return true if the property has been found and the value is valid for this property. On failure contents of @a field is undefined. Properties from extended schema are also supported as well as QVariant customProperty(const QString& propertyName) const; This function is used e.g. by KDbAlterTableHandler when property information comes in form of text. */ KDB_EXPORT bool setFieldProperty(KDbField *field, const QByteArray& propertyName, const QVariant& value); /*! @return property value loaded from a DOM @a node, written in a QtDesigner-like notation: <number>int</number> or <bool>bool</bool>, etc. Supported types are "string", "cstring", "bool", "number". For invalid values null QVariant is returned. You can check the validity of the returned value using QVariant::type(). */ KDB_EXPORT QVariant loadPropertyValueFromDom(const QDomNode& node, bool *ok); /*! Convenience version of loadPropertyValueFromDom(). @return int value. */ KDB_EXPORT int loadIntPropertyValueFromDom(const QDomNode& node, bool* ok); /*! Convenience version of loadPropertyValueFromDom(). @return QString value. */ KDB_EXPORT QString loadStringPropertyValueFromDom(const QDomNode& node, bool* ok); /*! Saves integer element for value @a value to @a doc document within parent element @a parentEl. The value will be enclosed in "number" element and "elementName" element. Example: saveNumberElementToDom(doc, parentEl, "height", 15) will create @code 15 @endcode @return the reference to element created with tag elementName. */ KDB_EXPORT QDomElement saveNumberElementToDom(QDomDocument *doc, QDomElement *parentEl, const QString& elementName, int value); /*! Saves boolean element for value @a value to @a doc document within parent element @a parentEl. Like saveNumberElementToDom() but creates "bool" tags. True/false values will be saved as "true"/"false" strings. @return the reference to element created with tag elementName. */ KDB_EXPORT QDomElement saveBooleanElementToDom(QDomDocument *doc, QDomElement *parentEl, const QString& elementName, bool value); //! @return equivalent of empty (default) value that can be set for a database field of type @a type /*! In particular returns: - empty string for text types, - 0 for integer and floating-point types, - false for boolean types, - a null byte array for BLOB type, - current date, time, date+time is returned (measured at client side) for date, time and date/time types respectively, - a null QVariant for unsupported values such as KDbField::InvalidType. */ KDB_EXPORT QVariant emptyValueForFieldType(KDbField::Type type); //! @return a value that can be set for a database field of type @a type having "notEmpty" property set. /*! It works in a similar way as @ref QVariant KDb::emptyValueForFieldType(KDbField::Type type) with the following differences: - " " string (a single space) is returned for Text and LongText types - a byte array with saved "filenew" PNG image (icon) for BLOB type Returns null QVariant for unsupported values like KDbField::InvalidType. */ KDB_EXPORT QVariant notEmptyValueForFieldType(KDbField::Type type); /*! @return true if the @a word is an reserved KDbSQL keyword See generated/sqlkeywords.cpp. @todo add function returning list of keywords. */ KDB_EXPORT bool isKDbSQLKeyword(const QByteArray& word); //! @return @a string string with applied KDbSQL identifier escaping /*! This escaping can be used for field, table, database names, etc. Use it for user-visible backend-independent statements. @see KDb::escapeIdentifierAndAddQuotes() */ KDB_EXPORT QString escapeIdentifier(const QString& string); //! @overload QString escapeIdentifier(const QString&) KDB_EXPORT QByteArray escapeIdentifier(const QByteArray& string); //! @return @a string string with applied KDbSQL identifier escaping and enclosed in " quotes /*! This escaping can be used for field, table, database names, etc. Use it for user-visible backend-independent statements. @see KDb::escapeIdentifier */ KDB_EXPORT QString escapeIdentifierAndAddQuotes(const QString& string); //! @overload QString escapeIdentifierAndAddQuotes(const QString&) KDB_EXPORT QByteArray escapeIdentifierAndAddQuotes(const QByteArray& string); /*! @return escaped string @a string for the KDbSQL dialect, i.e. doubles single quotes ("'") and inserts the string into single quotes. Quotes "'" are prepended and appended. Also escapes \\n, \\r, \\t, \\\\, \\0. Use it for user-visible backend-independent statements. @see unescapeString() */ KDB_EXPORT QString escapeString(const QString& string); //! Unescapes characters in string @a string for the KDbSQL dialect. /** The operation depends on @a quote character, which can be be ' or ". * @a string is assumed to be properly constructed. This is assured by the lexer's grammar. * Used by lexer to recognize the CHARACTER_STRING_LITERAL token. * @return unescaped string and sets value pointed by @a errorPosition (if any) to -1 on success; * and to index of problematic character on failure. * The function fails when unsupported @a quote character is passed or for unsupported sequences. * * Example sequences for ' character quote: * - \' -> ' (escaping) * - \" -> " (escaping) * - '' -> ' (repeated quote escapes too) * - "" -> "" (repeated but this is not the quote) * - ' -> (disallowed, escaping needed) * - " -> " * Example sequences for " character quote: * - \' -> ' (escaping) * - \" -> " (escaping) * - " -> " (disallowed, escaping needed) * - "" -> " (repeated quote escapes too) * - '' -> '' (repeated but this is not the quote) * - ' -> ' * * Following sequences are always unescaped (selection based on a mix of MySQL and C/JavaScript): * - \0 -> NULL (QChar()) * - \b -> backspace 0x8 * - \f -> form feed 0xc * - \n -> new line 0xa * - \r -> carriage return 0xd * - \t -> horizontal tab 0x9 * - \v -> vertical tab 0xb * - \\ -> backslash * - \? -> ? (useful when '?' placeholders are used) * - \% -> (useful when '%' wildcards are used e.g. for the LIKE operator) * - \_ -> (useful when '_' pattern is used e.g. for the LIKE operator) * - \xhh -> a character for which hh (exactly 2 digits) is interpreted as an hexadecimal * number, 00 <= hh <= FF. Widely supported by programming languages. * Can be also 00 <= hh <= ff. * Example: \xA9 translates to "©". * - \uxxxx -> 16-bit unicode character, exactly 4 digits, each x is a hexadecimal digit, * case insensitive; known from JavaScript, Java, C/C++. 0000 <= xxxxxx <= FFFF * Example: \u2665 translates to "♥". * - \u{xxxxxx} -> 24-bit unicode "code point" character, each x is a hexadecimal digit, * case insensitive; known from JavaScript (ECMAScript 6). 0 <= xxxxxx <= 10FFFF * Example: \u{1D306} translates to "𝌆" * * @note Characters without special meaning can be escaped, but then the "\" character * is skipped, e.g. "\a" == "a". * @note Trailing "\" character in @a string is ignored. * @note \nnn octal notation is not supported, it may be confusing and conflicting * when combined with other characters (\0012 is not the same as \012). * The industry is moving away from it and EcmaScript 5 deprecates it. * * See also: * - http://dev.mysql.com/doc/refman/5.7/en/string-literals.html * - https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences * - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings * - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals */ KDB_EXPORT QString unescapeString(const QString& string, char quote, int *errorPosition = nullptr); //! Escaping types for BLOBS. Used in escapeBLOB(). enum BLOBEscapingType { BLOBEscapeXHex = 1, //!< Escaping like X'1FAD', used by sqlite (hex numbers) BLOBEscape0xHex, //!< Escaping like 0x1FAD, used by mysql (hex numbers) BLOBEscapeHex, //!< Escaping like 1FAD without quotes or prefixes BLOBEscapeOctal, //!< Escaping like 'zk\\000$x', used by PostgreSQL //!< (only non-printable characters are escaped using octal numbers); //!< see http://www.postgresql.org/docs/9.5/interactive/datatype-binary.html BLOBEscapeByteaHex //!< "bytea hex" escaping, e.g. E'\xDEADBEEF'::bytea used by PostgreSQL //!< (only non-printable characters are escaped using octal numbers); //!< see http://www.postgresql.org/docs/9.5/interactive/datatype-binary.html }; /*! @return a string containing escaped, printable representation of @a array. Escaping is controlled by @a type. For empty array, QString() is returned, so if you want to use this function in an SQL statement, empty arrays should be detected and "NULL" string should be put instead. This is helper, used in KDbDriver::escapeBLOB() and KDb::variantToString(). */ KDB_EXPORT QString escapeBLOB(const QByteArray& array, BLOBEscapingType type); /*! @return byte array converted from @a data of length @a length. If @a length is negative, the data is assumed to point to a null-terminated string and its length is determined dynamically. @a data is escaped in format used by PostgreSQL's bytea datatype described at http://www.postgresql.org/docs/8.1/interactive/datatype-binary.html This function is used by PostgreSQL KDb and migration drivers. */ KDB_EXPORT QByteArray pgsqlByteaToByteArray(const char* data, int length = -1); /*! @return byte array converted from @a data of length @a length. If @a length is negative, the data is assumed to point to a null-terminated string and its length is determined dynamically. @a data is escaped in format X'*', where * is one or more hexadecimal digits. Both A-F and a-f letters are supported. Even and odd number of digits are supported. If @a ok is not 0, *ok is set to result of the conversion. See BLOBEscapeXHex. */ KDB_EXPORT QByteArray xHexToByteArray(const char* data, int length = -1, bool *ok = nullptr); /*! @return byte array converted from @a data of length @a length. If @a length is negative, the data is assumed to point to a null-terminated string and its length is determined dynamically. @a data is escaped in format 0x*, where * is one or more hexadecimal digits. Both A-F and a-f letters are supported. Even and odd number of digits are supported. If @a ok is not 0, *ok is set to result of the conversion. See BLOBEscape0xHex. */ KDB_EXPORT QByteArray zeroXHexToByteArray(const char* data, int length = -1, bool *ok = nullptr); /*! @return int list converted from string list. If @a ok is not 0, *ok is set to result of the conversion. */ KDB_EXPORT QList stringListToIntList(const QStringList &list, bool *ok = nullptr); /*! @return string converted from list @a list. Separators are ',' characters, "," and "\\" are escaped. @see KDb::deserializeList() */ KDB_EXPORT QString serializeList(const QStringList &list); /*! @return string list converted from @a data which was built using serializeList(). Separators are ',' characters, escaping is assumed as "\\,". */ KDB_EXPORT QStringList deserializeList(const QString &data); /*! @return int list converted from @a data which was built using serializeList(). Separators are ',' characters, escaping is assumed as "\\,". If @a ok is not 0, *ok is set to result of the conversion. @see KDb::stringListToIntList() */ KDB_EXPORT QList deserializeIntList(const QString &data, bool *ok); /*! @return string value serialized from a variant value @a v. This functions works like QVariant::toString() except the case when @a v is of type: - QByteArray - in this case KDb::escapeBLOB(v.toByteArray(), KDb::BLOBEscapeHex) is used. - QStringList - in this case KDb::serializeList(v.toStringList()) is used. This function is needed for handling values of random type, for example "defaultValue" property of table fields can contain value of any type. Note: the returned string is an unescaped string. */ KDB_EXPORT QString variantToString(const QVariant& v); /*! @return variant value of type @a type for a string @a s that was previously serialized using @ref variantToString( const QVariant& v ) function. @a ok is set to the result of the operation. With exception for types mentioned in documentation of variantToString(), QVariant::convert() is used for conversion. */ KDB_EXPORT QVariant stringToVariant(const QString& s, QVariant::Type type, bool* ok); /*! @return true if setting default value for @a field field is allowed. Fields with unique (and thus primary key) flags set do not accept default values. */ KDB_EXPORT bool isDefaultValueAllowed(const KDbField &field); //! Provides limits for values of type @a type /*! The result is put into integers pointed by @a minValue and @a maxValue. The limits are machine-independent,. what is useful for format and protocol compatibility. Supported types are Byte, ShortInteger, Integer and BigInteger. The value of @a signedness controls the values; they can be limited to unsigned or not. Results for BigInteger or non-integer types are the same as for Integer due to limitation of int type. Signed integers are assumed. @a minValue and @a maxValue must not be 0. */ KDB_EXPORT void getLimitsForFieldType(KDbField::Type type, qlonglong *minValue, qlonglong *maxValue, KDb::Signedness signedness = KDb::Signed); /*! @return type that's maximum of two integer types @a t1 and @a t2, e.g. Integer for (Byte, Integer). If one of the types is not of the integer group, KDbField::InvalidType is returned. Returned type may not fit to the result of evaluated expression that involves the arguments. For example, 100 is within Byte type, maximumForIntegerFieldTypes(Byte, Byte) is Byte but result of 100 * 100 exceeds the range of Byte. */ KDB_EXPORT KDbField::Type maximumForIntegerFieldTypes(KDbField::Type t1, KDbField::Type t2); //! @return QVariant value converted from a @a data string /*! Conversion is based on the information about type @a type. @a type has to be an element from KDbField::Type, not greater than KDbField::LastType. For unsupported type this function fails. @a length value controls number of characters used in the conversion. It is optional value for all cases but for the BLOB type because for it @a data is not null-terminated so the length cannot be measured. The value of @a signedness controls the conversion in case of integer types; numbers can be limited to unsigned or not. If @a ok is not 0 *ok is set to false on failure and to true on success. On failure a null QVariant is returned. The function fails if @a data is 0. For rules of conversion to the boolean type see the documentation of @ref QVariant::toBool(), QVariant::toDate() for date type, QVariant::toDateTime() for date+time type, QVariant::toTime() for time type. */ KDB_EXPORT QVariant cstringToVariant(const char* data, KDbField::Type type, bool *ok, int length = -1, KDb::Signedness signedness = KDb::Signed); /*! @return default file-based driver MIME type (typically something like "application/x-kexiproject-sqlite") */ KDB_EXPORT QString defaultFileBasedDriverMimeType(); /*! @return default file-based driver ID (currently, "org.kde.kdb.sqlite"). */ KDB_EXPORT QString defaultFileBasedDriverId(); /*! Escapes and converts value @a v (for type @a ftype) to string representation required by KDbSQL commands. For Date/Time type KDb::dateTimeToSQL() is used. For BLOB type KDb::escapeBlob() with BLOBEscape0xHex conversion type is used. */ KDB_EXPORT KDbEscapedString valueToSQL(KDbField::Type ftype, const QVariant& v); /*! Converts value @a v to string representation required by KDbSQL commands: ISO 8601 DateTime format - with "T" delimiter/ For specification see http://www.w3.org/TR/NOTE-datetime. Example: "1994-11-05T13:15:30" not "1994-11-05 13:15:30". @todo Add support for time zones */ KDB_EXPORT KDbEscapedString dateTimeToSQL(const QDateTime& v); #ifdef KDB_DEBUG_GUI //! A prototype of handler for GUI debugger typedef void(*DebugGUIHandler)(const QString&); //! Sets handler for GUI debugger KDB_EXPORT void setDebugGUIHandler(DebugGUIHandler handler); //! Outputs string @a text to the GUI debugger KDB_EXPORT void debugGUI(const QString& text); //! A prototype of handler for GUI debugger (specialized for the Alter Table feature) typedef void(*AlterTableActionDebugGUIHandler)(const QString&, int); //! Sets handler for GUI debugger (specialized for the Alter Table feature) KDB_EXPORT void setAlterTableActionDebugHandler(AlterTableActionDebugGUIHandler handler); //! Outputs string @a text to the GUI debugger (specialized for the Alter Table feature); //! @a nestingLevel can be provided for nested outputs. KDB_EXPORT void alterTableActionDebugGUI(const QString& text, int nestingLevel = 0); #endif //! @return @a string if it is not empty, else returns @a stringIfEmpty. /*! This function is an optimization in cases when @a string is a result of expensive functioncall because any evaluation will be performed once, not twice. Another advantage is simpified code through the functional approach. The function expects bool isEmpty() method to be present in type T, so T can typically be QString or QByteArray. */ template T iifNotEmpty(const T &string, const T &stringIfEmpty) { return string.isEmpty() ? stringIfEmpty : string; } //! @overload iifNotEmpty(const T &string, const T &stringIfEmpty) template T iifNotEmpty(const QByteArray &string, const T &stringIfEmpty) { return iifNotEmpty(QLatin1String(string), stringIfEmpty); } //! @overload iifNotEmpty(const T &string, const T &stringIfEmpty) template T iifNotEmpty(const T &string, const QByteArray &stringIfEmpty) { return iifNotEmpty(string, QLatin1String(stringIfEmpty)); } //! @return @a value if @a ok is true, else returns default value T(). template T iif(bool ok, const T &value) { if (ok) { return value; } return T(); } /*! @return a list of paths that KDb will search when dynamically loading libraries (plugins) This is basicaly list of directories returned QCoreApplication::libraryPaths() that have readable subdirectory "kdb". @see QCoreApplication::libraryPaths() */ KDB_EXPORT QStringList libraryPaths(); /*! @return new temporary name suitable for creating new table. The name has mask tmp__{baseName}{rand} where baseName is passed as argument and {rand} is a 10 digits long hexadecimal number. @a baseName can be empty. It is adviced to use the returned name as quickly as possible for creating new physical table. It is not 100% guaranteed that table with this name will not exist at an attempt of creation but it is very unlikely. The function checks for existence of a table with temporary name for connection @a conn. Empty string is returned if @a conn is not present or is not open or if checking for existence of table withg temporary name failed. */ KDB_EXPORT QString temporaryTableName(KDbConnection *conn, const QString &baseName); /*! @return absolute path to "sqlite3" program. Empty string is returned if the program was not found. */ KDB_EXPORT QString sqlite3ProgramPath(); /*! Imports file in SQL format from @a inputFileName into @a outputFileName. Works for any SQLite 3 dump file. Requires access to executing the "sqlite3" command. File named @a outputFileName will be silently overwritten with a new SQLite 3 database file. @return true on success. */ KDB_EXPORT bool importSqliteFile(const QString &inputFileName, const QString &outputFileName); /*! @return true if @a s is a valid identifier, ie. starts with a letter or '_' character and contains only letters, numbers and '_' character. */ KDB_EXPORT bool isIdentifier(const QString& s); //! @overload isIdentifier(const QString& s) //! @since 3.1 KDB_EXPORT bool isIdentifier(const QByteArray& s); /*! @return valid identifier based on @a s. Non-alphanumeric characters (or spaces) are replaced with '_'. If a number is at the beginning, '_' is added at start. Empty strings are not changed. Case remains unchanged. */ KDB_EXPORT QString stringToIdentifier(const QString &s); /*! @return useful message "Value of "valueName" field must be an identifier. "v" is not a valid identifier.". It is also used by KDbIdentifierValidator. */ KDB_EXPORT QString identifierExpectedMessage(const QString &valueName, const QVariant& v); } // namespace KDb #endif diff --git a/src/KDbConnection.cpp b/src/KDbConnection.cpp index e4bc3cc3..9e5f7787 100644 --- a/src/KDbConnection.cpp +++ b/src/KDbConnection.cpp @@ -1,3427 +1,3427 @@ /* 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, nullptr, KDbField::Unsigned)); t_objects->addField(new KDbField(QLatin1String("o_name"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_caption"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_desc"), KDbField::LongText)); //kdbDebug() << *t_objects; insertTable(t_objects); } { KDbInternalTableSchema *t_objectdata = new KDbInternalTableSchema(QLatin1String("kexi__objectdata")); t_objectdata->addField(new KDbField(QLatin1String("o_id"), KDbField::Integer, KDbField::NotNull, KDbField::Unsigned)); t_objectdata->addField(new KDbField(QLatin1String("o_data"), KDbField::LongText)); t_objectdata->addField(new KDbField(QLatin1String("o_sub_id"), KDbField::Text)); insertTable(t_objectdata); } { KDbInternalTableSchema *t_fields = new KDbInternalTableSchema(QLatin1String("kexi__fields")); t_fields->addField(new KDbField(QLatin1String("t_id"), KDbField::Integer, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_type"), KDbField::Byte, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_name"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_length"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_precision"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_constraints"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_options"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_default"), KDbField::Text)); //these are additional properties: t_fields->addField(new KDbField(QLatin1String("f_order"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_caption"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_help"), KDbField::LongText)); insertTable(t_fields); } { KDbInternalTableSchema *t_db = new KDbInternalTableSchema(QLatin1String("kexi__db")); t_db->addField(new KDbField(QLatin1String("db_property"), KDbField::Text, KDbField::NoConstraints, KDbField::NoOptions, 32)); t_db->addField(new KDbField(QLatin1String("db_value"), KDbField::LongText)); insertTable(t_db); } } void KDbConnectionPrivate::insertTable(KDbTableSchema* tableSchema) { KDbInternalTableSchema* internalTable = dynamic_cast(tableSchema); if (internalTable) { m_internalKDbTables.insert(internalTable); } else { m_tables.insert(tableSchema->id(), tableSchema); } m_tablesByName.insert(tableSchema->name(), tableSchema); } void KDbConnectionPrivate::removeTable(const KDbTableSchema& tableSchema) { 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, nullptr, nullptr, 0, KDb::isIdentifier); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of object names.")); } return list; } QStringList KDbConnection::tableNames(bool alsoSystemTables, bool* ok) { bool success; QStringList list = objectNames(KDb::TableObjectType, &success); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of table names.")); } if (alsoSystemTables && success) { list += kdbSystemTableNames(); } return list; } tristate KDbConnection::containsTable(const QString &tableName) { return drv_containsTable(tableName); } QStringList KDbConnection::kdbSystemTableNames() { return *g_kdbSystemTableNames; } KDbServerVersionInfo KDbConnection::serverVersion() const { return isConnected() ? d->serverVersion : KDbServerVersionInfo(); } KDbVersionInfo KDbConnection::databaseVersion() const { return isDatabaseUsed() ? d->databaseVersion : KDbVersionInfo(); } KDbProperties KDbConnection::databaseProperties() const { return d->dbProperties; } QList KDbConnection::tableIds(bool* ok) { return objectIds(KDb::TableObjectType, ok); } QList KDbConnection::queryIds(bool* ok) { return objectIds(KDb::QueryObjectType, ok); } QList KDbConnection::objectIds(int objectType, bool* ok) { if (!checkIsDatabaseUsed()) return QList(); KDbEscapedString sql; if (objectType == KDb::AnyObjectType) sql = "SELECT o_id, o_name FROM kexi__objects ORDER BY o_id"; else sql = "SELECT o_id, o_name FROM kexi__objects WHERE o_type=" + QByteArray::number(objectType) + " ORDER BY o_id"; KDbCursor *c = executeQuery(sql); if (!c) { if (ok) { *ok = false; } m_result.prependMessage(tr("Could not retrieve list of object identifiers.")); return QList(); } QList list; for (c->moveFirst(); !c->eof(); c->moveNext()) { QString tname = c->value(1).toString(); //kexi__objects.o_name if (KDb::isIdentifier(tname)) { list.append(c->value(0).toInt()); //kexi__objects.o_id } } deleteCursor(c); if (ok) { *ok = true; } return list; } //yeah, it is very efficient: #define C_A(a) , const QVariant& c ## a #define V_A0 d->driver->valueToSQL( tableSchema->field(0), c0 ) #define V_A(a) + ',' + d->driver->valueToSQL( \ tableSchema->field(a) ? tableSchema->field(a)->type() : KDbField::Text, c ## a ) // kdbDebug() << "******** " << QString("INSERT INTO ") + // escapeIdentifier(tableSchema->name()) + // " VALUES (" + vals + ")"; QSharedPointer KDbConnection::insertRecordInternal(const QString &tableSchemaName, KDbFieldList *fields, const KDbEscapedString &sql) { QSharedPointer res; if (!drv_beforeInsert(tableSchemaName,fields )) { return res; } res = prepareSql(sql); if (!res || res->lastResult().isError()) { res.clear(); return res; } if (!drv_afterInsert(tableSchemaName, fields)) { res.clear(); return res; } { // Fetching is needed to perform real execution at least for some backends. // Also we are not expecting record but let's delete if there's any. (void)res->fetchRecord(); } if (res->lastResult().isError()) { res.clear(); } return res; } #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbTableSchema* tableSchema args) { \ return insertRecordInternal(tableSchema->name(), tableSchema, \ KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) \ + " (" \ + tableSchema->sqlFieldsList(this) \ + ") VALUES (" + vals + ')'); \ } #define C_INS_REC_ALL \ C_INS_REC( C_A(0), V_A0 ) \ C_INS_REC( C_A(0) C_A(1), V_A0 V_A(1) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2), V_A0 V_A(1) V_A(2) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3), V_A0 V_A(1) V_A(2) V_A(3) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6) C_A(7), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) V_A(7) ) C_INS_REC_ALL #undef V_A0 #undef V_A #undef C_INS_REC #define V_A0 value += d->driver->valueToSQL( it.next(), c0 ); #define V_A( a ) value += (',' + d->driver->valueToSQL( it.next(), c ## a )); #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbFieldList* fields args) \ { \ KDbEscapedString value; \ const KDbField::List *flist = fields->fields(); \ QListIterator it(*flist); \ vals \ it.toFront(); \ QString tableName((it.hasNext() && it.peekNext()->table()) ? it.next()->table()->name() : QLatin1String("??")); \ return insertRecordInternal(tableName, fields, \ KDbEscapedString(QLatin1String("INSERT INTO ") + escapeIdentifier(tableName)) \ + " (" + fields->sqlFieldsList(this) \ + ") VALUES (" + value + ')'); \ } C_INS_REC_ALL #undef C_A #undef V_A #undef V_ALAST #undef C_INS_REC #undef C_INS_REC_ALL QSharedPointer KDbConnection::insertRecord(KDbTableSchema *tableSchema, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = tableSchema->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); QList::ConstIterator it = values.constBegin(); KDbEscapedString sql; sql.reserve(4096); while (fieldsIt != flist->constEnd() && (it != values.end())) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) + " VALUES ("; } else { sql += ','; } sql += d->driver->valueToSQL(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSQL( f, *it ); ++it; ++fieldsIt; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableSchema->name(), tableSchema, sql); return res; } QSharedPointer KDbConnection::insertRecord(KDbFieldList *fields, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = fields->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); KDbEscapedString sql; sql.reserve(4096); QList::ConstIterator it = values.constBegin(); const QString tableName(flist->first()->table()->name()); while (fieldsIt != flist->constEnd() && it != values.constEnd()) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableName) + '(' + fields->sqlFieldsList(this) + ") VALUES ("; } else { sql += ','; } sql += d->driver->valueToSQL(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSQL( f, *it ); ++it; ++fieldsIt; if (fieldsIt == flist->constEnd()) break; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableName, fields, sql); return res; } inline static bool checkSql(const KDbEscapedString& sql, KDbResult* result) { Q_ASSERT(result); if (!sql.isValid()) { *result = KDbResult(ERR_SQL_EXECUTION_ERROR, KDbConnection::tr("SQL statement for execution is invalid or empty.")); result->setErrorSql(sql); //remember for error handling return false; } return true; } QSharedPointer KDbConnection::prepareSql(const KDbEscapedString& sql) { m_result.setSql(sql); return QSharedPointer(drv_prepareSql(sql)); } bool KDbConnection::executeSql(const KDbEscapedString& sql) { m_result.setSql(sql); if (!checkSql(sql, &m_result)) { return false; } if (!drv_executeSql(sql)) { m_result.setMessage(QString()); //clear as this could be most probably just "Unknown error" string. m_result.setErrorSql(sql); m_result.prependMessage(ERR_SQL_EXECUTION_ERROR, tr("Error while executing SQL statement.")); 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 nullptr; } //! Creates a KDbField list for kexi__fields, for sanity. Used by createTable() static KDbFieldList* createFieldListForKexi__Fields(KDbTableSchema *kexi__fieldsSchema) { if (!kexi__fieldsSchema) return nullptr; return kexi__fieldsSchema->subList( QList() << "t_id" << "f_type" << "f_name" << "f_length" << "f_precision" << "f_constraints" << "f_options" << "f_default" << "f_order" << "f_caption" << "f_help" ); } static QVariant buildLengthValue(const KDbField &f) { if (f.isFPNumericType()) { return f.scale(); } return f.maxLength(); } //! builds a list of values for field's @a f properties. Used by createTable(). static void buildValuesForKexi__Fields(QList& vals, KDbField* f) { const KDbField::Type type = f->type(); // cache: evaluating type of expressions can be expensive vals.clear(); vals << QVariant(f->table()->id()) << QVariant(type) << QVariant(f->name()) << buildLengthValue(*f) << QVariant(KDbField::isFPNumericType(type) ? f->precision() : 0) << QVariant(f->constraints()) << QVariant(f->options()) // KDb::variantToString() is needed here because the value can be of any QVariant type, // depending on f->type() << (f->defaultValue().isNull() ? QVariant() : QVariant(KDb::variantToString(f->defaultValue()))) << QVariant(f->order()) << QVariant(f->caption()) << QVariant(f->description()); } bool KDbConnection::storeMainFieldSchema(KDbField *field) { if (!field || !field->table()) return false; KDbFieldList *fl = createFieldListForKexi__Fields(d->table(QLatin1String("kexi__fields"))); if (!fl) return false; QList vals; buildValuesForKexi__Fields(vals, field); QList::ConstIterator valsIt = vals.constBegin(); bool first = true; KDbEscapedString sql("UPDATE kexi__fields SET "); foreach(KDbField *f, *fl->fields()) { sql.append((first ? QString() : QLatin1String(", ")) + f->name() + QLatin1Char('=') + d->driver->valueToSQL(f, *valsIt)); if (first) first = false; ++valsIt; } delete fl; sql.append(KDbEscapedString(" WHERE t_id=%1 AND f_name=%2") .arg(d->driver->valueToSQL(KDbField::Integer, field->table()->id())) .arg(escapeString(field->name()))); return executeSql(sql); } #define createTable_ERR \ { kdbDebug() << "ERROR!"; \ m_result.prependMessage(KDbConnection::tr("Creating table failed.")); \ rollbackAutoCommitTransaction(tg.transaction()); \ return false; } bool KDbConnection::createTable(KDbTableSchema* tableSchema, 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 = nullptr; 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()) != nullptr) { clearResult(); m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Table \"%1\" already exists.").arg(tableSchema->name())); return false; } } KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; if (internalTable) { if (!drv_containsTable(internalTable->name())) { // internal table may exist if (!drv_createTable(*tableSchema)) { createTable_ERR; } } } else { if (!drv_createTable(*tableSchema)) { createTable_ERR; } } //add the object data to kexi__* tables if (!internalTable) { //update kexi__objects if (!storeNewObjectData(tableSchema)) createTable_ERR; KDbTableSchema *ts = d->table(QLatin1String("kexi__fields")); if (!ts) return false; //for sanity: remove field info (if any) for this table id if (!KDb::deleteRecords(this, *ts, QLatin1String("t_id"), tableSchema->id())) return false; KDbFieldList *fl = createFieldListForKexi__Fields(ts); if (!fl) return false; foreach(KDbField *f, *tableSchema->fields()) { QList vals; buildValuesForKexi__Fields(vals, f); if (!insertRecord(fl, vals)) createTable_ERR; } delete fl; if (!storeExtendedTableSchemaData(tableSchema)) createTable_ERR; } bool res = commitAutoCommitTransaction(tg.transaction()); if (res) { if (!internalTable) { if (previousSchemaStillKept) { //remove previous table schema d->removeTable(*tableSchema); } } //store locally d->insertTable(tableSchema); //ok, this table is not created by the connection tableSchema->setConnection(this); } return res; } KDbTableSchema *KDbConnection::copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData) { clearResult(); if (this->tableSchema(tableSchema.name()) != &tableSchema) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableSchema.name())); return nullptr; } KDbTableSchema *copiedTable = new KDbTableSchema(tableSchema, false /* !copyId*/); // copy name, caption, description copiedTable->setName(newData.name()); copiedTable->setCaption(newData.caption()); copiedTable->setDescription(newData.description()); // copy the structure and data if (!createTable(copiedTable, false /* !replaceExisting */)) { delete copiedTable; return nullptr; } if (!drv_copyTableData(tableSchema, *copiedTable)) { dropTable(copiedTable); delete copiedTable; return nullptr; } return copiedTable; } KDbTableSchema *KDbConnection::copyTable(const QString &tableName, const KDbObject &newData) { clearResult(); KDbTableSchema* ts = tableSchema(tableName); if (!ts) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableName)); return nullptr; } return copyTable(*ts, newData); } bool KDbConnection::drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) { KDbEscapedString sql = KDbEscapedString("INSERT INTO %1 SELECT * FROM %2") .arg(escapeIdentifier(destinationTableSchema.name())) .arg(escapeIdentifier(tableSchema.name())); return executeSql(sql); } bool KDbConnection::removeObject(int objId) { clearResult(); //remove table schema from kexi__* tables KDbTableSchema *kexi__objects = d->table(QLatin1String("kexi__objects")); KDbTableSchema *kexi__objectdata = d->table(QLatin1String("kexi__objectdata")); if (!kexi__objects || !kexi__objectdata || !KDb::deleteRecords(this, *kexi__objects, QLatin1String("o_id"), objId) //schema entry || !KDb::deleteRecords(this, *kexi__objectdata, QLatin1String("o_id"), objId)) //data blocks { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Could not delete object's data.")); return false; } return true; } bool KDbConnection::drv_dropTable(const QString& tableName) { return executeSql(KDbEscapedString("DROP TABLE %1").arg(escapeIdentifier(tableName))); } tristate KDbConnection::dropTable(KDbTableSchema* tableSchema) { return 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 != nullptr; 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 (!executeSql( KDbEscapedString("UPDATE kexi__objects SET o_id=%1 WHERE o_id=%2 AND o_type=%3") .arg(d->driver->valueToSQL(KDbField::Integer, origID)) .arg(d->driver->valueToSQL(KDbField::Integer, tableSchema->id())) .arg(d->driver->valueToSQL(KDbField::Integer, int(KDb::TableObjectType))))) { return false; } if (!executeSql(KDbEscapedString("UPDATE kexi__fields SET t_id=%1 WHERE t_id=%2") .arg(d->driver->valueToSQL(KDbField::Integer, origID)) .arg(d->driver->valueToSQL(KDbField::Integer, tableSchema->id())))) { return false; } //maintain table ID d->changeTableId(tableSchema, origID); tableSchema->setId(origID); } if (!drv_alterTableName(tableSchema, newTableName)) { alterTableName_ERR; return false; } // Update kexi__objects //! @todo if (!executeSql(KDbEscapedString("UPDATE kexi__objects SET o_name=%1 WHERE o_id=%2") .arg(escapeString(tableSchema->name())) .arg(d->driver->valueToSQL(KDbField::Integer, tableSchema->id())))) { alterTableName_ERR; return false; } //! @todo what about caption? //restore old name: it will be changed soon! tableSchema->setName(oldTableName); if (!commitAutoCommitTransaction(tg.transaction())) { alterTableName_ERR; return false; } //update tableSchema: d->renameTable(tableSchema, newTableName); return true; } bool KDbConnection::drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) { const QString oldTableName = tableSchema->name(); tableSchema->setName(newName); if (!executeSql(KDbEscapedString("ALTER TABLE %1 RENAME TO %2") .arg(KDbEscapedString(escapeIdentifier(oldTableName)), KDbEscapedString(escapeIdentifier(newName))))) { tableSchema->setName(oldTableName); //restore old name return false; } return true; } bool KDbConnection::dropQuery(KDbQuerySchema* querySchema) { clearResult(); if (!querySchema) return false; KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; //remove query schema from kexi__objects table if (!removeObject(querySchema->id())) { return false; } //! @todo update any structure that depend on this table! d->removeQuery(querySchema); return commitAutoCommitTransaction(tg.transaction()); } bool KDbConnection::dropQuery(const QString& queryName) { clearResult(); KDbQuerySchema* qs = querySchema(queryName); if (!qs) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Query \"%1\" does not exist.").arg(queryName)); return false; } return dropQuery(qs); } bool KDbConnection::drv_createTable(const KDbTableSchema& tableSchema) { const KDbNativeStatementBuilder builder(this); KDbEscapedString sql; if (!builder.generateCreateTableStatement(&sql,tableSchema)) { return false; } //kdbDebug() << "******** " << sql; return executeSql(sql); } bool KDbConnection::drv_createTable(const QString& tableName) { KDbTableSchema *ts = tableSchema(tableName); if (!ts) return false; return drv_createTable(*ts); } bool KDbConnection::beginAutoCommitTransaction(KDbTransactionGuard* tg) { if ((d->driver->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 (!executeSql(KDbEscapedString("BEGIN"))) return nullptr; return new KDbTransactionData(this); } bool KDbConnection::drv_commitTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("COMMIT")); } bool KDbConnection::drv_rollbackTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("ROLLBACK")); } bool KDbConnection::drv_setAutoCommit(bool /*on*/) { return true; } KDbCursor* KDbConnection::executeQuery(const KDbEscapedString& sql, KDbCursor::Options options) { if (sql.isEmpty()) return nullptr; KDbCursor *c = prepareQuery(sql, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor *c = prepareQuery(query, params, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, KDbCursor::Options options) { return executeQuery(query, QList(), options); } KDbCursor* KDbConnection::executeQuery(KDbTableSchema* table, KDbCursor::Options options) { return executeQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbTableSchema* table, KDbCursor::Options options) { return prepareQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor* cursor = prepareQuery(query, options); if (cursor) cursor->setQueryParameters(params); return cursor; } bool KDbConnection::deleteCursor(KDbCursor *cursor) { if (!cursor) return false; if (cursor->connection() != this) {//illegal call kdbWarning() << "Could not delete the cursor not owned by the same connection!"; return false; } const bool ret = cursor->close(); CursorDeleter deleter(cursor); return ret; } //! @todo IMPORTANT: fix KDbConnection::setupObjectData() after refactoring bool KDbConnection::setupObjectData(const KDbRecordData &data, KDbObject *object) { if (data.count() < 5) { kdbWarning() << "Aborting, object data should have at least 5 elements, found" << data.count(); return false; } bool ok; const int id = data[0].toInt(&ok); if (!ok) return false; object->setId(id); const QString name(data[2].toString()); if (!KDb::isIdentifier(name)) { m_result = KDbResult(ERR_INVALID_IDENTIFIER, tr("Invalid object name \"%1\".").arg(name)); return false; } object->setName(name); object->setCaption(data[3].toString()); object->setDescription(data[4].toString()); // kdbDebug()<<"@@@ KDbConnection::setupObjectData() == " << sdata.schemaDataDebugString(); return true; } tristate KDbConnection::loadObjectData(int 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; } QSharedPointer result = insertRecord(fl.data(), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); if (!result) { return false; } //fetch newly assigned ID //! @todo safe to cast it? - quint64 obj_id = KDb::lastInsertedAutoIncValue(&result, QLatin1String("o_id"), *ts); + quint64 obj_id = KDb::lastInsertedAutoIncValue(result, QLatin1String("o_id"), *ts); //kdbDebug() << "NEW obj_id == " << obj_id; if (obj_id == std::numeric_limits::max()) { return false; } object->setId(obj_id); return true; } else { QScopedPointer fl(ts->subList( QList() << "o_id" << "o_type" << "o_name" << "o_caption" << "o_desc")); return fl && insertRecord(fl.data(), QVariant(object->id()), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); } } //existing object: return executeSql( KDbEscapedString("UPDATE kexi__objects SET o_type=%2, o_caption=%3, o_desc=%4 WHERE o_id=%1") .arg(d->driver->valueToSQL(KDbField::Integer, object->id())) .arg(d->driver->valueToSQL(KDbField::Integer, object->type())) .arg(escapeString(object->caption())) .arg(escapeString(object->description()))); } bool KDbConnection::storeObjectData(KDbObject* object) { return storeObjectDataInternal(object, false); } bool KDbConnection::storeNewObjectData(KDbObject* object) { return storeObjectDataInternal(object, true); } QString KDbConnection::escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const { return escapingType == KDb::KDbEscaping ? KDb::escapeIdentifier(id) : escapeIdentifier(id); } KDbCursor* KDbConnection::executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params) { Q_ASSERT(!sql.isEmpty() || query); clearResult(); if (!sql.isEmpty()) { return executeQuery(sql); } if (!query) { return nullptr; } if (params) { return executeQuery(query, *params); } return executeQuery(query); } tristate KDbConnection::querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, 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, nullptr, nullptr, addLimitTo1); } tristate KDbConnection::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, bool addLimitTo1) { return querySingleRecordInternal(data, nullptr, query, nullptr, addLimitTo1); } tristate KDbConnection::querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, const QList& params, bool addLimitTo1) { return querySingleRecordInternal(data, nullptr, 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, nullptr, nullptr, column, addLimitTo1); } tristate KDbConnection::querySingleString(KDbQuerySchema* query, QString* value, int column, bool addLimitTo1) { return querySingleStringInternal(nullptr, value, query, nullptr, column, addLimitTo1); } tristate KDbConnection::querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column, bool addLimitTo1) { return querySingleStringInternal(nullptr, 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, nullptr, nullptr, column, addLimitTo1); } tristate KDbConnection::querySingleNumber(KDbQuerySchema* query, int* number, int column, bool addLimitTo1) { return querySingleNumberInternal(nullptr, number, query, nullptr, column, addLimitTo1); } tristate KDbConnection::querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column, bool addLimitTo1) { return querySingleNumberInternal(nullptr, 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, nullptr, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, int column) { return queryStringListInternal(nullptr, list, query, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column) { return queryStringListInternal(nullptr, list, query, ¶ms, column, nullptr); } tristate KDbConnection::resultExists(const KDbEscapedString& sql, 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 nullptr; KDbField::Type f_type = (KDbField::Type)f_int_type; int f_len = qMax(0, data.at(3).toInt(&ok)); // defined limit if (!ok) { return nullptr; } 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 nullptr; KDbField::Constraints f_constr = (KDbField::Constraints)data.at(5).toInt(&ok); if (!ok) return nullptr; KDbField::Options f_opts = (KDbField::Options)data.at(6).toInt(&ok); if (!ok) return nullptr; QString name(data.at(2).toString()); if (!KDb::isIdentifier(name)) { name = KDb::stringToIdentifier(name); } KDbField *f = new KDbField( name, f_type, f_constr, f_opts, f_len, f_prec); QVariant defaultVariant = data.at(7); if (defaultVariant.isValid()) { defaultVariant = KDb::stringToVariant(defaultVariant.toString(), KDbField::variantType(f_type), &ok); if (ok) { f->setDefaultValue(defaultVariant); } else { kdbWarning() << "problem with KDb::stringToVariant(" << defaultVariant << ')'; ok = true; //problem with defaultValue is not critical } } f->setCaption(data.at(9).toString()); f->setDescription(data.at(10).toString()); return f; } KDbTableSchema* KDbConnection::setupTableSchema(const KDbRecordData &data) { KDbTableSchema *t = new KDbTableSchema(this); if (!setupObjectData(data, t)) { delete t; return nullptr; } 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 nullptr; } if (!cursor->moveFirst()) { if (!cursor->result().isError() && cursor->eof()) { m_result = KDbResult(tr("Table has no fields defined.")); } deleteCursor(cursor); delete t; return nullptr; } // For each field: load its schema KDbRecordData fieldData; bool ok = true; while (!cursor->eof()) { // kdbDebug()<<"@@@ f_name=="<value(2).asCString(); if (!cursor->storeCurrentRecord(&fieldData)) { ok = false; break; } KDbField *f = setupField(fieldData); if (!f || !t->addField(f)) { ok = false; break; } cursor->moveNext(); } if (!ok) {//error: deleteCursor(cursor); delete t; return nullptr; } if (!deleteCursor(cursor)) { delete t; return nullptr; } if (!loadExtendedTableSchemaData(t)) { delete t; return nullptr; } //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 nullptr; } 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 nullptr; } 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 executeSql(KDbEscapedString("UPDATE kexi__objectdata SET o_data=%1 WHERE o_id=%2 AND ") .arg(d->driver->valueToSQL(KDbField::LongText, dataString)) .arg(d->driver->valueToSQL(KDbField::Integer, objectID)) + sql_sub); } return executeSql( KDbEscapedString("INSERT INTO kexi__objectdata (o_id, o_data, o_sub_id) VALUES (") + KDbEscapedString::number(objectID) + ',' + d->driver->valueToSQL(KDbField::LongText, dataString) + ',' + d->driver->valueToSQL(KDbField::Text, dataID) + ')'); } bool KDbConnection::copyDataBlock(int sourceObjectID, int destObjectID, const QString &dataID) { if (sourceObjectID <= 0 || destObjectID <= 0) return false; if (sourceObjectID == destObjectID) return true; if (!removeDataBlock(destObjectID, dataID)) // remove before copying return false; KDbEscapedString sql = KDbEscapedString( "INSERT INTO kexi__objectdata SELECT %1, t.o_data, t.o_sub_id " "FROM kexi__objectdata AS t WHERE o_id=%2") .arg(d->driver->valueToSQL(KDbField::Integer, destObjectID)) .arg(d->driver->valueToSQL(KDbField::Integer, sourceObjectID)); if (!dataID.isEmpty()) { sql += KDbEscapedString(" AND ") + KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID); } return executeSql(sql); } bool KDbConnection::removeDataBlock(int objectID, const QString& dataID) { if (objectID <= 0) return false; if (dataID.isEmpty()) return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), QString::number(objectID)); else return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), KDbField::Integer, objectID, QLatin1String("o_sub_id"), KDbField::Text, dataID); } KDbQuerySchema* KDbConnection::setupQuerySchema(const KDbRecordData &data) { bool ok = true; const int objID = data[0].toInt(&ok); if (!ok) return nullptr; 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 nullptr; } KDbQuerySchema *query = nullptr; 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 nullptr; } if (!setupObjectData(data, query)) { delete query; return nullptr; } 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 nullptr; } 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 nullptr; } 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() : nullptr; if (!useRecordId && !pkey) { kdbWarning() << " -- NO MASTER TABLE's PKEY!"; m_result = KDbResult(ERR_UPDATE_NO_MASTER_TABLES_PKEY, tr("Could not update record because master table has no primary key defined.")); //! @todo perhaps we can try to update without using PKEY? return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("UPDATE ") + escapeIdentifier(mt->name()) + " SET "; KDbEscapedString sqlset, sqlwhere; sqlset.reserve(1024); sqlwhere.reserve(1024); KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); //gather the fields which are updated ( have values in KDbRecordEditBuffer) KDbFieldList affectedFields; for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { if (it.key()->field()->table() != mt) continue; // skip values for fields outside of the master table (e.g. a "visible value" of the lookup field) if (!sqlset.isEmpty()) sqlset += ','; KDbField* currentField = it.key()->field(); const bool affectedFieldsAddOk = affectedFields.addField(currentField); Q_ASSERT(affectedFieldsAddOk); sqlset += KDbEscapedString(escapeIdentifier(currentField->name())) + '=' + d->driver->valueToSQL(currentField, it.value()); } if (pkey) { const QVector pkeyFieldsOrder(query->pkeyFieldsOrder()); //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 = executeSql(sql); // postprocessing after update if (!drv_afterUpdate(mt->name(), &affectedFields)) return false; if (!res) { m_result = KDbResult(ERR_UPDATE_SERVER_ERROR, tr("Record updating on the server failed.")); return false; } //success: now also assign new values in memory: QHash columnsOrderExpanded; updateRecordDataWithNewValues(query, data, b, &columnsOrderExpanded); return true; } bool KDbConnection::insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); //--get PKEY /*disabled: there may be empty records (with autoinc) if (buf.dbBuffer().isEmpty()) { kdbDebug() << " -- NO CHANGES DATA!"; return true; }*/ KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_INSERT_NO_MASTER_TABLE, tr("Could not insert record because there is no master table specified.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; if (!getRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sqlcols, sqlvals; sqlcols.reserve(1024); sqlvals.reserve(1024); //insert the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(mt->name()) + " ("; KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); // add default values, if available (for any column without value explicitly set) const KDbQueryColumnInfo::Vector fieldsExpanded(query->fieldsExpanded(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 QSharedPointer result = insertRecordInternal(mt->name(), &affectedFields, sql); if (!result) { m_result = KDbResult(ERR_INSERT_SERVER_ERROR, tr("Record inserting on the server failed.")); return false; } //success: now also assign a new value in memory: QHash columnsOrderExpanded; updateRecordDataWithNewValues(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(), + = 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() : nullptr; //! @todo allow to delete from a table without pkey if (!useRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; m_result = KDbResult(ERR_DELETE_NO_MASTER_TABLES_PKEY, tr("Could not delete record because there is no primary key for master table specified.")); return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()) + " WHERE "; KDbEscapedString sqlwhere; sqlwhere.reserve(1024); if (pkey) { const QVector pkeyFieldsOrder(query->pkeyFieldsOrder()); //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 (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } bool KDbConnection::deleteAllRecords(KDbQuerySchema* query) { clearResult(); KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; return false; } KDbIndexSchema *pkey = mt->primaryKey(); if (!pkey || pkey->fields()->isEmpty()) { kdbWarning() << "-- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()); //kdbDebug() << "-- SQL == " << sql; if (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } 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