diff --git a/autotests/CMakeLists.txt b/autotests/CMakeLists.txt index 9b4478be..a239e9d3 100644 --- a/autotests/CMakeLists.txt +++ b/autotests/CMakeLists.txt @@ -1,55 +1,56 @@ remove_definitions( -DQT_NO_KEYWORDS -DQT_NO_SIGNALS_SLOTS_KEYWORDS -DQT_NO_CAST_FROM_ASCII -DQT_USE_QSTRINGBUILDER ) set(FILES_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}) set(KDB_LOCAL_PLUGINS_DIR ${PROJECT_BINARY_DIR}/plugins) add_definitions( -DFILES_OUTPUT_DIR=\"${FILES_OUTPUT_DIR}\" # make plugins work without installing them: -DKDB_LOCAL_PLUGINS_DIR=\"${KDB_LOCAL_PLUGINS_DIR}\" # nonstandard path for sqlite3 extensions, they would work too if we placed them # in ${KDB_LOCAL_PLUGINS_DIR}/sqlite3 but we want to test the "extraSqliteExtensionPaths" # connection option in ConnectionTest::testCreateDb(): -DSQLITE_LOCAL_ICU_EXTENSION_PATH=\"${KDB_LOCAL_PLUGINS_DIR}/sqlite3\" -DYYTOKENTYPE # this removes access to yytokentype enum as we should access KDb::Token instead ) include(ECMAddTests) find_package(Qt5Test) set_package_properties(Qt5Test PROPERTIES DESCRIPTION "Qt5Test library" URL "https://www.qt.io" TYPE RECOMMENDED PURPOSE "Required by tests") # A helper library for db-related tests add_library(kdbtestutils SHARED KDbTestUtils.cpp ) target_link_libraries(kdbtestutils PUBLIC KDb Qt5::Test ) generate_export_header(kdbtestutils) # Tests ecm_add_tests( ConnectionOptionsTest.cpp ConnectionTest.cpp DriverTest.cpp ExpressionsTest.cpp + QuerySchemaTest.cpp KDbTest.cpp LINK_LIBRARIES kdbtestutils ) if(NOT WIN32) #TODO enable for Windows when headers_test.sh is ported e.g. to python add_subdirectory(headers) endif() add_subdirectory(tools) add_subdirectory(parser) diff --git a/autotests/KDbTest.cpp b/autotests/KDbTest.cpp index 0c8ee420..f11855ec 100644 --- a/autotests/KDbTest.cpp +++ b/autotests/KDbTest.cpp @@ -1,1226 +1,1189 @@ /* This file is part of the KDE project Copyright (C) 2015-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 "KDbTest.h" #include #include #include #include #include QTEST_GUILESS_MAIN(KDbTest) -Q_DECLARE_METATYPE(KDbField::TypeGroup) -Q_DECLARE_METATYPE(KDbField::Type) -Q_DECLARE_METATYPE(KDb::Signedness) -Q_DECLARE_METATYPE(QList) -Q_DECLARE_METATYPE(KDb::BLOBEscapingType) - void KDbTest::initTestCase() { } void KDbTest::testVersionInfo() { KDbVersionInfo info = KDb::version(); KDbVersionInfo info2(KDb::version()); QCOMPARE(info, info2); KDbVersionInfo info3(info.major(), info.minor(), info.release()); QCOMPARE(info, info3); QVERIFY(KDbVersionInfo(0, 0, 0).isNull()); QVERIFY(!info.isNull()); QVERIFY(!info2.isNull()); QVERIFY(!info3.isNull()); } //! @todo add tests requiring connection #if 0 //! @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) //! @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) //! @overload bool deleteRecords(KDbConnection*, const QString&, const QString&, const QString&); inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString &keyname, const QString &keyval) //! @overload bool deleteRecords(KDbConnection*, const KDbTableSchema&, const QString&, const QString&); inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString& keyname, int keyval) //! @overload bool deleteRecords(KDbConnection*, const KDbTableSchema&, const QString&, int); inline bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString& keyname, int 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) #endif void KDbTest::testFieldTypes() { QCOMPARE(KDbField::FirstType, KDbField::Byte); QCOMPARE(KDbField::LastType, KDbField::BLOB); QVERIFY(KDbField::FirstType < KDbField::LastType); } void KDbTest::testFieldTypesForGroup_data() { QTest::addColumn("typeGroup"); QTest::addColumn>("types"); int c = 0; ++c; QTest::newRow("invalid") << KDbField::InvalidGroup << (QList() << KDbField::InvalidType); ++c; QTest::newRow("text") << KDbField::TextGroup << (QList() << KDbField::Text << KDbField::LongText); ++c; QTest::newRow("integer") << KDbField::IntegerGroup << (QList() << KDbField::Byte << KDbField::ShortInteger << KDbField::Integer << KDbField::BigInteger); ++c; QTest::newRow("float") << KDbField::FloatGroup << (QList() << KDbField::Float << KDbField::Double); ++c; QTest::newRow("boolean") << KDbField::BooleanGroup << (QList() << KDbField::Boolean); ++c; QTest::newRow("datetime") << KDbField::DateTimeGroup << (QList() << KDbField::Date << KDbField::DateTime << KDbField::Time); ++c; QTest::newRow("blob") << KDbField::BLOBGroup << (QList() << KDbField::BLOB); QCOMPARE(c, KDbField::typeGroupsCount()); // make sure we're checking everything } void KDbTest::testFieldTypesForGroup() { QFETCH(KDbField::TypeGroup, typeGroup); QFETCH(QList, types); QCOMPARE(KDb::fieldTypesForGroup(typeGroup), types); } void KDbTest::testFieldTypeNamesAndStringsForGroup_data() { QTest::addColumn("typeGroup"); QTest::addColumn>("typeNames"); QTest::addColumn("typeStrings"); int c = 0; ++c; QTest::newRow("invalid") << KDbField::InvalidGroup << (QList() << "Invalid Type") << (QStringList() << "InvalidType"); ++c; QTest::newRow("text") << KDbField::TextGroup << (QList() << "Text" << "Long Text") << (QStringList() << "Text" << "LongText"); ++c; QTest::newRow("integer") << KDbField::IntegerGroup << (QList() << "Byte" << "Short Integer Number" << "Integer Number" << "Big Integer Number") << (QStringList() << "Byte" << "ShortInteger" << "Integer" << "BigInteger"); ++c; QTest::newRow("float") << KDbField::FloatGroup << (QList() << "Single Precision Number" << "Double Precision Number") << (QStringList() << "Float" << "Double"); ++c; QTest::newRow("boolean") << KDbField::BooleanGroup << (QList() << "Yes/No Value") << (QStringList() << "Boolean"); ++c; QTest::newRow("datetime") << KDbField::DateTimeGroup << (QList() << "Date" << "Date and Time" << "Time") << (QStringList() << "Date" << "DateTime" << "Time"); ++c; QTest::newRow("blob") << KDbField::BLOBGroup << (QList() << "Object") << (QStringList() << "BLOB"); QCOMPARE(c, KDbField::typeGroupsCount()); // make sure we're checking everything } void KDbTest::testFieldTypeNamesAndStringsForGroup() { QFETCH(KDbField::TypeGroup, typeGroup); QFETCH(QList, typeNames); QFETCH(QStringList, typeStrings); QStringList translatedNames; foreach(const QByteArray &name, typeNames) { translatedNames.append(KDbField::tr(name.constData())); } QCOMPARE(KDb::fieldTypeNamesForGroup(typeGroup), translatedNames); QCOMPARE(KDb::fieldTypeStringsForGroup(typeGroup), typeStrings); } void KDbTest::testDefaultFieldTypeForGroup() { int c = 0; ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::InvalidGroup), KDbField::InvalidType); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::TextGroup), KDbField::Text); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::IntegerGroup), KDbField::Integer); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::FloatGroup), KDbField::Double); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::BooleanGroup), KDbField::Boolean); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::DateTimeGroup), KDbField::Date); ++c; QCOMPARE(KDb::defaultFieldTypeForGroup(KDbField::BLOBGroup), KDbField::BLOB); QCOMPARE(c, KDbField::typeGroupsCount()); // make sure we're checking everything } void KDbTest::testSimplifiedFieldTypeName() { int c = 0; ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::InvalidType), KDbField::tr("Invalid Group")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Byte), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::ShortInteger), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Integer), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::BigInteger), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Boolean), KDbField::tr("Yes/No")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Date), KDbField::tr("Date/Time")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::DateTime), KDbField::tr("Date/Time")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Time), KDbField::tr("Date/Time")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Float), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Double), KDbField::tr("Number")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Text), KDbField::tr("Text")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::LongText), KDbField::tr("Text")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::BLOB), KDbField::tr("Image")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Null), KDbField::tr("Invalid Group")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Asterisk), KDbField::tr("Invalid Group")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Enum), KDbField::tr("Invalid Group")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Map), KDbField::tr("Invalid Group")); ++c; QCOMPARE(KDb::simplifiedFieldTypeName(KDbField::Tuple), KDbField::tr("Invalid Group")); QCOMPARE(c, KDbField::typesCount() + KDbField::specialTypesCount()); // make sure we're checking everything } void KDbTest::testIsEmptyValue_data() { QTest::addColumn("type"); QTest::addColumn("value"); QTest::addColumn("result"); QTest::addColumn("resultForNullValue"); QTest::addColumn("resultForEmptyString"); int c = 0; ++c; QTest::newRow("Invalid") << KDbField::InvalidType << QVariant("abc") << false << true << false; ++c; QTest::newRow("Byte") << KDbField::Byte << QVariant(17) << false << true << false; ++c; QTest::newRow("ShortInteger") << KDbField::ShortInteger << QVariant(1733) << false << true << false; ++c; QTest::newRow("Integer") << KDbField::Integer << QVariant(11733) << false << true << false; ++c; QTest::newRow("BigInteger") << KDbField::BigInteger << QVariant(0xffffff12) << false << true << false; ++c; QTest::newRow("Boolean") << KDbField::Boolean << QVariant(false) << false << true << false; ++c; QTest::newRow("Date") << KDbField::Date << QVariant(QDate(2015, 11, 07)) << false << true << false; ++c; QTest::newRow("DateTime") << KDbField::DateTime << QVariant(QDateTime(QDate(2015, 11, 07), QTime(12, 58, 17))) << false << true << false; ++c; QTest::newRow("Time") << KDbField::Time << QVariant(QTime(12, 58, 17)) << false << true << false; ++c; QTest::newRow("Float") << KDbField::Float << QVariant(3.14) << false << true << false; ++c; QTest::newRow("Double") << KDbField::Double << QVariant(3.1415) << false << true << false; ++c; QTest::newRow("Text") << KDbField::Text << QVariant(QLatin1String("abc")) << false << false << true; ++c; QTest::newRow("LongText") << KDbField::LongText << QVariant(QLatin1String("abc")) << false << false << true; ++c; QTest::newRow("BLOB") << KDbField::LongText << QVariant(QByteArray(5, 'X')) << false << false << true; ++c; QTest::newRow("Null") << KDbField::Null << QVariant(123) << false << true << false; ++c; QTest::newRow("Asterisk") << KDbField::Asterisk << QVariant(123) << false << true << false; ++c; QTest::newRow("Enum") << KDbField::Enum << QVariant(123) << false << true << false; ++c; QTest::newRow("Map") << KDbField::Map << QVariant(123) << false << true << false; ++c; QTest::newRow("Tuple") << KDbField::Tuple << QVariant(123) << false << true << false; QCOMPARE(c, KDbField::typesCount() + KDbField::specialTypesCount()); } void KDbTest::testIsEmptyValue() { QFETCH(KDbField::Type, type); QFETCH(QVariant, value); QFETCH(bool, result); QFETCH(bool, resultForNullValue); QFETCH(bool, resultForEmptyString); QCOMPARE(KDb::isEmptyValue(type, QVariant()), resultForNullValue); QCOMPARE(KDb::isEmptyValue(type, QVariant(QString(""))), resultForEmptyString); QCOMPARE(KDb::isEmptyValue(type, value), result); } //! @todo add tests #if 0 /*! 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, KDbField::InvalidType is returned. This can be used when type information is deserialized from a string or QVariant. */ 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. */ 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 src/generated/sqlkeywords.cpp in the KDb source code. @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 w using 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. */ KDB_EXPORT QString escapeString(const QString& string); /** * @brief Returns escaped string @a string * * If @a drv driver is present, it is used to perform escaping, otherwise escapeString() is used * so the KDbSQL dialect-escaping is performed. */ KDB_EXPORT KDbEscapedString escapeString(KDbDriver *drv, const QString& string); /** * @brief Returns escaped string @a string * * If @a conn is present, its driver is used to perform escaping, otherwise escapeString() is used * so the KDbSQL dialect-escaping is performed. */ KDB_EXPORT KDbEscapedString escapeString(KDbConnection *conn, const QString& string); #endif void KDbTest::testUnescapeString_data() { QTest::addColumn("sequence"); QTest::addColumn("result"); QTest::addColumn("quote"); // can be ' or ", if 0 then both variants are checked QTest::addColumn("errorPosition"); QTest::addColumn("errorPositionWhenAppended"); // quote-independent cases, success #define T2(tag, sequence, result, quote) QTest::newRow(tag) << QString::fromUtf8(sequence) \ << QString::fromUtf8(result) << quote << -1 << -1 #define T(tag, sequence, result) T2(tag, sequence, result, '\0') QTest::newRow("null") << QString() << QString() << '\0' << -1 << -1; QTest::newRow("\\0") << QString("\\0") << QString(QLatin1Char('\0')) << '\0' << -1 << -1; const char *s = " String without escaping %_? 𝌆 ©"; T("without escaping", s, s); T("empty", "", ""); T("\\'", "\\'", "'"); T("\\\"", "\\\"", "\""); T("\\\\", "\\\\", "\\"); T("\\b", "\\b", "\b"); T("\\f", "\\f", "\f"); T("\\n", "\\n", "\n"); T("\\r", "\\r", "\r"); T("\\t", "\\t", "\t"); T("\\v", "\\v", "\v"); T("_\\_", "_\\_", "__"); T("?\\?", "?\\?", "??"); T("%\\%", "%\\%", "%%"); T("ignored \\ in \\a", "\\a", "a"); T("ignored \\ in \\♥", "\\♥ ", "♥ "); T("ignored \\ in 𝌆\\\\\\a", "𝌆\\\\\\a", "𝌆\\a"); T("unfinished \\", "\\", ""); T("unfinished \\ 2", "one two\\", "one two"); T("\\xA9", "\\xA9", "©"); T("\\xa9\\xa9", "\\xa9\\xa9", "©©"); QTest::newRow("\\x00") << QString("\\x00") << QString(QLatin1Char('\0')) << '\0' << -1 << -1; QTest::newRow("\\u0000") << QString("\\u0000") << QString(QChar(static_cast(0))) << '\0' << -1 << -1; T("\\u2665", "\\u2665", "♥"); #ifndef _MSC_VER // does not work with MSVC: "warning C4566: character represented // by universal-character-name cannot be represented in the current code page" T("\\xff", "\\xff", "\u00ff"); T("\\uffff", "\\uffff", "\uffff"); #endif QTest::newRow("\\u{0}") << QString("\\u{0}") << QString(QLatin1Char('\0')) << '\0' << -1 << -1; QTest::newRow("\\u{0000000000}") << QString("\\u{0000000000}") << QString(QLatin1Char('\0')) << '\0' << -1 << -1; T("\\u{A9}", "\\u{A9}", "©"); T("\\u{a9}", "\\u{a9}", "©"); T("\\u{0a9}", "\\u{0a9}", "©"); T("\\u{00a9}", "\\u{00a9}", "©"); T("\\u{2665}", "\\u{2665}", "♥"); T("\\u{02665}", "\\u{02665}", "♥"); QTest::newRow("\\u{1D306}") << QString("\\u{1D306}") << QString(QChar(0x1D306)) << '\0' << -1 << -1; QTest::newRow("\\u{1d306}") << QString("\\u{1d306}") << QString(QChar(0x1d306)) << '\0' << -1 << -1; QTest::newRow("\\u{01D306}") << QString("\\u{01D306}") << QString(QChar(0x1D306)) << '\0' << -1 << -1; QTest::newRow("\\u{01d306}") << QString("\\u{01d306}") << QString(QChar(0x1d306)) << '\0' << -1 << -1; QTest::newRow("\\u{00001D306}") << QString("\\u{00001D306}") << QString(QChar(0x1D306)) << '\0' << -1 << -1; QTest::newRow("\\u{10FFFF}") << QString("\\u{10FFFF}") << QString(QChar(0x10FFFF)) << '\0' << -1 << -1; // quote-dependent cases, success T2("2x ' for ' quote", "''", "'", '\''); T2("4x ' for ' quote", "''''", "''", '\''); T2("2x \" for ' quote", "\"\"", "\"\"", '\''); T2("3x \" for ' quote", "\"\"\"", "\"\"\"", '\''); T2("2x ' for \" quote", "''", "''", '"'); T2("3x ' for \" quote", "'''", "'''", '"'); T2("2x \" for \" quote", "\"\"", "\"", '"'); T2("4x \" for \" quote", "\"\"\"\"", "\"\"", '"'); #undef T #undef T2 // failures QTest::newRow("invalid quote") << QString::fromUtf8("abc") << QString() << 'x' << 0 << 0; #define T(tag, sequence, quote, errorPosition, errorPositionWhenAppended) \ QTest::newRow(tag) << QString::fromUtf8(sequence) << QString() << quote \ << errorPosition << errorPositionWhenAppended T("missing ' quote", "'", '\'', 0, 0); T("missing \" quote", "\"", '"', 0, 0); T("invalid \\x", "\\x", '\0', 1, 2); T("invalid \\xQ", "\\xQ", '\0', 2, 2); T("invalid \\xQt", "\\xQt", '\0', 2, 2); T("invalid \\xAQ", "\\xAQ", '\0', 3, 3); T("invalid \\u", "\\u", '\0', 1, 2); T("invalid \\ua", "\\ua", '\0', 2, 3); T("invalid \\u40", "\\u40", '\0', 3, 4); T("invalid \\u405", "\\u405", '\0', 4, 5); T("invalid \\uQ", "\\uQ", '\0', 2, 2); T("invalid \\uQt", "\\uQt", '\0', 2, 2); T("invalid \\uQt5", "\\uQt5", '\0', 2, 2); T("invalid \\uQt57", "\\uQt57", '\0', 2, 2); T("invalid \\uaQ", "\\uaQ", '\0', 3, 3); T("invalid \\uabQ", "\\uabQ", '\0', 4, 4); T("invalid \\uabcQ", "\\uabcQ", '\0', 5, 5); T("invalid \\u{", "\\u{", '\0', 2, 3); T("invalid \\u{26", "\\u{26", '\0', 4, 5); T("invalid \\u{266", "\\u{266", '\0', 5, 6); T("invalid \\u{2665", "\\u{2665", '\0', 6, 7); T("invalid \\u{2665a", "\\u{2665a", '\0', 7, 8); T("invalid \\u{}", "\\u{}", '\0', 3, 3); T("invalid \\u{Q}", "\\u{Q}", '\0', 3, 3); T("invalid \\u{Qt}", "\\u{Qt}", '\0', 3, 3); T("invalid \\u{Qt5}", "\\u{Qt5}", '\0', 3, 3); T("invalid \\u{Qt57}", "\\u{Qt57}", '\0', 3, 3); T("invalid \\u{Qt57", "\\u{Qt57", '\0', 3, 3); T("invalid \\u{aQ}", "\\u{aQ}", '\0', 4, 4); T("invalid \\u{abQ}", "\\u{abQ}", '\0', 5, 5); T("invalid \\u{abcQ}", "\\u{abcQ}", '\0', 6, 6); T("invalid \\u{abcdQ}", "\\u{abcdQ}", '\0', 7, 7); T("invalid \\u{abcdQ}", "\\u{abcdQ}", '\0', 7, 7); T("invalid \\u{abcdfQ}", "\\u{abcdfQ}", '\0', 8, 8); T("invalid too large \\u{110000}", "\\u{110000}", '\0', 8, 8); T("invalid too large \\u{1100000}", "\\u{1100000}", '\0', 8, 8); T("invalid too large \\u{00110000}", "\\u{00110000}", '\0', 10, 10); } void KDbTest::testUnescapeStringHelper(const QString &sequenceString, const QString &resultString_, char quote, int errorPosition, int offset) { int actualErrorPosition = -2; QString resultString(resultString_); if (errorPosition >= 0) { errorPosition += offset; resultString.clear(); } //qDebug() << KDb::unescapeString("\\0bar", '\'', &errorPosition); #define COMPARE(x, y) \ if (x != y) { \ qDebug() << "sequenceString:" << sequenceString << "resultString:" << resultString; \ } \ QCOMPARE(x, y) if (quote == 0) { // both cases COMPARE(KDb::unescapeString(sequenceString, '\'', &actualErrorPosition), resultString); COMPARE(actualErrorPosition, errorPosition); COMPARE(KDb::unescapeString(sequenceString, '\'', nullptr), resultString); COMPARE(KDb::unescapeString(sequenceString, '"', &actualErrorPosition), resultString); COMPARE(actualErrorPosition, errorPosition); COMPARE(KDb::unescapeString(sequenceString, '"', nullptr), resultString); } else { if (quote != '\'' && quote != '"') { resultString.clear(); errorPosition = 0; } COMPARE(KDb::unescapeString(sequenceString, quote, &actualErrorPosition), resultString); COMPARE(actualErrorPosition, errorPosition); COMPARE(KDb::unescapeString(sequenceString, quote, nullptr), resultString); } #undef CHECK_POS } void KDbTest::testUnescapeString() { QFETCH(QString, sequence); QFETCH(QString, result); QFETCH(char, quote); QFETCH(int, errorPosition); QFETCH(int, errorPositionWhenAppended); testUnescapeStringHelper(sequence, result, quote, errorPosition, 0); testUnescapeStringHelper("foo" + sequence, "foo" + result, quote, errorPosition, 3); testUnescapeStringHelper(sequence + " bar", result + " bar", quote, errorPositionWhenAppended, 0); testUnescapeStringHelper("foo" + sequence + " bar", "foo" + result + " bar", quote, errorPositionWhenAppended, 3); } void KDbTest::testEscapeBLOB_data() { QTest::addColumn("blob"); QTest::addColumn("escapedX"); QTest::addColumn("escaped0x"); QTest::addColumn("escapedHex"); QTest::addColumn("escapedOctal"); QTest::addColumn("escapedBytea"); QTest::newRow("") << QByteArray() << QString("X''") << QString() << QString("") << QString("''") << QString("E'\\\\x'::bytea"); QTest::newRow("0,1,k") << QByteArray("\0\1k", 3) << QString("X'00016B'") << QString("0x00016B") << QString("00016B") << QString("'\\\\000\\\\001k'") << QString("E'\\\\x00016B'::bytea"); QTest::newRow("ABC\\\\0") << QByteArray("ABC\0", 4) << QString("X'41424300'") << QString("0x41424300") << QString("41424300") << QString("'ABC\\\\000'") << QString("E'\\\\x41424300'::bytea"); QTest::newRow("'") << QByteArray("'") << QString("X'27'") << QString("0x27") << QString("27") << QString("'\\\\047'") << QString("E'\\\\x27'::bytea"); QTest::newRow("\\") << QByteArray("\\") << QString("X'5C'") << QString("0x5C") << QString("5C") << QString("'\\\\134'") << QString("E'\\\\x5C'::bytea"); } void KDbTest::testEscapeBLOB() { QFETCH(QByteArray, blob); QFETCH(QString, escapedX); QFETCH(QString, escaped0x); QFETCH(QString, escapedHex); QFETCH(QString, escapedOctal); QFETCH(QString, escapedBytea); QCOMPARE(KDb::escapeBLOB(blob, KDb::BLOBEscapeXHex), escapedX); QCOMPARE(KDb::escapeBLOB(blob, KDb::BLOBEscape0xHex), escaped0x); QCOMPARE(KDb::escapeBLOB(blob, KDb::BLOBEscapeHex), escapedHex); QCOMPARE(KDb::escapeBLOB(blob, KDb::BLOBEscapeOctal), escapedOctal); QCOMPARE(KDb::escapeBLOB(blob, KDb::BLOBEscapeByteaHex), escapedBytea); } void KDbTest::testPgsqlByteaToByteArray() { QCOMPARE(KDb::pgsqlByteaToByteArray(nullptr, 0), QByteArray()); QCOMPARE(KDb::pgsqlByteaToByteArray("", 0), QByteArray()); QCOMPARE(KDb::pgsqlByteaToByteArray(" ", 0), QByteArray()); QCOMPARE(KDb::pgsqlByteaToByteArray("\\101"), QByteArray("A")); QCOMPARE(KDb::pgsqlByteaToByteArray("\\101", 4), QByteArray("A")); QCOMPARE(KDb::pgsqlByteaToByteArray("\\101B", 4), QByteArray("A")); // cut-off at #4 QCOMPARE(KDb::pgsqlByteaToByteArray("\\'\\\\\\'"), QByteArray("\'\\\'")); QCOMPARE(KDb::pgsqlByteaToByteArray("\\\\a\\377bc\\'d\"\n"), QByteArray("\\a\377bc\'d\"\n")); } void KDbTest::testXHexToByteArray_data() { QTest::addColumn("data"); QTest::addColumn("length"); // -2 means "compute length", other values: pass it as is QTest::addColumn("ok"); QTest::addColumn("result"); QTest::newRow("") << QByteArray() << 0 << false << QByteArray(); QTest::newRow("bad prefix") << QByteArray("bad") << -2 << false << QByteArray(); QTest::newRow("X") << QByteArray("X") << -2 << false << QByteArray(); QTest::newRow("X'") << QByteArray("X'") << -2 << false << QByteArray(); QTest::newRow("X''") << QByteArray("X''") << -2 << true << QByteArray(); QTest::newRow("X'1") << QByteArray("X'1") << -2 << false << QByteArray(); QTest::newRow("X'1' cut") << QByteArray("X'1'") << 3 << false << QByteArray(); QTest::newRow("X'1'") << QByteArray("X'1'") << -2 << true << QByteArray("\1"); QTest::newRow("X'0'") << QByteArray("X'0'") << -2 << true << QByteArray("\0", 1); QTest::newRow("X'000'") << QByteArray("X'000'") << -2 << true << QByteArray("\0\0", 2); QTest::newRow("X'01'") << QByteArray("X'01'") << -2 << true << QByteArray("\1"); QTest::newRow("X'FeAb2C'") << QByteArray("X'FeAb2C'") << -2 << true << QByteArray("\376\253\54"); } void KDbTest::testXHexToByteArray() { QFETCH(QByteArray, data); QFETCH(int, length); QFETCH(bool, ok); QFETCH(QByteArray, result); bool actualOk; QCOMPARE(KDb::xHexToByteArray(data.constData(), length == -1 ? data.length() : length, &actualOk), result); QCOMPARE(actualOk, ok); QCOMPARE(KDb::xHexToByteArray(data.constData(), length, nullptr), result); } void KDbTest::testZeroXHexToByteArray_data() { QTest::addColumn("data"); QTest::addColumn("length"); // -2 means "compute length", other values: pass it as is QTest::addColumn("ok"); QTest::addColumn("result"); QTest::newRow("") << QByteArray() << 0 << false << QByteArray(); QTest::newRow("0") << QByteArray("0") << -2 << false << QByteArray(); QTest::newRow("0x") << QByteArray("0x") << -2 << false << QByteArray(); QTest::newRow("0X22") << QByteArray("0X22") << -2 << false << QByteArray(); QTest::newRow("bad prefix") << QByteArray("bad") << -2 << false << QByteArray(); QTest::newRow("0x0") << QByteArray("0x0") << -2 << true << QByteArray("\0", 1); QTest::newRow("0x0 cut") << QByteArray("0x0") << 2 << false << QByteArray(); QTest::newRow("0X0") << QByteArray("0X0") << -2 << false << QByteArray(); QTest::newRow("0x0123") << QByteArray("0x0123") << -2 << true << QByteArray("\1\43"); QTest::newRow("0x0123 cut") << QByteArray("0x0123") << 4 << true << QByteArray("\1"); QTest::newRow("0x00000'") << QByteArray("0x00000") << -2 << true << QByteArray("\0\0\0", 3); QTest::newRow("0xFeAb2C") << QByteArray("0xFeAb2C") << -2 << true << QByteArray("\376\253\54"); } void KDbTest::testZeroXHexToByteArray() { QFETCH(QByteArray, data); QFETCH(int, length); QFETCH(bool, ok); QFETCH(QByteArray, result); bool actualOk; QCOMPARE(KDb::zeroXHexToByteArray(data.constData(), length == -1 ? data.length() : length, &actualOk), result); QCOMPARE(actualOk, ok); QCOMPARE(KDb::zeroXHexToByteArray(data.constData(), length, nullptr), result); } //! @todo add tests #if 0 /*! @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); /*! @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); #endif void KDbTest::testCstringToVariant_data() { QTest::addColumn("data"); // QString() -> 0, QString("") -> empty string "" QTest::addColumn("type"); QTest::addColumn("length"); QTest::addColumn("variant"); QTest::addColumn("signedness"); QTest::addColumn("okResult"); int c = 0; ++c; QTest::newRow("invalid1") << QString() << KDbField::InvalidType << -1 << QVariant() << KDb::Signed << false; QTest::newRow("invalid2") << "" << KDbField::InvalidType << -1 << QVariant() << KDb::Signed << false; QTest::newRow("invalid3") << "abc" << KDbField::InvalidType << 3 << QVariant() << KDb::Signed << false; ++c; QTest::newRow("byte1") << "0" << KDbField::Byte << 1 << QVariant(0) << KDb::Signed << true; QTest::newRow("ubyte1") << "0" << KDbField::Byte << 1 << QVariant(0) << KDb::Unsigned << true; QTest::newRow("byte2") << "42" << KDbField::Byte << -1 << QVariant(42) << KDb::Signed << true; QTest::newRow("ubyte2") << "42" << KDbField::Byte << -1 << QVariant(42) << KDb::Unsigned << true; QTest::newRow("byte3") << "129" << KDbField::Byte << -1 << QVariant() << KDb::Signed << false; QTest::newRow("ubyte3") << "129" << KDbField::Byte << -1 << QVariant(129) << KDb::Unsigned << true; QTest::newRow("byte4") << "-128" << KDbField::Byte << -1 << QVariant(-128) << KDb::Signed << true; QTest::newRow("ubyte4") << "-128" << KDbField::Byte << -1 << QVariant() << KDb::Unsigned << false; ++c; QTest::newRow("short1") << "-123" << KDbField::ShortInteger << -1 << QVariant(-123) << KDb::Signed << true; QTest::newRow("short2") << "942" << KDbField::ShortInteger << -1 << QVariant(942) << KDb::Signed << true; QTest::newRow("short3") << "32767" << KDbField::ShortInteger << -1 << QVariant(32767) << KDb::Signed << true; QTest::newRow("short4") << "32768" << KDbField::ShortInteger << -1 << QVariant() << KDb::Signed << false; QTest::newRow("ushort4") << "32768" << KDbField::ShortInteger << -1 << QVariant(32768) << KDb::Unsigned << true; QTest::newRow("short5") << "-32768" << KDbField::ShortInteger << -1 << QVariant(-32768) << KDb::Signed << true; QTest::newRow("ushort5") << "-32768" << KDbField::ShortInteger << -1 << QVariant() << KDb::Unsigned << false; ++c; QTest::newRow("int1") << QString::number(0x07FFFFFFF) << KDbField::Integer << -1 << QVariant(0x07FFFFFFF) << KDb::Signed << true; QTest::newRow("uint1") << QString::number(0x07FFFFFFF) << KDbField::Integer << -1 << QVariant(0x07FFFFFFF) << KDb::Unsigned << true; QTest::newRow("int2") << QString::number(-0x07FFFFFFF) << KDbField::Integer << -1 << QVariant(-0x07FFFFFFF) << KDb::Signed << true; QTest::newRow("uint2") << QString::number(-0x07FFFFFFF) << KDbField::Integer << -1 << QVariant() << KDb::Unsigned << false; QTest::newRow("int3") << QString::number(std::numeric_limits::min()) << KDbField::Integer << -1 << QVariant() << KDb::Signed << false; QTest::newRow("uint4") << "-1" << KDbField::Integer << -1 << QVariant() << KDb::Unsigned << false; QTest::newRow("int4") << "-1" << KDbField::Integer << -1 << QVariant(-1) << KDb::Signed << true; //!< @todo cannot be larger? ++c; QTest::newRow("bigint1") << QString::number(0x07FFFFFFF) << KDbField::BigInteger << -1 << QVariant(0x07FFFFFFF) << KDb::Signed << true; QTest::newRow("ubigint1") << QString::number(0x07FFFFFFF) << KDbField::BigInteger << -1 << QVariant(0x07FFFFFFF) << KDb::Unsigned << true; QTest::newRow("bigint2") << QString::number(-0x07FFFFFFF) << KDbField::BigInteger << -1 << QVariant(-0x07FFFFFFF) << KDb::Signed << true; QTest::newRow("ubigint2") << QString::number(-0x07FFFFFFF) << KDbField::BigInteger << -1 << QVariant() << KDb::Unsigned << false; QTest::newRow("bigint3") << QString::number(std::numeric_limits::min()) << KDbField::BigInteger << -1 << QVariant() << KDb::Signed << false; QTest::newRow("ubigint4") << "-1" << KDbField::BigInteger << -1 << QVariant() << KDb::Unsigned << false; QTest::newRow("bigint4") << "-1" << KDbField::BigInteger << -1 << QVariant(-1) << KDb::Signed << true; ++c; QTest::newRow("bool0") << "0" << KDbField::Boolean << -1 << QVariant(false) << KDb::Signed << true; QTest::newRow("bool1") << "1" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; QTest::newRow("bool-") << "-" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; QTest::newRow("bool5") << "5" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; QTest::newRow("bool false") << "false" << KDbField::Boolean << -1 << QVariant(false) << KDb::Signed << true; QTest::newRow("bool False") << "False" << KDbField::Boolean << -1 << QVariant(false) << KDb::Signed << true; QTest::newRow("bool TRUE") << "TRUE" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; QTest::newRow("bool true") << "true" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; QTest::newRow("bool no") << "no" << KDbField::Boolean << -1 << QVariant(true) << KDb::Signed << true; // surprised? See docs for QVariant::toBool(). ++c; //! @todo support Date ++c; //! @todo support DateTime ++c; //! @todo support Time ++c; //! @todo support Float ++c; //! @todo support Double ++c; //! @todo support Text ++c; //! @todo support LongText ++c; //! @todo support BLOB ++c; QTest::newRow("Null") << " " << KDbField::Null << -1 << QVariant() << KDb::Signed << false; ++c; QTest::newRow("Asterisk") << " " << KDbField::Asterisk << -1 << QVariant() << KDb::Signed << false; ++c; QTest::newRow("Enum") << " " << KDbField::Enum << -1 << QVariant() << KDb::Signed << false; ++c; QTest::newRow("Map") << " " << KDbField::Map << -1 << QVariant() << KDb::Signed << false; ++c; QTest::newRow("Tuple") << " " << KDbField::Tuple << -1 << QVariant() << KDb::Signed << false; QCOMPARE(c, KDbField::typesCount() + KDbField::specialTypesCount()); } void KDbTest::testCstringToVariant() { QFETCH(QString, data); QFETCH(KDbField::Type, type); QFETCH(int, length); QFETCH(QVariant, variant); QFETCH(KDb::Signedness, signedness); QFETCH(bool, okResult); bool ok; const QByteArray ba(data.toUtf8()); // to avoid pointer to temp. const char *realData = ba.isNull() ? nullptr : ba.constData(); QCOMPARE(KDb::cstringToVariant(realData, type, &ok, length, signedness), variant); QCOMPARE(ok, okResult); QCOMPARE(KDb::cstringToVariant(realData, type, nullptr, length, signedness), variant); // a case where ok == 0 if (realData) { QCOMPARE(KDb::cstringToVariant(realData, type, &ok, data.length(), signedness), variant); // a case where length is set QCOMPARE(ok, okResult); } QCOMPARE(KDb::cstringToVariant(nullptr, type, &ok, length, signedness), QVariant()); // a case where data == 0 (NULL) QVERIFY(ok || type < KDbField::Byte || type > KDbField::LastType); // fails for NULL if this type isn't allowed if (type != KDbField::Boolean) { QCOMPARE(KDb::cstringToVariant(realData, type, &ok, 0, signedness), QVariant()); // a case where length == 0 QVERIFY(!ok); } if (KDbField::isTextType(type)) { // a case where data == "" QCOMPARE(KDb::cstringToVariant("", type, &ok, length, signedness), QVariant("")); QVERIFY(ok); } else if (type != KDbField::Boolean) { QCOMPARE(KDb::cstringToVariant("", type, &ok, length, signedness), QVariant()); QVERIFY(!ok); } } //! @todo add tests #if 0 /*! @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(); #endif void KDbTest::testTemporaryTableName() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); QString baseName = QLatin1String("foobar"); QString tempName1 = KDb::temporaryTableName(utils.connection.data(), baseName); QVERIFY(!tempName1.isEmpty()); QVERIFY(tempName1.contains(baseName)); QString tempName2 = KDb::temporaryTableName(utils.connection.data(), baseName); QVERIFY(!tempName2.isEmpty()); QVERIFY(tempName2.contains(baseName)); QVERIFY(tempName1 != tempName2); utils.connection->closeDatabase(); QString tempName = KDb::temporaryTableName(utils.connection.data(), baseName); QVERIFY2(tempName.isEmpty(), "Temporary name should not be created for closed connection"); utils.connection->disconnect(); tempName = KDb::temporaryTableName(utils.connection.data(), baseName); QVERIFY2(tempName.isEmpty(), "Temporary name should not be created for closed connection"); utils.connection->dropDatabase(utils.connection->data().databaseName()); } //! @todo add tests #if 0 /*! @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 @c true if @a s is a valid identifier, i.e. starts with a letter or '_' character and contains only letters, numbers and '_' character. */ KDB_EXPORT bool isIdentifier(const QString& 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" column 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); #endif void KDbTest::deleteRecordWithOneConstraintsTest() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "id", 2)); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "id", "3"), "Passing a valid Integer in String Format"); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "id", "Foo")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "name", "Jaroslaw")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "surname", "FooBar")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", 45)); // and empty data. KDbTableSchema *kdb_t = utils.connection.data()->tableSchema("persons"); QVERIFY(kdb_t); QVERIFY2(utils.connection.data()->insertRecord(kdb_t, 10, 20, QVariant(), "Bar"), "Inserting NULL data"); QVERIFY2(utils.connection.data()->insertRecord(kdb_t,15, 20, "", "Bar"), "Inserting empty data"); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "name", QString()), "Passing a null value instead of string"); // QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "name", ""), "Passing an empty string"); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", "Nitish")); QVERIFY(utils.testDisconnectAndDropDb()); } void KDbTest::deleteNonExistingRecordTest() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "id", 400)); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "name", "FooBar")); QVERIFY2(!KDb::deleteRecords(utils.connection.data(), "persons", "Foo", "FooBar"), "Passing a NonExisting Column - should fail because 'Foo' column does not exist, " "See also https://bugs.kde.org/376052"); QVERIFY(utils.testDisconnectAndDropDb()); } void KDbTest::deleteRecordWithTwoConstraintsTest() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "id", KDbField::Integer, 2, "age", KDbField::Integer, 60), "Both fields are INTEGER"); KDbTableSchema *kdb_t = utils.connection.data()->tableSchema("persons"); QVERIFY(kdb_t); utils.connection.data()->insertRecord(kdb_t, 10, QVariant(), "Foo", "Bar") ; QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "id", KDbField::Integer, 10, "age", KDbField::Integer, QVariant()), "Passing NULL value for integer field"); QVERIFY(utils.connection.data()->insertRecord(kdb_t, 20, QVariant(), QVariant(), "Bar")); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, QVariant(), "name", KDbField::Text, QVariant()), "Passing 2 NULL values"); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, 20, "name", KDbField::Text, "Jaroslaw"), "One argument is Integer and another is Text"); QVERIFY2(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, 20, "name", KDbField::Text, 56), "Two arguments, passing second integer instead of text but it is converted to text"); QVERIFY2(!KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, "TRAP", "name", KDbField::Text, 56), "Passing text instead of integer, conversion error expected"); QVERIFY(utils.testDisconnectAndDropDb()); } void KDbTest::deleteRecordWithThreeConstraintsTest() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); KDbTableSchema *kdb_t = utils.connection.data()->tableSchema("persons"); QVERIFY(kdb_t); //One null value. QVERIFY(utils.connection.data()->insertRecord(kdb_t, 10, QVariant(), "Foo", "Bar")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, QVariant(), "name", KDbField::Text, "Foo", "surname", KDbField::Text, "Bar")); //Mix of null and empty values QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, QVariant(), "name", KDbField::Text, "", "surname", KDbField::Text, "")); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer,27, "name", KDbField::Text, "Jaraslaw", "id", KDbField::Integer, 1)); QVERIFY(KDb::deleteRecords(utils.connection.data(), "persons", "age", KDbField::Integer, 60, "name", KDbField::Text, "Lech", "id", KDbField::Integer, 2)); QVERIFY(utils.testDisconnectAndDropDb()); } void KDbTest::deleteAllRecordsTest() { QVERIFY(utils.testCreateDbWithTables("KDbTest")); QVERIFY(KDb::deleteAllRecords(utils.connection.data(), "persons")); QRegularExpression deleteAllErrorRegExp( "KDbResult: .* MESSAGE=\\\"Error while executing SQL statement.\\\" ERR_SQL=KDbEscapedString:" "\\\"DELETE FROM \\[.*\\]\\\" SERVER_ERROR_CODE=0 SERVER_MESSAGE=\\\"no such table: "); QTest::ignoreMessage(QtWarningMsg, deleteAllErrorRegExp); QVERIFY2(!KDb::deleteAllRecords(utils.connection.data(), QString()), "Passing a null table name"); QTest::ignoreMessage(QtWarningMsg, deleteAllErrorRegExp); QVERIFY2(!KDb::deleteAllRecords(utils.connection.data(), ""), "Passing an empty table name"); QVERIFY(KDb::deleteAllRecords(utils.connection.data(), "cars")); QTest::ignoreMessage(QtWarningMsg, deleteAllErrorRegExp); QVERIFY2(!KDb::deleteAllRecords(utils.connection.data(), "NonExistingTable"), "Passing a nonexisting table name"); QVERIFY(utils.testDisconnectAndDropDb()); } void KDbTest::cleanupTestCase() { } diff --git a/autotests/KDbTestUtils.h b/autotests/KDbTestUtils.h index 7ce3767e..a1e4edf1 100644 --- a/autotests/KDbTestUtils.h +++ b/autotests/KDbTestUtils.h @@ -1,132 +1,138 @@ /* This file is part of the KDE project Copyright (C) 2015 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_TESTUTILS_H #define KDB_TESTUTILS_H #include "kdbtestutils_export.h" #include #include #include #include #include +Q_DECLARE_METATYPE(KDbField::TypeGroup) +Q_DECLARE_METATYPE(KDbField::Type) +Q_DECLARE_METATYPE(KDb::Signedness) +Q_DECLARE_METATYPE(QList) +Q_DECLARE_METATYPE(KDb::BLOBEscapingType) + //! @internal for KDB_VERIFY template const T* KDB_POINTER_WRAPPER(const T &t) { return &t; } //! @internal for KDB_VERIFY template const T* KDB_POINTER_WRAPPER(const T *t) { return t; } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(T *t) { return t; } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(const QPointer &t) { return t.data(); } //! @internal for KDB_VERIFY template T* KDB_POINTER_WRAPPER(const QScopedPointer &t) { return t.data(); } //! Calls @a call and verifies status of @a resultable //! On error displays the status on debug and does the same as QVERIFY with @a errorMessage #define KDB_VERIFY(resultable, call, errorMessage) \ do { \ bool KDB_VERIFY_ok = (call); \ const KDbResultable *KDB_VERIFY_resultablePtr = KDB_POINTER_WRAPPER(resultable); \ if (KDB_VERIFY_resultablePtr->result().isError()) { \ qDebug() << KDB_VERIFY_resultablePtr->result(); \ } \ if (!QTest::qVerify(KDB_VERIFY_ok && !KDB_VERIFY_resultablePtr->result().isError(), # call, (errorMessage), __FILE__, __LINE__)) {\ return; \ } \ } \ while (false) //! Calls @a call and verifies status of @a resultable //! On error displays the status on debug and does the same as QVERIFY with @a errorMessage #define KDB_EXPECT_FAIL(resultable, call, expectedErrorCode, errorMessage) \ do { \ bool KDB_VERIFY_ok = (call); \ const KDbResultable *KDB_VERIFY_resultablePtr = KDB_POINTER_WRAPPER(resultable); \ if (KDB_VERIFY_resultablePtr->result().isError()) { \ qDebug() << KDB_VERIFY_resultablePtr->result(); \ } \ QVERIFY(KDB_VERIFY_resultablePtr->result().isError()); \ if (!QTest::qVerify(!KDB_VERIFY_ok, # call, (errorMessage), __FILE__, __LINE__)) {\ return; \ } \ if (!QTest::qCompare(KDB_VERIFY_resultablePtr->result().code(), expectedErrorCode, # call, # expectedErrorCode, __FILE__, __LINE__)) {\ return; \ } \ } \ while (false) //! Declares method @a name that returns false on test failure, it can be called as utility function. //! Also declared internal method name ## Internal which performs the actual test. //! This way users of this method can call QVERIFY(utils.()); #define KDBTEST_METHOD_DECL(name, argsDecl, args) \ public: \ bool name argsDecl Q_REQUIRED_RESULT { name ## Internal args ; return !QTest::currentTestFailed(); } \ private Q_SLOTS: \ void name ## Internal argsDecl //! Test utilities that provide basic database features class KDBTESTUTILS_EXPORT KDbTestUtils : public QObject { Q_OBJECT public: KDbTestUtils(); KDbDriverManager manager; QPointer driver; QScopedPointer connection; KDBTEST_METHOD_DECL(testDriverManager, (), ()); KDBTEST_METHOD_DECL(testSqliteDriver, (), ()); KDBTEST_METHOD_DECL(testConnect, (const KDbConnectionData &cdata), (cdata)); KDBTEST_METHOD_DECL(testUse, (), ()); //! Creates database with name @a dbName //! Does not use the database. //! @todo don't hardcode SQLite here //! @note dbName should not include ".kexi" extension or path KDBTEST_METHOD_DECL(testCreateDb, (const QString &dbName), (dbName)); //! Creates database with name @a dbName, then uses it and creates test tables //! The database stays used. //! @note dbName should not include ".kexi" extension or path KDBTEST_METHOD_DECL(testCreateDbWithTables, (const QString &dbName), (dbName)); KDBTEST_METHOD_DECL(testProperties, (), ()); KDBTEST_METHOD_DECL(testCreateTables, (), ()); KDBTEST_METHOD_DECL(testDisconnect, (), ()); KDBTEST_METHOD_DECL(testDropDb, (), ()); KDBTEST_METHOD_DECL(testDisconnectAndDropDb, (), ()); protected: void testDisconnectPrivate(); void testDriver(const QString &driverId, bool fileBased, const QStringList &mimeTypes); void testDriverManagerInternal(bool forceEmpty); }; #endif diff --git a/autotests/QuerySchemaTest.cpp b/autotests/QuerySchemaTest.cpp new file mode 100644 index 00000000..67fe66c1 --- /dev/null +++ b/autotests/QuerySchemaTest.cpp @@ -0,0 +1,67 @@ +/* This file is part of the KDE project + Copyright (C) 2017 Jarosław Staniek + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +*/ + +#include "QuerySchemaTest.h" + +#include +#include +#include +#include +#include + +#include +#include + +QTEST_GUILESS_MAIN(QuerySchemaTest) + +void QuerySchemaTest::initTestCase() +{ +} + +void QuerySchemaTest::testCaching() +{ + QVERIFY(utils.testCreateDbWithTables("QuerySchemaTest")); + KDbQuerySchema query; + KDbTableSchema *carsTable = utils.connection->tableSchema("cars"); + QVERIFY(carsTable); + query.addTable(carsTable); + KDbField *idField = carsTable->field("id"); + QVERIFY(idField); + // "SELECT id, cars.* from cars" + query.addField(idField); + query.addAsterisk(new KDbQueryAsterisk(&query, *carsTable)); + QCOMPARE(query.fieldCount(), 2); + const KDbQueryColumnInfo::Vector expandedAll1 = query.fieldsExpanded(utils.connection.data()); + QCOMPARE(expandedAll1.count(), 4); + const KDbQueryColumnInfo::Vector expandedUnique1 + = query.fieldsExpanded(utils.connection.data(), KDbQuerySchema::FieldsExpandedMode::Unique); + QCOMPARE(expandedUnique1.count(), 3); + // remove the asterisk -> "SELECT id from cars" + query.removeField(query.field(1)); + QCOMPARE(query.fieldCount(), 1); + const KDbQueryColumnInfo::Vector expandedAll2 = query.fieldsExpanded(utils.connection.data()); + QCOMPARE(expandedAll2.count(), 1); + const KDbQueryColumnInfo::Vector expandedUnique2 + = query.fieldsExpanded(utils.connection.data(), KDbQuerySchema::FieldsExpandedMode::Unique); + QCOMPARE(expandedUnique2.count(), 1); +} + +void QuerySchemaTest::cleanupTestCase() +{ +} diff --git a/autotests/QuerySchemaTest.h b/autotests/QuerySchemaTest.h new file mode 100644 index 00000000..a9c8e231 --- /dev/null +++ b/autotests/QuerySchemaTest.h @@ -0,0 +1,40 @@ +/* This file is part of the KDE project + Copyright (C) 2017 Jarosław Staniek + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this program; see the file COPYING. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +*/ + +#ifndef KDBQUERYSCHEMATEST_H +#define KDBQUERYSCHEMATEST_H + +#include "KDbTestUtils.h" + +class QuerySchemaTest : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void initTestCase(); + + //! Tests if expanded fields cache is updated when query schema object changes + void testCaching(); + + void cleanupTestCase(); + +private: + KDbTestUtils utils; +}; + +#endif diff --git a/autotests/parser/SqlParserTest.cpp b/autotests/parser/SqlParserTest.cpp index 328a6641..59133a12 100644 --- a/autotests/parser/SqlParserTest.cpp +++ b/autotests/parser/SqlParserTest.cpp @@ -1,367 +1,368 @@ /* This file is part of the KDE project Copyright (C) 2012 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "SqlParserTest.h" #include #include #include #include #include #include Q_DECLARE_METATYPE(KDbEscapedString) QTEST_GUILESS_MAIN(SqlParserTest) void SqlParserTest::initTestCase() { QString dir(QFile::decodeName(OUTPUT_DIR)); QString fname("errors.txt"); m_errorFile.setFileName(dir + QDir::separator() + fname); QVERIFY2(m_errorFile.open(QFile::WriteOnly | QFile::Text), qPrintable(QString("Cannot open %1 file").arg(m_errorFile.fileName()))); m_errorStream.setDevice(&m_errorFile); } bool SqlParserTest::openDatabase(const QString &path) { KDbConnectionData cdata; cdata.setDatabaseName(path); if (!m_utils.testConnect(cdata) || !m_utils.connection) { qDebug() << m_utils.driver->result(); return false; } m_parser.reset(new KDbParser(m_utils.connection.data())); #if 0 if (m_conn->databaseExists(dbName)) { if (!m_conn->dropDatabase(dbName)) { m_conn->disconnect(); return false; } qDebug() << "Database" << dbName << "dropped."; } if (!m_conn->createDatabase(dbName)) { qDebug() << m_conn->result(); m_conn->disconnect(); return false; } #endif if (!m_utils.testUse() || !m_utils.connection->isDatabaseUsed()) { qDebug() << m_utils.connection->result(); bool result = m_utils.testDisconnect(); Q_UNUSED(result); return false; } return true; } KDbEscapedString SqlParserTest::parse(const KDbEscapedString& sql, bool *ok) { KDbParser *parser = m_parser.data(); *ok = parser->parse(sql); if (!*ok) { //qDebug() << parser->error(); return KDbEscapedString(); } QScopedPointer q(parser->query()); if (!q) { //qDebug() << parser->error(); *ok = false; return KDbEscapedString(); } //qDebug() << *q.data(); QList params; KDbNativeStatementBuilder builder(m_utils.connection.data()); KDbEscapedString querySql; *ok = builder.generateSelectStatement(&querySql, q.data(), params); //qDebug() << querySql; return querySql; } static void eatComment(QString* string) { if (!string->startsWith("--")) { return; } int i = 0; for (; i < string->length() && string->at(i) == '-'; ++i) ; QString result = string->mid(i).trimmed(); *string = result; } static void eatEndLines(QString* string) { if (!string->endsWith("--")) { return; } int i = string->length() - 1; for (; i >= 0 && string->at(i) == '-'; --i) ; *string = string->left(i+1).trimmed(); } static void eatEndComment(QString* string) { int pos = string->indexOf("; --"); if (pos == -1) { return; } string->truncate(pos); *string = string->trimmed() + ';'; } void SqlParserTest::testParse_data() { QTest::addColumn("fname"); QTest::addColumn("lineNum"); QTest::addColumn("sql"); QTest::addColumn("expectError"); QString dir(QFile::decodeName(FILES_DATA_DIR)); QString fname("statements.txt"); QFile input(dir + QDir::separator() + fname); bool ok = input.open(QFile::ReadOnly | QFile::Text); QVERIFY2(ok, qPrintable(QString("Could not open data file %1").arg(input.fileName()))); QTextStream in(&input); QString category; QString testName; bool expectError = false; int lineNum = 1; QString dbPath; bool clearTestName = false; for (; !in.atEnd(); ++lineNum) { QString line(in.readLine()); if (line.startsWith("--")) { // comment eatComment(&line); eatEndLines(&line); if (line.startsWith("TODO:")) { continue; } else if (line.startsWith("CATEGORY: ")) { if (clearTestName) { expectError = false; clearTestName = false; testName.clear(); } category = line.mid(QString("CATEGORY: ").length()).trimmed(); //qDebug() << "CATEGORY:" << category; } else if (line == "QUIT") { break; } else if (line.startsWith("SQLITEFILE: ")) { if (clearTestName) { expectError = false; clearTestName = false; testName.clear(); } ok = dbPath.isEmpty(); QVERIFY2(ok, qPrintable(QString("Error at line %1: SQLite was file already specified (%2)") .arg(lineNum).arg(dbPath))); dbPath = line.mid(QString("SQLITEFILE: ").length()).trimmed(); dbPath = dir + QDir::separator() + dbPath; ok = openDatabase(dbPath); QVERIFY2(ok, qPrintable(QString("Error at line %1: Could not open SQLite file %2") .arg(lineNum).arg(dbPath))); } else if (line.startsWith("ERROR: ")) { if (clearTestName) { clearTestName = false; testName.clear(); } expectError = true; testName = line.mid(QString("ERROR: ").length()).trimmed(); } else { if (clearTestName) { expectError = false; clearTestName = false; testName.clear(); } if (!testName.isEmpty()) { testName.append(" "); } testName.append(line); } } else { eatEndComment(&line); KDbEscapedString sql(line.trimmed()); clearTestName = true; if (sql.isEmpty()) { expectError = false; continue; } ok = !dbPath.isEmpty(); QVERIFY2(ok, qPrintable(QString("Error at line %1: SQLite was file not specified, " "could not execute statement").arg(lineNum))); QTest::newRow(qPrintable(QString("File: %1:%2; Category: \"%3\"; Test: \"%4\"%5") .arg(fname).arg(lineNum).arg(category, testName, expectError ? "; Error expected" : ""))) << fname << lineNum << sql << expectError; } } input.close(); } void SqlParserTest::testParse() { QFETCH(QString, fname); QFETCH(int, lineNum); QFETCH(KDbEscapedString, sql); QFETCH(bool, expectError); QString message; if (!sql.endsWith(';')) { message = QString("%1:%2: Missing ';' at the end of line").arg(fname).arg(lineNum); m_errorStream << fname << ':' << lineNum << ' ' << message << endl; QVERIFY2(sql.endsWith(';'), qPrintable(message)); } sql.chop(1); //qDebug() << "SQL:" << sql.toString() << expectError; bool ok; KDbEscapedString result = parse(sql, &ok); KDbParser *parser = m_parser.data(); if (ok) { // sucess, so error cannot be expected ok = !expectError; message = QString("Unexpected success in SQL statement: \"%1\"; Result: %2") .arg(sql.toString(), result.toString()); if (ok) { qDebug() << "Result:" << result.toString(); } else { m_errorStream << fname << ':' << lineNum << ' ' << message << endl; if (parser->query()) { - qDebug() << *parser->query(); - m_errorStream << KDbUtils::debugString(*parser->query()) << endl; + const KDbConnectionAndQuerySchema connQuery(parser->connection(), *parser->query()); + qDebug() << connQuery; + m_errorStream << KDbUtils::debugString(connQuery) << endl; } } QVERIFY2(ok, qPrintable(message)); } else { // failure, so error should be expected ok = expectError; message = QString("%1; Failed SQL Statement:\n\"%2\"\n %3^\n") .arg(KDbUtils::debugString(parser->error()), sql.toString(), QString(parser->error().position() - 1, QChar(' '))); if (ok) { qDebug() << parser->error(); } else { m_errorStream << fname << ':' << lineNum << message << endl; } QVERIFY2(ok, qPrintable(message)); } } void SqlParserTest::testTokens() { KDbToken t = KDbToken::LEFT; qDebug() << t << t.toChar() << t.value() << t.isValid(); t = '+'; qDebug() << t << t.toChar() << t.value() << t.isValid(); t = KDbToken(); qDebug() << t << t.toChar() << t.value() << t.isValid(); QCOMPARE(KDbToken::SQL_TYPE.value(), 258); QCOMPARE(KDbToken::AS.value(), 259); QCOMPARE(KDbToken::AS_EMPTY.value(), 260); QCOMPARE(KDbToken::ASC.value(), 261); QCOMPARE(KDbToken::AUTO_INCREMENT.value(), 262); QCOMPARE(KDbToken::BIT.value(), 263); QCOMPARE(KDbToken::BITWISE_SHIFT_LEFT.value(), 264); QCOMPARE(KDbToken::BITWISE_SHIFT_RIGHT.value(), 265); QCOMPARE(KDbToken::BY.value(), 266); QCOMPARE(KDbToken::CHARACTER_STRING_LITERAL.value(), 267); QCOMPARE(KDbToken::CONCATENATION.value(), 268); QCOMPARE(KDbToken::CREATE.value(), 269); QCOMPARE(KDbToken::DESC.value(), 270); QCOMPARE(KDbToken::DISTINCT.value(), 271); QCOMPARE(KDbToken::DOUBLE_QUOTED_STRING.value(), 272); QCOMPARE(KDbToken::FROM.value(), 273); QCOMPARE(KDbToken::JOIN.value(), 274); QCOMPARE(KDbToken::KEY.value(), 275); QCOMPARE(KDbToken::LEFT.value(), 276); QCOMPARE(KDbToken::LESS_OR_EQUAL.value(), 277); QCOMPARE(KDbToken::GREATER_OR_EQUAL.value(), 278); QCOMPARE(KDbToken::SQL_NULL.value(), 279); QCOMPARE(KDbToken::SQL_IS.value(), 280); QCOMPARE(KDbToken::SQL_IS_NULL.value(), 281); QCOMPARE(KDbToken::SQL_IS_NOT_NULL.value(), 282); QCOMPARE(KDbToken::ORDER.value(), 283); QCOMPARE(KDbToken::PRIMARY.value(), 284); QCOMPARE(KDbToken::SELECT.value(), 285); QCOMPARE(KDbToken::INTEGER_CONST.value(), 286); QCOMPARE(KDbToken::REAL_CONST.value(), 287); QCOMPARE(KDbToken::RIGHT.value(), 288); QCOMPARE(KDbToken::SQL_ON.value(), 289); QCOMPARE(KDbToken::DATE_CONST.value(), 290); QCOMPARE(KDbToken::DATETIME_CONST.value(), 291); QCOMPARE(KDbToken::TIME_CONST.value(), 292); QCOMPARE(KDbToken::TABLE.value(), 293); QCOMPARE(KDbToken::IDENTIFIER.value(), 294); QCOMPARE(KDbToken::IDENTIFIER_DOT_ASTERISK.value(), 295); QCOMPARE(KDbToken::QUERY_PARAMETER.value(), 296); QCOMPARE(KDbToken::VARCHAR.value(), 297); QCOMPARE(KDbToken::WHERE.value(), 298); QCOMPARE(KDbToken::SQL.value(), 299); QCOMPARE(KDbToken::SQL_TRUE.value(), 300); QCOMPARE(KDbToken::SQL_FALSE.value(), 301); QCOMPARE(KDbToken::UNION.value(), 302); QCOMPARE(KDbToken::SCAN_ERROR.value(), 303); QCOMPARE(KDbToken::AND.value(), 304); QCOMPARE(KDbToken::BETWEEN.value(), 305); QCOMPARE(KDbToken::NOT_BETWEEN.value(), 306); QCOMPARE(KDbToken::EXCEPT.value(), 307); QCOMPARE(KDbToken::SQL_IN.value(), 308); QCOMPARE(KDbToken::INTERSECT.value(), 309); QCOMPARE(KDbToken::LIKE.value(), 310); QCOMPARE(KDbToken::ILIKE.value(), 311); QCOMPARE(KDbToken::NOT_LIKE.value(), 312); QCOMPARE(KDbToken::NOT.value(), 313); QCOMPARE(KDbToken::NOT_EQUAL.value(), 314); QCOMPARE(KDbToken::NOT_EQUAL2.value(), 315); QCOMPARE(KDbToken::OR.value(), 316); QCOMPARE(KDbToken::SIMILAR_TO.value(), 317); QCOMPARE(KDbToken::NOT_SIMILAR_TO.value(), 318); QCOMPARE(KDbToken::XOR.value(), 319); QCOMPARE(KDbToken::UMINUS.value(), 320); //! @todo add extra tokens: BETWEEN_AND, NOT_BETWEEN_AND } void SqlParserTest::cleanupTestCase() { QVERIFY(m_utils.testDisconnect()); m_errorFile.close(); #if 0 if (!m_conn->dropDatabase()) { qDebug() << m_conn->result(); } qDebug() << "Database" << m_conn->data().databaseName() << "dropped."; #endif } diff --git a/src/KDb.cpp b/src/KDb.cpp index 01d8c57a..d29ef277 100644 --- a/src/KDb.cpp +++ b/src/KDb.cpp @@ -1,2296 +1,2229 @@ /* This file is part of the KDE project Copyright (C) 2004-2017 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 "KDbConnectionData.h" #include "KDbConnection.h" #include "KDbCursor.h" #include "kdb_debug.h" #include "KDbDriverBehavior.h" #include "KDbDriverManager.h" #include "KDbDriver_p.h" #include "KDbLookupFieldSchema.h" #include "KDbMessageHandler.h" #include "KDbNativeStatementBuilder.h" #include "KDb_p.h" #include "KDbQuerySchema.h" #include "KDbRecordData.h" #include "KDbSqlResult.h" #include "KDbTableOrQuerySchema.h" #include "KDbVersionInfo.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 accept() override; void reject() override; protected: void finish(); 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(); QString message; QString details; KDbMessageHandler::MessageType type; if (m_error) { reject(); //kdbDebug() << "after reject"; 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) { reject(); //kdbDebug() << "after reject"; message = tr("Test connection to \"%1\" database server failed. The server is not responding.") .arg(m_connData.toUserVisibleString()); type = KDbMessageHandler::Sorry; } else { accept(); //kdbDebug() << "after accept"; 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() << "Error:" << msg << details; } } void ConnectionTestDialog::accept() { finish(); QProgressDialog::accept(); // krazy:exclude=qclasses } void ConnectionTestDialog::reject() { finish(); QProgressDialog::reject(); // krazy:exclude=qclasses } void ConnectionTestDialog::finish() { if (m_thread->isRunning()) { m_thread->terminate(); } m_timer.disconnect(this); m_timer.stop(); } // ---- //! @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) { return conn ? conn->executeSql(KDbEscapedString("DELETE FROM %1 WHERE %2=%3") .arg(conn->escapeIdentifier(tableName)) .arg(conn->escapeIdentifier(keyname)) .arg(conn->driver()->valueToSql(keytype, keyval))) : false; } 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) { return conn ? 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))) : false; } 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) { return conn ? 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))) : false; } bool KDb::deleteAllRecords(KDbConnection* conn, const QString &tableName) { return conn ? conn->executeSql( KDbEscapedString("DELETE FROM %1").arg(conn->escapeIdentifier(tableName))) : false; } KDB_EXPORT quint64 KDb::lastInsertedAutoIncValue(QSharedPointer result, const QString &autoIncrementFieldName, const QString &tableName, quint64 *recordId) { if (!result) { return std::numeric_limits::max(); } const quint64 foundRecordId = result->lastInsertRecordId(); if (recordId) { *recordId = foundRecordId; } 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 = KDbDriverPrivate::behavior(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) { if (!msg) { kdbWarning() << "missing 'msg' parameter"; return; } if (!details) { kdbWarning() << "missing 'details' parameter"; return; } 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) { getHTMLErrorMesage(resultable, msg, msg); } void KDb::getHTMLErrorMesage(const KDbResultable& resultable, KDbResultInfo *info) { if (!info) { kdbWarning() << "missing 'info' parameter"; return; } getHTMLErrorMesage(resultable, &info->message, &info->description); } tristate KDb::idForObjectName(KDbConnection* conn, int *id, const QString& objName, int objType) { return conn ? conn->querySingleNumber( KDbEscapedString("SELECT o_id FROM kexi__objects WHERE o_name=%1 AND o_type=%2") .arg(conn->escapeString(objName)) .arg(objType), id) : false; } //----------------------------------------- tristate KDb::showConnectionTestDialog(QWidget *parent, const KDbConnectionData &data, KDbMessageHandler *msgHandler) { ConnectionTestDialog dlg(data, msgHandler, parent); const int result = dlg.exec(); if (dlg.wasCanceled()) { return cancelled; } return result == QDialog::Accepted; } -int KDb::recordCount(KDbConnection* conn, const KDbEscapedString& sql) -{ - int count = -1; //will be changed only on success of querySingleNumber() - if (conn) { - (void)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) { - if (tableOrQuery->table()) - return recordCount(*tableOrQuery->table()); - if (tableOrQuery->query()) - return recordCount(tableOrQuery->query(), params); - } - return -1; -} - -int KDb::fieldCount(KDbTableOrQuerySchema* tableOrQuery) -{ - if (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) { if (!tableName || !fieldName) { return false; } 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) { QLocale defaultLocale; return ::numberToString(value, decimalPlaces, &defaultLocale); } QString KDb::numberToLocaleString(double value, int decimalPlaces, const QLocale &locale) { return ::numberToString(value, decimalPlaces, &locale); } 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) { if (!values) { return; } 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) { if (!values) { return; } 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 const 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) { if (!field) { return false; } 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) { if (!field) { return false; } #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) { if (!doc || !parentEl || elementName.isEmpty()) { return QDomElement(); } 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) { if (!doc || !parentEl || elementName.isEmpty()) { return QDomElement(); } 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; } KDbEscapedString KDb::escapeString(KDbDriver *drv, const QString& string) { return drv ? drv->escapeString(string) : KDbEscapedString(KDb::escapeString(string)); } KDbEscapedString KDb::escapeString(KDbConnection *conn, const QString& string) { return conn ? conn->escapeString(string) : KDbEscapedString(KDb::escapeString(string)); } //! @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) { if (!minValue || !maxValue) { return; } 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) { 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 3eaf822d..fb6ce80a 100644 --- a/src/KDb.h +++ b/src/KDb.h @@ -1,835 +1,777 @@ /* This file is part of the KDE project Copyright (C) 2004-2017 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 "KDbField.h" #include "KDbGlobal.h" #include "KDbSqlResult.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 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(); /** * @brief Deletes records using one generic criteria. * * @return @c true on success and @c false on failure and if @a conn is @c nullptr */ KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname, KDbField::Type keytype, const QVariant &keyval); //! @overload 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 inline bool deleteRecords(KDbConnection* conn, const QString &tableName, const QString &keyname, const QString &keyval) { return deleteRecords(conn, tableName, keyname, KDbField::Text, keyval); } //! @overload inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString &keyname, const QString &keyval) { return deleteRecords(conn, table.name(), keyname, keyval); } //! @overload inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, const QString& keyname, int keyval) { return deleteRecords(conn, table, keyname, KDbField::Integer, keyval); } //! @overload 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()); } /** * 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, 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); /** * @brief Sets HTML-formatted error message with extra details obtained from result object * * 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 there is no error (resultable.result().isError() == false) or if @a msg or * @a details is @c nullptr. * In this case strings pointer by @a msg and @a details strings are not changed. * If the string pointed by @a msg is not empty, it is not modified and message obtained from * @a resultable is appended to the string pointed by @a details instead. */ KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg, QString *details); /** * @overload * * This methods works similarly but appends both a message and a description to string pointed by * @a msg. */ KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg); /** * @overload * * This methods similarly but outputs message to @a info 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); /** * @brief Finds 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 or if @a conn is @c nullptr, @c false is returned. * If there is no object with specified name and type, @c cancelled value is returned. */ KDB_EXPORT tristate idForObjectName(KDbConnection* conn, int *id, const QString& objName, int objType); -/** - * @brief Returns number of records returned by given SQL statement - * - * @return number of records that can be retrieved after executing @a sql statement within - * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not - * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. - * -1 is returned if any error occurred or if @a conn is @c nullptr. - */ -//! @todo perhaps use quint64 here? -KDB_EXPORT int recordCount(KDbConnection* conn, const KDbEscapedString& sql); - -/** - * @brief Returns number of records that contains given table - * - * @return number of records that can be retrieved from @a tableSchema. - * To obtain the result the table must be created or retrieved using a KDbConnection object, - * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" - * SQL aggregation is used at the backed. - * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr. - */ -//! @todo perhaps use quint64 here? -KDB_EXPORT int recordCount(const KDbTableSchema& tableSchema); - -/** - * @overload - * - * Operates on a query schema. @a params are optional values of parameters that will be inserted - * into [] placeholders before execution of query that counts the records. - * To obtain the result the query must be created or retrieved using a KDbConnection object, - * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" - * SQL aggregation is used at the backed. - * -1 is returned if error occurred or if querySchema->connection() is @c nullptr. - */ -//! @todo perhaps use quint64 here? -KDB_EXPORT int recordCount(KDbQuerySchema* querySchema, - const QList& params = QList()); - -/** - * @overload - * - * Operates on a table or query schema. @a params is a list of optional parameters that - * will be inserted into [] placeholders before execution of query that counts the records. - * - * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned. - */ -//! @todo perhaps use quint64 here? -KDB_EXPORT int recordCount(KDbTableOrQuerySchema* tableOrQuery, - const QList& params = QList()); - -/** - * @brief Returns number of columns within record set returned from specified table or query - * - * In case of query expanded fields list is counted. - * Returns -1 if @a tableOrQuery is @c nullptr or has neither table or query assigned. - */ -KDB_EXPORT int fieldCount(KDbTableOrQuerySchema* tableOrQuery); - /** * @brief Shows connection test dialog * * Shows connection test dialog with a progress bar indicating connection testing * (within a separate thread). @a data is used to perform a (temporary) test connection. * @a msgHandler can be used for error handling. @a parent is used as dialog's parent widget. * * The dialog is modal so the call is blocking. * * On successful connecting, a successfull message of type KDbMessageHandler::Information is passed * to @a msgHandler. After testing, temporary connection is closed. * * @return @c true for successfull connecting, @c for failed connecting and @c cancelled if the test * has been cancelled. */ KDB_EXPORT tristate showConnectionTestDialog(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). - @a tableName or @a fieldName is @c nullptr 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); /** * @brief Returns number converted to string using default locale * * This method is similar to KDb::numberToString() but the string is formatted using QLocale::toString(). * * @see KDb::numberToString() KDbField::visibleDecimalPlaces() */ KDB_EXPORT QString numberToLocaleString(double value, int decimalPlaces); /** * @overload * * Returns number converted to string using specified locale. */ KDB_EXPORT QString numberToLocaleString(double value, int decimalPlaces, const QLocale &locale); //! @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 not cleared before filling. This function is used e.g. for altering table design. Nothing is performed if @a values is @c nullptr. If @a lookup is @c nullptr, all returned values are null. */ 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. Nothing is performed if @a values is @c nullptr. */ 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. If @a field is @c nullptr nothing is performed and @c false is returned. */ KDB_EXPORT bool setFieldProperties(KDbField *field, const QMap& values); /*! Sets value of a single property 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 not modified. Properties from extended schema are also supported as well as custom properties (using KDbField::setCustomProperty()). This function is used e.g. by KDbAlterTableHandler when property information comes in form of text. If @a field is @c nullptr nothing is performed and @c false is returned. */ 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. Validity of the returned value can be checked using the @a ok parameter and 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); /*! Creates a new DOM element named @a elementName with numeric value @a value in @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) creates: @code 15 @endcode @return the reference to element created with tag elementName. Null element is returned if @a doc or @a parentEl is @c nullptr or if @a elementName is empty. */ KDB_EXPORT QDomElement saveNumberElementToDom(QDomDocument *doc, QDomElement *parentEl, const QString& elementName, int value); /*! Creates a new DOM element named @a elementName with boolean value @a value in @a doc document within parent element @a parentEl. This method is like saveNumberElementToDom() but creates "bool" tags. True/false values will be saved as "true"/"false" strings. Example: saveBooleanElementToDom(doc, parentEl, "visible", true) creates: @code true @endcode @return the reference to element created with tag elementName. Null element is returned if @a doc or @a parentEl is @c nullptr or if @a elementName is empty. */ 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); /** * @brief Returns escaped string @a string * * If @a drv driver is present, it is used to perform escaping, otherwise escapeString() is used * so the KDbSQL dialect-escaping is performed. * * @since 3.1.0 */ KDB_EXPORT KDbEscapedString escapeString(KDbDriver *drv, const QString& string); /** * @brief Returns escaped string @a string * * If @a conn is present, its driver is used to perform escaping, otherwise escapeString() is used * so the KDbSQL dialect-escaping is performed. * * @since 3.1.0 */ KDB_EXPORT KDbEscapedString escapeString(KDbConnection *conn, 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 @c nullptr or is not open or if checking for existence of table with 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 @c true if @a s is a valid identifier, i.e. 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 6bebcccc..d47c19fd 100644 --- a/src/KDbConnection.cpp +++ b/src/KDbConnection.cpp @@ -1,3420 +1,3487 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbConnection.h" #include "KDbConnection_p.h" #include "KDbCursor.h" #include "KDbDriverBehavior.h" #include "KDbDriverMetaData.h" #include "KDbDriver_p.h" #include "KDbLookupFieldSchema.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbQuerySchema_p.h" #include "KDbRecordData.h" #include "KDbRecordEditBuffer.h" #include "KDbRelationship.h" #include "KDbSqlRecord.h" #include "KDbSqlResult.h" +#include "KDbTableOrQuerySchema.h" #include "KDbTableSchemaChangeListener.h" #include "KDbTransactionData.h" #include "KDbTransactionGuard.h" #include "kdb_debug.h" #include #include #include /*! Version number of extended table schema. List of changes: * 2: (Kexi 2.5.0) Added maxLengthIsDefault property (type: bool, if true, KDbField::maxLengthStrategy() == KDbField::DefaultMaxLength) * 1: (Kexi 1.x) Initial version */ #define KDB_EXTENDED_TABLE_SCHEMA_VERSION 2 KDbConnectionInternal::KDbConnectionInternal(KDbConnection *conn) : connection(conn) { } class CursorDeleter { public: explicit CursorDeleter(KDbCursor *cursor) { delete cursor; } }; //================================================ class Q_DECL_HIDDEN KDbConnectionOptions::Private { public: Private() : connection(nullptr) {} Private(const Private &other) { copy(other); } #define KDbConnectionOptionsPrivateArgs(o) std::tie(o.connection) void copy(const Private &other) { KDbConnectionOptionsPrivateArgs((*this)) = KDbConnectionOptionsPrivateArgs(other); } bool operator==(const Private &other) const { return KDbConnectionOptionsPrivateArgs((*this)) == KDbConnectionOptionsPrivateArgs(other); } KDbConnection *connection; }; KDbConnectionOptions::KDbConnectionOptions() : d(new Private) { KDbUtils::PropertySet::insert("readOnly", false, tr("Read only", "Read only connection")); } KDbConnectionOptions::KDbConnectionOptions(const KDbConnectionOptions &other) : KDbUtils::PropertySet(other) , d(new Private(*other.d)) { } KDbConnectionOptions::~KDbConnectionOptions() { delete d; } KDbConnectionOptions& KDbConnectionOptions::operator=(const KDbConnectionOptions &other) { if (this != &other) { KDbUtils::PropertySet::operator=(other); d->copy(*other.d); } return *this; } bool KDbConnectionOptions::operator==(const KDbConnectionOptions &other) const { return KDbUtils::PropertySet::operator==(other) && *d == *other.d; } bool KDbConnectionOptions::isReadOnly() const { return property("readOnly").value().toBool(); } void KDbConnectionOptions::insert(const QByteArray &name, const QVariant &value, const QString &caption) { if (name == "readOnly") { setReadOnly(value.toBool()); return; } QString realCaption; if (property(name).caption().isEmpty()) { // don't allow to change the caption realCaption = caption; } KDbUtils::PropertySet::insert(name, value, realCaption); } void KDbConnectionOptions::setCaption(const QByteArray &name, const QString &caption) { if (name == "readOnly") { return; } KDbUtils::PropertySet::setCaption(name, caption); } void KDbConnectionOptions::setValue(const QByteArray &name, const QVariant &value) { if (name == "readOnly") { setReadOnly(value.toBool()); return; } KDbUtils::PropertySet::setValue(name, value); } void KDbConnectionOptions::remove(const QByteArray &name) { if (name == "readOnly") { return; } KDbUtils::PropertySet::remove(name); } void KDbConnectionOptions::setReadOnly(bool set) { if (d->connection && d->connection->isConnected()) { return; //sanity } KDbUtils::PropertySet::setValue("readOnly", set); } void KDbConnectionOptions::setConnection(KDbConnection *connection) { d->connection = connection; } //================================================ KDbConnectionPrivate::KDbConnectionPrivate(KDbConnection* const conn, KDbDriver *drv, const KDbConnectionData& _connData, const KDbConnectionOptions &_options) : conn(conn) , connData(_connData) , options(_options) , driver(drv) , dbProperties(conn) { options.setConnection(conn); } KDbConnectionPrivate::~KDbConnectionPrivate() { options.setConnection(nullptr); deleteAllCursors(); delete m_parser; qDeleteAll(tableSchemaChangeListeners); qDeleteAll(obsoleteQueries); } void KDbConnectionPrivate::deleteAllCursors() { QSet cursorsToDelete(cursors); cursors.clear(); for(KDbCursor* c : cursorsToDelete) { CursorDeleter deleter(c); } } void KDbConnectionPrivate::errorInvalidDBContents(const QString& details) { conn->m_result = KDbResult(ERR_INVALID_DATABASE_CONTENTS, KDbConnection::tr("Invalid database contents. %1").arg(details)); } QString KDbConnectionPrivate::strItIsASystemObject() const { return KDbConnection::tr("It is a system object."); } void KDbConnectionPrivate::setupKDbSystemSchema() { if (!m_internalKDbTables.isEmpty()) { return; //already set up } { KDbInternalTableSchema *t_objects = new KDbInternalTableSchema(QLatin1String("kexi__objects")); t_objects->addField(new KDbField(QLatin1String("o_id"), KDbField::Integer, KDbField::PrimaryKey | KDbField::AutoInc, KDbField::Unsigned)); t_objects->addField(new KDbField(QLatin1String("o_type"), KDbField::Byte, nullptr, KDbField::Unsigned)); t_objects->addField(new KDbField(QLatin1String("o_name"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_caption"), KDbField::Text)); t_objects->addField(new KDbField(QLatin1String("o_desc"), KDbField::LongText)); //kdbDebug() << *t_objects; insertTable(t_objects); } { KDbInternalTableSchema *t_objectdata = new KDbInternalTableSchema(QLatin1String("kexi__objectdata")); t_objectdata->addField(new KDbField(QLatin1String("o_id"), KDbField::Integer, KDbField::NotNull, KDbField::Unsigned)); t_objectdata->addField(new KDbField(QLatin1String("o_data"), KDbField::LongText)); t_objectdata->addField(new KDbField(QLatin1String("o_sub_id"), KDbField::Text)); insertTable(t_objectdata); } { KDbInternalTableSchema *t_fields = new KDbInternalTableSchema(QLatin1String("kexi__fields")); t_fields->addField(new KDbField(QLatin1String("t_id"), KDbField::Integer, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_type"), KDbField::Byte, nullptr, KDbField::Unsigned)); t_fields->addField(new KDbField(QLatin1String("f_name"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_length"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_precision"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_constraints"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_options"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_default"), KDbField::Text)); //these are additional properties: t_fields->addField(new KDbField(QLatin1String("f_order"), KDbField::Integer)); t_fields->addField(new KDbField(QLatin1String("f_caption"), KDbField::Text)); t_fields->addField(new KDbField(QLatin1String("f_help"), KDbField::LongText)); insertTable(t_fields); } { KDbInternalTableSchema *t_db = new KDbInternalTableSchema(QLatin1String("kexi__db")); t_db->addField(new KDbField(QLatin1String("db_property"), KDbField::Text, KDbField::NoConstraints, KDbField::NoOptions, 32)); t_db->addField(new KDbField(QLatin1String("db_value"), KDbField::LongText)); insertTable(t_db); } } void KDbConnectionPrivate::insertTable(KDbTableSchema* tableSchema) { KDbInternalTableSchema* internalTable = dynamic_cast(tableSchema); if (internalTable) { m_internalKDbTables.insert(internalTable); } else { m_tables.insert(tableSchema->id(), tableSchema); } m_tablesByName.insert(tableSchema->name(), tableSchema); } void KDbConnectionPrivate::removeTable(const KDbTableSchema& tableSchema) { m_tablesByName.remove(tableSchema.name()); KDbTableSchema *toDelete = m_tables.take(tableSchema.id()); delete toDelete; } void KDbConnectionPrivate::takeTable(KDbTableSchema* tableSchema) { if (m_tables.isEmpty()) { return; } m_tables.take(tableSchema->id()); m_tablesByName.take(tableSchema->name()); } void KDbConnectionPrivate::renameTable(KDbTableSchema* tableSchema, const QString& newName) { m_tablesByName.take(tableSchema->name()); tableSchema->setName(newName); m_tablesByName.insert(tableSchema->name(), tableSchema); } void KDbConnectionPrivate::changeTableId(KDbTableSchema* tableSchema, int newId) { m_tables.take(tableSchema->id()); m_tables.insert(newId, tableSchema); } void KDbConnectionPrivate::clearTables() { m_tablesByName.clear(); qDeleteAll(m_internalKDbTables); m_internalKDbTables.clear(); QHash tablesToDelete(m_tables); m_tables.clear(); qDeleteAll(tablesToDelete); } void KDbConnectionPrivate::insertQuery(KDbQuerySchema* query) { m_queries.insert(query->id(), query); m_queriesByName.insert(query->name(), query); } void KDbConnectionPrivate::removeQuery(KDbQuerySchema* querySchema) { m_queriesByName.remove(querySchema->name()); m_queries.remove(querySchema->id()); delete querySchema; } void KDbConnectionPrivate::setQueryObsolete(KDbQuerySchema* query) { obsoleteQueries.insert(query); m_queriesByName.take(query->name()); m_queries.take(query->id()); } void KDbConnectionPrivate::clearQueries() { qDeleteAll(m_queries); m_queries.clear(); } KDbTableSchema* KDbConnectionPrivate::setupTableSchema(KDbTableSchema *table) { Q_ASSERT(table); QScopedPointer newTable(table); KDbCursor *cursor; if (!(cursor = conn->executeQuery( KDbEscapedString("SELECT t_id, f_type, f_name, f_length, f_precision, f_constraints, " "f_options, f_default, f_order, f_caption, f_help " "FROM kexi__fields WHERE t_id=%1 ORDER BY f_order") .arg(driver->valueToSql(KDbField::Integer, table->id()))))) { return nullptr; } if (!cursor->moveFirst()) { if (!cursor->result().isError() && cursor->eof()) { conn->m_result = KDbResult(tr("Table has no fields defined.")); } conn->deleteCursor(cursor); return nullptr; } // For each field: load its schema KDbRecordData fieldData; bool ok = true; while (!cursor->eof()) { // kdbDebug()<<"@@@ f_name=="<value(2).asCString(); if (!cursor->storeCurrentRecord(&fieldData)) { ok = false; break; } KDbField *f = conn->setupField(fieldData); if (!f || !table->addField(f)) { ok = false; break; } cursor->moveNext(); } if (!ok) {//error: conn->deleteCursor(cursor); return nullptr; } if (!conn->deleteCursor(cursor)) { return nullptr; } if (!conn->loadExtendedTableSchemaData(table)) { return nullptr; } //store locally: insertTable(table); return newTable.take(); } KDbQuerySchema* KDbConnectionPrivate::setupQuerySchema(KDbQuerySchema *query) { Q_ASSERT(query); QScopedPointer newQuery(query); QString sql; if (!conn->loadDataBlock(query->id(), &sql, QLatin1String("sql"))) { conn->m_result = KDbResult( ERR_OBJECT_NOT_FOUND, tr("Could not find definition for query \"%1\". Deleting this query is recommended.") .arg(query->name())); return nullptr; } if (!parser()->parse(KDbEscapedString(sql), query)) { conn->m_result = KDbResult( ERR_SQL_PARSE_ERROR, tr("

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

\n" "

This query can be edited only in Text View.

") .arg(query->name(), sql)); return nullptr; } insertQuery(query); return newQuery.take(); } +KDbQuerySchemaFieldsExpanded *KDbConnectionPrivate::fieldsExpanded(const KDbQuerySchema *query) +{ + return m_fieldsExpandedCache[query]; +} + +void KDbConnectionPrivate::insertFieldsExpanded(const KDbQuerySchema *query, KDbQuerySchemaFieldsExpanded *cache) +{ + m_fieldsExpandedCache.insert(query, cache); +} + //================================================ namespace { //! @internal static: list of internal KDb system table names class SystemTables : public QStringList { public: SystemTables() : QStringList({ QLatin1String("kexi__objects"), QLatin1String("kexi__objectdata"), QLatin1String("kexi__fields"), QLatin1String("kexi__db")}) {} }; } Q_GLOBAL_STATIC(SystemTables, g_kdbSystemTableNames) KDbConnection::KDbConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options) : d(new KDbConnectionPrivate(this, driver, connData, options)) { if (d->connData.driverId().isEmpty()) { d->connData.setDriverId(d->driver->metaData()->id()); } } void KDbConnection::destroy() { disconnect(); //do not allow the driver to touch me: I will kill myself. d->driver->d->connections.remove(this); } KDbConnection::~KDbConnection() { KDbConnectionPrivate *thisD = d; d = nullptr; // make sure d is nullptr before destructing delete thisD; } KDbConnectionData KDbConnection::data() const { return d->connData; } KDbDriver* KDbConnection::driver() const { return d->driver; } bool KDbConnection::connect() { clearResult(); if (d->isConnected) { m_result = KDbResult(ERR_ALREADY_CONNECTED, tr("Connection already established.")); return false; } d->serverVersion.clear(); if (!(d->isConnected = drv_connect())) { if (m_result.code() == ERR_NONE) { m_result.setCode(ERR_OTHER); } m_result.setMessage(d->driver->metaData()->isFileBased() ? tr("Could not open \"%1\" project file.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName())) : tr("Could not connect to \"%1\" database server.") .arg(d->connData.toUserVisibleString())); } if (d->isConnected && !d->driver->behavior()->USING_DATABASE_REQUIRED_TO_CONNECT) { if (!drv_getServerVersion(&d->serverVersion)) return false; } return d->isConnected; } bool KDbConnection::isDatabaseUsed() const { return !d->usedDatabase.isEmpty() && d->isConnected && drv_isDatabaseUsed(); } void KDbConnection::clearResult() { KDbResultable::clearResult(); } bool KDbConnection::disconnect() { clearResult(); if (!d->isConnected) return true; if (!closeDatabase()) return false; bool ok = drv_disconnect(); if (ok) d->isConnected = false; return ok; } bool KDbConnection::isConnected() const { return d->isConnected; } bool KDbConnection::checkConnected() { if (d->isConnected) { clearResult(); return true; } m_result = KDbResult(ERR_NO_CONNECTION, tr("Not connected to the database server.")); return false; } bool KDbConnection::checkIsDatabaseUsed() { if (isDatabaseUsed()) { clearResult(); return true; } m_result = KDbResult(ERR_NO_DB_USED, tr("Currently no database is used.")); return false; } QStringList KDbConnection::databaseNames(bool also_system_db) { //kdbDebug() << also_system_db; if (!checkConnected()) return QStringList(); QString tmpdbName; //some engines need to have opened any database before executing "create database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return QStringList(); QStringList list; bool ret = drv_getDatabasesList(&list); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return QStringList(); } if (!ret) return QStringList(); if (also_system_db) return list; //filter system databases: for (QMutableListIterator it(list); it.hasNext();) { if (d->driver->isSystemDatabaseName(it.next())) { it.remove(); } } return list; } bool KDbConnection::drv_getDatabasesList(QStringList* list) { list->clear(); return true; } bool KDbConnection::drv_databaseExists(const QString &dbName, bool ignoreErrors) { QStringList list = databaseNames(true);//also system if (m_result.isError()) { return false; } if (list.indexOf(dbName) == -1) { if (!ignoreErrors) m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("The database \"%1\" does not exist.").arg(dbName)); return false; } return true; } bool KDbConnection::databaseExists(const QString &dbName, bool ignoreErrors) { // kdbDebug() << dbName << ignoreErrors; if (d->driver->behavior()->CONNECTION_REQUIRED_TO_CHECK_DB_EXISTENCE && !checkConnected()) return false; clearResult(); if (d->driver->metaData()->isFileBased()) { //for file-based db: file must exists and be accessible QFileInfo file(d->connData.databaseName()); if (!file.exists() || (!file.isFile() && !file.isSymLink())) { if (!ignoreErrors) m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("The database file \"%1\" does not exist.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } if (!file.isReadable()) { if (!ignoreErrors) m_result = KDbResult(ERR_ACCESS_RIGHTS, tr("Database file \"%1\" is not readable.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } if (!d->options.isReadOnly() && !file.isWritable()) { if (!ignoreErrors) m_result = KDbResult(ERR_ACCESS_RIGHTS, tr("Database file \"%1\" is not writable.") .arg(QDir::fromNativeSeparators(QFileInfo(d->connData.databaseName()).fileName()))); return false; } return true; } QString tmpdbName; //some engines need to have opened any database before executing "create database" const bool orig_skipDatabaseExistsCheckInUseDatabase = d->skipDatabaseExistsCheckInUseDatabase; d->skipDatabaseExistsCheckInUseDatabase = true; bool ret = useTemporaryDatabaseIfNeeded(&tmpdbName); d->skipDatabaseExistsCheckInUseDatabase = orig_skipDatabaseExistsCheckInUseDatabase; if (!ret) return false; ret = drv_databaseExists(dbName, ignoreErrors); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } return ret; } #define createDatabase_CLOSE \ { if (!closeDatabase()) { \ m_result = KDbResult(KDbConnection::tr("Database \"%1\" has been created but " \ "could not be closed after creation.").arg(dbName)); \ return false; \ } } #define createDatabase_ERROR \ { createDatabase_CLOSE; return false; } bool KDbConnection::createDatabase(const QString &dbName) { if (d->driver->behavior()->CONNECTION_REQUIRED_TO_CREATE_DB && !checkConnected()) return false; if (databaseExists(dbName)) { m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Database \"%1\" already exists.").arg(dbName)); return false; } if (d->driver->isSystemDatabaseName(dbName)) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not create database \"%1\". This name is reserved for system database.").arg(dbName)); return false; } if (d->driver->metaData()->isFileBased()) { //update connection data if filename differs if (QFileInfo(dbName).isAbsolute()) { d->connData.setDatabaseName(dbName); } else { d->connData.setDatabaseName( QFileInfo(d->connData.databaseName()).absolutePath() + QDir::separator() + QFileInfo(dbName).fileName()); } } QString tmpdbName; //some engines need to have opened any database before executing "create database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return false; //low-level create if (!drv_createDatabase(dbName)) { m_result.prependMessage(tr("Error creating database \"%1\" on the server.").arg(dbName)); (void)closeDatabase();//sanity return false; } if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } if (!tmpdbName.isEmpty() || !d->driver->behavior()->IS_DB_OPEN_AFTER_CREATE) { //db need to be opened if (!useDatabase(dbName, false/*not yet kexi compatible!*/)) { m_result = KDbResult(tr("Database \"%1\" has been created but could not be opened.").arg(dbName)); return false; } } else { //just for the rule d->usedDatabase = dbName; d->isConnected = true; } KDbTransaction trans; if (d->driver->transactionsSupported()) { trans = beginTransaction(); if (!trans.isActive()) return false; } //-create system tables schema objects d->setupKDbSystemSchema(); //-physically create internal KDb tables foreach(KDbInternalTableSchema* t, d->internalKDbTables()) { if (!drv_createTable(*t)) createDatabase_ERROR; } //-insert KDb version info: // (for compatibility with Kexi expect the legacy kexidb_major_ver/kexidb_minor_ver values) KDbTableSchema *table = d->table(QLatin1String("kexi__db")); if (!table) createDatabase_ERROR; if (!insertRecord(table, QLatin1String("kexidb_major_ver"), KDb::version().major()) || !insertRecord(table, QLatin1String("kexidb_minor_ver"), KDb::version().minor())) createDatabase_ERROR; if (trans.isActive() && !commitTransaction(trans)) createDatabase_ERROR; createDatabase_CLOSE; return true; } #undef createDatabase_CLOSE #undef createDatabase_ERROR bool KDbConnection::useDatabase(const QString &dbName, bool kexiCompatible, bool *cancelled, KDbMessageHandler* msgHandler) { if (cancelled) *cancelled = false; //kdbDebug() << dbName << kexiCompatible; if (!checkConnected()) return false; QString my_dbName; if (dbName.isEmpty()) my_dbName = d->connData.databaseName(); else my_dbName = dbName; if (my_dbName.isEmpty()) return false; if (d->usedDatabase == my_dbName) return true; //already used if (!d->skipDatabaseExistsCheckInUseDatabase) { if (!databaseExists(my_dbName, false /*don't ignore errors*/)) return false; //database must exist } if (!d->usedDatabase.isEmpty() && !closeDatabase()) //close db if already used return false; d->usedDatabase.clear(); if (!drv_useDatabase(my_dbName, cancelled, msgHandler)) { if (cancelled && *cancelled) return false; QString msg(tr("Opening database \"%1\" failed.").arg(my_dbName)); m_result.prependMessage(msg); return false; } if (d->serverVersion.isNull() && d->driver->behavior()->USING_DATABASE_REQUIRED_TO_CONNECT) { // get version just now, it was not possible earlier if (!drv_getServerVersion(&d->serverVersion)) return false; } //-create system tables schema objects d->setupKDbSystemSchema(); if (kexiCompatible && my_dbName.compare(anyAvailableDatabaseName(), Qt::CaseInsensitive) != 0) { //-get global database information bool ok; const int major = d->dbProperties.value(QLatin1String("kexidb_major_ver")).toInt(&ok); if (!ok) { m_result = d->dbProperties.result(); return false; } const int minor = d->dbProperties.value(QLatin1String("kexidb_minor_ver")).toInt(&ok); if (!ok) { m_result = d->dbProperties.result(); return false; } d->databaseVersion.setMajor(major); d->databaseVersion.setMinor(minor); } d->usedDatabase = my_dbName; return true; } bool KDbConnection::closeDatabase() { if (d->usedDatabase.isEmpty()) return true; //no db used if (!checkConnected()) return true; bool ret = true; /*! @todo (js) add CLEVER algorithm here for nested transactions */ if (d->driver->transactionsSupported()) { //rollback all transactions d->dontRemoveTransactions = true; //lock! foreach(const KDbTransaction& tr, d->transactions) { if (!rollbackTransaction(tr)) {//rollback as much as you can, don't stop on prev. errors ret = false; } else { kdbDebug() << "transaction rolled back!"; kdbDebug() << "trans.refcount==" << (tr.m_data ? QString::number(tr.m_data->refcount()) : QLatin1String("(null)")); } } d->dontRemoveTransactions = false; //unlock! d->transactions.clear(); //free trans. data } //delete own cursors: d->deleteAllCursors(); //delete own schemas d->clearTables(); d->clearQueries(); if (!drv_closeDatabase()) return false; d->usedDatabase.clear(); return ret; } QString KDbConnection::currentDatabase() const { return d->usedDatabase; } bool KDbConnection::useTemporaryDatabaseIfNeeded(QString* name) { if (d->driver->behavior()->USE_TEMPORARY_DATABASE_FOR_CONNECTION_IF_NEEDED && !isDatabaseUsed()) { //we have no db used, but it is required by engine to have used any! *name = anyAvailableDatabaseName(); if (name->isEmpty()) { m_result = KDbResult(ERR_NO_DB_USED, tr("Could not find any database for temporary connection.")); return false; } const bool orig_skipDatabaseExistsCheckInUseDatabase = d->skipDatabaseExistsCheckInUseDatabase; d->skipDatabaseExistsCheckInUseDatabase = true; bool ret = useDatabase(*name, false); d->skipDatabaseExistsCheckInUseDatabase = orig_skipDatabaseExistsCheckInUseDatabase; if (!ret) { m_result = KDbResult(m_result.code(), tr("Error during starting temporary connection using \"%1\" database name.").arg(*name)); return false; } } return true; } bool KDbConnection::dropDatabase(const QString &dbName) { if (d->driver->behavior()->CONNECTION_REQUIRED_TO_DROP_DB && !checkConnected()) return false; QString dbToDrop; if (dbName.isEmpty() && d->usedDatabase.isEmpty()) { if (!d->driver->metaData()->isFileBased() || (d->driver->metaData()->isFileBased() && d->connData.databaseName().isEmpty())) { m_result = KDbResult(ERR_NO_NAME_SPECIFIED, tr("Could not delete database. Name is not specified.")); return false; } //this is a file driver so reuse previously passed filename dbToDrop = d->connData.databaseName(); } else { if (dbName.isEmpty()) { dbToDrop = d->usedDatabase; } else { if (d->driver->metaData()->isFileBased()) //lets get full path dbToDrop = QFileInfo(dbName).absoluteFilePath(); else dbToDrop = dbName; } } if (dbToDrop.isEmpty()) { m_result = KDbResult(ERR_NO_NAME_SPECIFIED, tr("Could not delete database. Name is not specified.")); return false; } if (d->driver->isSystemDatabaseName(dbToDrop)) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not delete system database \"%1\".").arg(dbToDrop)); return false; } if (isDatabaseUsed() && d->usedDatabase == dbToDrop) { //we need to close database because cannot drop used this database if (!closeDatabase()) return false; } QString tmpdbName; //some engines need to have opened any database before executing "drop database" if (!useTemporaryDatabaseIfNeeded(&tmpdbName)) return false; //ok, now we have access to dropping bool ret = drv_dropDatabase(dbToDrop); if (!tmpdbName.isEmpty()) { //whatever result is - now we have to close temporary opened database: if (!closeDatabase()) return false; } return ret; } QStringList KDbConnection::objectNames(int objectType, bool* ok) { if (!checkIsDatabaseUsed()) { if (ok) { *ok = false; } return QStringList(); } KDbEscapedString sql; if (objectType == KDb::AnyObjectType) { sql = "SELECT o_name FROM kexi__objects ORDER BY o_id"; } else { sql = KDbEscapedString("SELECT o_name FROM kexi__objects WHERE o_type=%1" " ORDER BY o_id").arg(d->driver->valueToSql(KDbField::Integer, objectType)); } QStringList list; const bool success = queryStringListInternal(&sql, &list, nullptr, nullptr, 0, KDb::isIdentifier); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of object names.")); } return list; } QStringList KDbConnection::tableNames(bool alsoSystemTables, bool* ok) { bool success; QStringList list = objectNames(KDb::TableObjectType, &success); if (ok) { *ok = success; } if (!success) { m_result.prependMessage(tr("Could not retrieve list of table names.")); } if (alsoSystemTables && success) { list += kdbSystemTableNames(); } return list; } tristate KDbConnection::containsTable(const QString &tableName) { return drv_containsTable(tableName); } QStringList KDbConnection::kdbSystemTableNames() { return *g_kdbSystemTableNames; } KDbServerVersionInfo KDbConnection::serverVersion() const { return isConnected() ? d->serverVersion : KDbServerVersionInfo(); } KDbVersionInfo KDbConnection::databaseVersion() const { return isDatabaseUsed() ? d->databaseVersion : KDbVersionInfo(); } KDbProperties KDbConnection::databaseProperties() const { return d->dbProperties; } QList KDbConnection::tableIds(bool* ok) { return objectIds(KDb::TableObjectType, ok); } QList KDbConnection::queryIds(bool* ok) { return objectIds(KDb::QueryObjectType, ok); } QList KDbConnection::objectIds(int objectType, bool* ok) { if (!checkIsDatabaseUsed()) return QList(); KDbEscapedString sql; if (objectType == KDb::AnyObjectType) sql = "SELECT o_id, o_name FROM kexi__objects ORDER BY o_id"; else sql = "SELECT o_id, o_name FROM kexi__objects WHERE o_type=" + QByteArray::number(objectType) + " ORDER BY o_id"; KDbCursor *c = executeQuery(sql); if (!c) { if (ok) { *ok = false; } m_result.prependMessage(tr("Could not retrieve list of object identifiers.")); return QList(); } QList list; for (c->moveFirst(); !c->eof(); c->moveNext()) { QString tname = c->value(1).toString(); //kexi__objects.o_name if (KDb::isIdentifier(tname)) { list.append(c->value(0).toInt()); //kexi__objects.o_id } } deleteCursor(c); if (ok) { *ok = true; } return list; } //yeah, it is very efficient: #define C_A(a) , const QVariant& c ## a #define V_A0 d->driver->valueToSql( tableSchema->field(0), c0 ) #define V_A(a) + ',' + d->driver->valueToSql( \ tableSchema->field(a) ? tableSchema->field(a)->type() : KDbField::Text, c ## a ) // kdbDebug() << "******** " << QString("INSERT INTO ") + // escapeIdentifier(tableSchema->name()) + // " VALUES (" + vals + ")"; QSharedPointer KDbConnection::insertRecordInternal(const QString &tableSchemaName, KDbFieldList *fields, const KDbEscapedString &sql) { QSharedPointer res; if (!drv_beforeInsert(tableSchemaName,fields )) { return res; } res = prepareSql(sql); if (!res || res->lastResult().isError()) { res.clear(); return res; } if (!drv_afterInsert(tableSchemaName, fields)) { res.clear(); return res; } { // Fetching is needed to perform real execution at least for some backends. // Also we are not expecting record but let's delete if there's any. QSharedPointer record = res->fetchRecord(); Q_UNUSED(record) } if (res->lastResult().isError()) { res.clear(); } return res; } #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbTableSchema* tableSchema args) { \ return insertRecordInternal(tableSchema->name(), tableSchema, \ KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) \ + " (" \ + tableSchema->sqlFieldsList(this) \ + ") VALUES (" + vals + ')'); \ } #define C_INS_REC_ALL \ C_INS_REC( C_A(0), V_A0 ) \ C_INS_REC( C_A(0) C_A(1), V_A0 V_A(1) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2), V_A0 V_A(1) V_A(2) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3), V_A0 V_A(1) V_A(2) V_A(3) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) ) \ C_INS_REC( C_A(0) C_A(1) C_A(2) C_A(3) C_A(4) C_A(5) C_A(6) C_A(7), V_A0 V_A(1) V_A(2) V_A(3) V_A(4) V_A(5) V_A(6) V_A(7) ) C_INS_REC_ALL #undef V_A0 #undef V_A #undef C_INS_REC #define V_A0 value += d->driver->valueToSql( it.next(), c0 ); #define V_A( a ) value += (',' + d->driver->valueToSql( it.next(), c ## a )); #define C_INS_REC(args, vals) \ QSharedPointer KDbConnection::insertRecord(KDbFieldList* fields args) \ { \ KDbEscapedString value; \ const KDbField::List *flist = fields->fields(); \ QListIterator it(*flist); \ vals \ it.toFront(); \ QString tableName((it.hasNext() && it.peekNext()->table()) ? it.next()->table()->name() : QLatin1String("??")); \ return insertRecordInternal(tableName, fields, \ KDbEscapedString(QLatin1String("INSERT INTO ") + escapeIdentifier(tableName)) \ + " (" + fields->sqlFieldsList(this) \ + ") VALUES (" + value + ')'); \ } C_INS_REC_ALL #undef C_A #undef V_A #undef V_ALAST #undef C_INS_REC #undef C_INS_REC_ALL QSharedPointer KDbConnection::insertRecord(KDbTableSchema *tableSchema, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = tableSchema->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); QList::ConstIterator it = values.constBegin(); KDbEscapedString sql; sql.reserve(4096); while (fieldsIt != flist->constEnd() && (it != values.end())) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableSchema->name()) + " VALUES ("; } else { sql += ','; } sql += d->driver->valueToSql(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSql( f, *it ); ++it; ++fieldsIt; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableSchema->name(), tableSchema, sql); return res; } QSharedPointer KDbConnection::insertRecord(KDbFieldList *fields, const QList &values) { // Each SQL identifier needs to be escaped in the generated query. QSharedPointer res; const KDbField::List *flist = fields->fields(); if (flist->isEmpty()) { return res; } KDbField::ListIterator fieldsIt(flist->constBegin()); KDbEscapedString sql; sql.reserve(4096); QList::ConstIterator it = values.constBegin(); const QString tableName(flist->first()->table()->name()); while (fieldsIt != flist->constEnd() && it != values.constEnd()) { KDbField *f = *fieldsIt; if (sql.isEmpty()) { sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(tableName) + '(' + fields->sqlFieldsList(this) + ") VALUES ("; } else { sql += ','; } sql += d->driver->valueToSql(f, *it); // kdbDebug() << "val" << i++ << ": " << d->driver->valueToSql( f, *it ); ++it; ++fieldsIt; if (fieldsIt == flist->constEnd()) break; } sql += ')'; m_result.setSql(sql); res = insertRecordInternal(tableName, fields, sql); return res; } inline static bool checkSql(const KDbEscapedString& sql, KDbResult* result) { Q_ASSERT(result); if (!sql.isValid()) { *result = KDbResult(ERR_SQL_EXECUTION_ERROR, KDbConnection::tr("SQL statement for execution is invalid or empty.")); result->setErrorSql(sql); //remember for error handling return false; } return true; } QSharedPointer KDbConnection::prepareSql(const KDbEscapedString& sql) { m_result.setSql(sql); return QSharedPointer(drv_prepareSql(sql)); } bool KDbConnection::executeSql(const KDbEscapedString& sql) { m_result.setSql(sql); if (!checkSql(sql, &m_result)) { return false; } if (!drv_executeSql(sql)) { m_result.setMessage(QString()); //clear as this could be most probably just "Unknown error" string. m_result.setErrorSql(sql); m_result.prependMessage(ERR_SQL_EXECUTION_ERROR, tr("Error while executing SQL statement.")); kdbWarning() << m_result; return false; } return true; } KDbField* KDbConnection::findSystemFieldName(const KDbFieldList& fieldlist) { for (KDbField::ListIterator it(fieldlist.fieldsIterator()); it != fieldlist.fieldsIteratorConstEnd(); ++it) { if (d->driver->isSystemFieldName((*it)->name())) return *it; } return nullptr; } //! Creates a KDbField list for kexi__fields, for sanity. Used by createTable() static KDbFieldList* createFieldListForKexi__Fields(KDbTableSchema *kexi__fieldsSchema) { if (!kexi__fieldsSchema) return nullptr; return kexi__fieldsSchema->subList( QList() << "t_id" << "f_type" << "f_name" << "f_length" << "f_precision" << "f_constraints" << "f_options" << "f_default" << "f_order" << "f_caption" << "f_help" ); } static QVariant buildLengthValue(const KDbField &f) { if (f.isFPNumericType()) { return f.scale(); } return f.maxLength(); } //! builds a list of values for field's @a f properties. Used by createTable(). static void buildValuesForKexi__Fields(QList& vals, KDbField* f) { const KDbField::Type type = f->type(); // cache: evaluating type of expressions can be expensive vals.clear(); vals << QVariant(f->table()->id()) << QVariant(type) << QVariant(f->name()) << buildLengthValue(*f) << QVariant(KDbField::isFPNumericType(type) ? f->precision() : 0) << QVariant(f->constraints()) << QVariant(f->options()) // KDb::variantToString() is needed here because the value can be of any QVariant type, // depending on f->type() << (f->defaultValue().isNull() ? QVariant() : QVariant(KDb::variantToString(f->defaultValue()))) << QVariant(f->order()) << QVariant(f->caption()) << QVariant(f->description()); } bool KDbConnection::storeMainFieldSchema(KDbField *field) { if (!field || !field->table()) return false; KDbFieldList *fl = createFieldListForKexi__Fields(d->table(QLatin1String("kexi__fields"))); if (!fl) return false; QList vals; buildValuesForKexi__Fields(vals, field); QList::ConstIterator valsIt = vals.constBegin(); bool first = true; KDbEscapedString sql("UPDATE kexi__fields SET "); foreach(KDbField *f, *fl->fields()) { sql.append((first ? QString() : QLatin1String(", ")) + f->name() + QLatin1Char('=') + d->driver->valueToSql(f, *valsIt)); if (first) first = false; ++valsIt; } delete fl; sql.append(KDbEscapedString(" WHERE t_id=%1 AND f_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, field->table()->id())) .arg(escapeString(field->name()))); return executeSql(sql); } #define createTable_ERR \ { kdbDebug() << "ERROR!"; \ m_result.prependMessage(KDbConnection::tr("Creating table failed.")); \ rollbackAutoCommitTransaction(tg.transaction()); \ return false; } bool KDbConnection::createTable(KDbTableSchema* tableSchema, CreateTableOptions options) { if (!tableSchema || !checkIsDatabaseUsed()) return false; //check if there are any fields if (tableSchema->fieldCount() < 1) { clearResult(); m_result = KDbResult(ERR_CANNOT_CREATE_EMPTY_OBJECT, tr("Could not create table without fields.")); return false; } KDbInternalTableSchema* internalTable = dynamic_cast(tableSchema); const QString tableName(tableSchema->name()); if (!internalTable) { if (d->driver->isSystemObjectName(tableName)) { clearResult(); m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("System name \"%1\" cannot be used as table name.") .arg(tableSchema->name())); return false; } KDbField *sys_field = findSystemFieldName(*tableSchema); if (sys_field) { clearResult(); m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("System name \"%1\" cannot be used as one of fields in \"%2\" table.") .arg(sys_field->name(), tableName)); return false; } } bool previousSchemaStillKept = false; KDbTableSchema *existingTable = nullptr; if (options & CreateTableOption::DropDestination) { //get previous table (do not retrieve, though) existingTable = this->tableSchema(tableName); if (existingTable) { if (existingTable == tableSchema) { clearResult(); m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Could not create the same table \"%1\" twice.").arg(tableSchema->name())); return false; } //! @todo (js) update any structure (e.g. queries) that depend on this table! if (existingTable->id() > 0) tableSchema->setId(existingTable->id()); //copy id from existing table previousSchemaStillKept = true; if (!dropTableInternal(existingTable, false /*alsoRemoveSchema*/)) return false; } } else { if (this->tableSchema(tableSchema->name())) { clearResult(); m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Table \"%1\" already exists.").arg(tableSchema->name())); return false; } } KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; if (internalTable) { if (!drv_containsTable(internalTable->name())) { // internal table may exist if (!drv_createTable(*tableSchema)) { createTable_ERR; } } } else { if (!drv_createTable(*tableSchema)) { createTable_ERR; } } //add the object data to kexi__* tables if (!internalTable) { //update kexi__objects if (!storeNewObjectData(tableSchema)) createTable_ERR; KDbTableSchema *ts = d->table(QLatin1String("kexi__fields")); if (!ts) return false; //for sanity: remove field info (if any) for this table id if (!KDb::deleteRecords(this, *ts, QLatin1String("t_id"), tableSchema->id())) return false; KDbFieldList *fl = createFieldListForKexi__Fields(ts); if (!fl) return false; foreach(KDbField *f, *tableSchema->fields()) { QList vals; buildValuesForKexi__Fields(vals, f); if (!insertRecord(fl, vals)) createTable_ERR; } delete fl; if (!storeExtendedTableSchemaData(tableSchema)) createTable_ERR; } bool res = commitAutoCommitTransaction(tg.transaction()); if (res) { if (!internalTable) { if (previousSchemaStillKept) { //remove previous table schema d->removeTable(*tableSchema); } } //store locally d->insertTable(tableSchema); //ok, this table is not created by the connection tableSchema->setConnection(this); } return res; } KDbTableSchema *KDbConnection::copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData) { clearResult(); if (this->tableSchema(tableSchema.name()) != &tableSchema) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableSchema.name())); return nullptr; } KDbTableSchema *copiedTable = new KDbTableSchema(tableSchema, false /* !copyId*/); // copy name, caption, description copiedTable->setName(newData.name()); copiedTable->setCaption(newData.caption()); copiedTable->setDescription(newData.description()); // copy the structure and data if (!createTable(copiedTable, CreateTableOptions(CreateTableOption::Default) & ~CreateTableOptions(CreateTableOption::DropDestination))) { delete copiedTable; return nullptr; } if (!drv_copyTableData(tableSchema, *copiedTable)) { dropTable(copiedTable); delete copiedTable; return nullptr; } return copiedTable; } KDbTableSchema *KDbConnection::copyTable(const QString &tableName, const KDbObject &newData) { clearResult(); KDbTableSchema* ts = tableSchema(tableName); if (!ts) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableName)); return nullptr; } return copyTable(*ts, newData); } bool KDbConnection::drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema) { KDbEscapedString sql = KDbEscapedString("INSERT INTO %1 SELECT * FROM %2") .arg(escapeIdentifier(destinationTableSchema.name())) .arg(escapeIdentifier(tableSchema.name())); return executeSql(sql); } bool KDbConnection::removeObject(int objId) { clearResult(); //remove table schema from kexi__* tables KDbTableSchema *kexi__objects = d->table(QLatin1String("kexi__objects")); KDbTableSchema *kexi__objectdata = d->table(QLatin1String("kexi__objectdata")); if (!kexi__objects || !kexi__objectdata || !KDb::deleteRecords(this, *kexi__objects, QLatin1String("o_id"), objId) //schema entry || !KDb::deleteRecords(this, *kexi__objectdata, QLatin1String("o_id"), objId)) //data blocks { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Could not delete object's data.")); return false; } return true; } bool KDbConnection::drv_dropTable(const QString& tableName) { return executeSql(KDbEscapedString("DROP TABLE %1").arg(escapeIdentifier(tableName))); } tristate KDbConnection::dropTable(KDbTableSchema* tableSchema) { return dropTableInternal(tableSchema, true); } tristate KDbConnection::dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); if (!tableSchema) return false; //be sure that we handle the correct KDbTableSchema object: if (tableSchema->id() < 0 || this->tableSchema(tableSchema->name()) != tableSchema || this->tableSchema(tableSchema->id()) != tableSchema) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Could not delete table \"%1\". %2") .arg(tr("Unexpected name or identifier."), tableSchema->name())); return false; } tristate res = KDbTableSchemaChangeListener::closeListeners(this, tableSchema); if (true != res) return res; //sanity checks: if (d->driver->isSystemObjectName(tableSchema->name())) { m_result = KDbResult(ERR_SYSTEM_NAME_RESERVED, tr("Could not delete table \"%1\". %2") .arg(tableSchema->name(), d->strItIsASystemObject())); return false; } KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; //for sanity we're checking if this table exists physically const tristate result = drv_containsTable(tableSchema->name()); if (~result) { return cancelled; } if (result == true) { if (!drv_dropTable(tableSchema->name())) return false; } KDbTableSchema *ts = d->table(QLatin1String("kexi__fields")); if (!ts || !KDb::deleteRecords(this, *ts, QLatin1String("t_id"), tableSchema->id())) //field entries return false; //remove table schema from kexi__objects table if (!removeObject(tableSchema->id())) { return false; } if (alsoRemoveSchema) { //! @todo js: update any structure (e.g. queries) that depend on this table! tristate res = removeDataBlock(tableSchema->id(), QLatin1String("extended_schema")); if (!res) return false; d->removeTable(*tableSchema); } return commitAutoCommitTransaction(tg.transaction()); } tristate KDbConnection::dropTable(const QString& tableName) { clearResult(); KDbTableSchema* ts = tableSchema(tableName); if (!ts) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Table \"%1\" does not exist.").arg(tableName)); return false; } return dropTable(ts); } tristate KDbConnection::alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema) { clearResult(); tristate res = KDbTableSchemaChangeListener::closeListeners(this, tableSchema); if (true != res) return res; if (tableSchema == newTableSchema) { m_result = KDbResult(ERR_OBJECT_THE_SAME, tr("Could not alter table \"%1\" using the same table as destination.") .arg(tableSchema->name())); return false; } //! @todo (js) implement real altering //! @todo (js) update any structure (e.g. query) that depend on this table! bool ok = true; bool empty; #if 0 //! @todo uncomment: empty = isEmpty(tableSchema, ok) && ok; #else empty = true; #endif if (empty) { ok = createTable(newTableSchema, KDbConnection::CreateTableOption::Default | KDbConnection::CreateTableOption::DropDestination); } return ok; } bool KDbConnection::alterTableName(KDbTableSchema* tableSchema, const QString& newName, AlterTableNameOptions options) { clearResult(); if (tableSchema != this->tableSchema(tableSchema->id())) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Unknown table \"%1\".").arg(tableSchema->name())); return false; } if (newName.isEmpty() || !KDb::isIdentifier(newName)) { m_result = KDbResult(ERR_INVALID_IDENTIFIER, tr("Invalid table name \"%1\".").arg(newName)); return false; } const QString oldTableName = tableSchema->name(); const QString newTableName = newName.trimmed(); if (oldTableName.trimmed() == newTableName) { m_result = KDbResult(ERR_OBJECT_THE_SAME, tr("Could not rename table \"%1\" using the same name.") .arg(newTableName)); return false; } //! @todo alter table name for server DB backends! //! @todo what about objects (queries/forms) that use old name? KDbTableSchema *tableToReplace = this->tableSchema(newName); const bool destTableExists = tableToReplace != nullptr; const int origID = destTableExists ? tableToReplace->id() : -1; //will be reused in the new table if (!(options & AlterTableNameOption::DropDestination) && destTableExists) { m_result = KDbResult(ERR_OBJECT_EXISTS, tr("Could not rename table \"%1\" to \"%2\". Table \"%3\" already exists.") .arg(tableSchema->name(), newName, newName)); return false; } //helper: #define alterTableName_ERR \ tableSchema->setName(oldTableName) //restore old name KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; // drop the table replaced (with schema) if (destTableExists) { if (!dropTable(newName)) { return false; } // the new table owns the previous table's id: if (!executeSql( KDbEscapedString("UPDATE kexi__objects SET o_id=%1 WHERE o_id=%2 AND o_type=%3") .arg(d->driver->valueToSql(KDbField::Integer, origID)) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())) .arg(d->driver->valueToSql(KDbField::Integer, int(KDb::TableObjectType))))) { return false; } if (!executeSql(KDbEscapedString("UPDATE kexi__fields SET t_id=%1 WHERE t_id=%2") .arg(d->driver->valueToSql(KDbField::Integer, origID)) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())))) { return false; } //maintain table ID d->changeTableId(tableSchema, origID); tableSchema->setId(origID); } if (!drv_alterTableName(tableSchema, newTableName)) { alterTableName_ERR; return false; } // Update kexi__objects //! @todo if (!executeSql(KDbEscapedString("UPDATE kexi__objects SET o_name=%1 WHERE o_id=%2") .arg(escapeString(tableSchema->name())) .arg(d->driver->valueToSql(KDbField::Integer, tableSchema->id())))) { alterTableName_ERR; return false; } //! @todo what about caption? //restore old name: it will be changed soon! tableSchema->setName(oldTableName); if (!commitAutoCommitTransaction(tg.transaction())) { alterTableName_ERR; return false; } //update tableSchema: d->renameTable(tableSchema, newTableName); return true; } bool KDbConnection::drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName) { const QString oldTableName = tableSchema->name(); tableSchema->setName(newName); if (!executeSql(KDbEscapedString("ALTER TABLE %1 RENAME TO %2") .arg(KDbEscapedString(escapeIdentifier(oldTableName)), KDbEscapedString(escapeIdentifier(newName))))) { tableSchema->setName(oldTableName); //restore old name return false; } return true; } bool KDbConnection::dropQuery(KDbQuerySchema* querySchema) { clearResult(); if (!querySchema) return false; KDbTransactionGuard tg; if (!beginAutoCommitTransaction(&tg)) return false; //remove query schema from kexi__objects table if (!removeObject(querySchema->id())) { return false; } //! @todo update any structure that depend on this table! d->removeQuery(querySchema); return commitAutoCommitTransaction(tg.transaction()); } bool KDbConnection::dropQuery(const QString& queryName) { clearResult(); KDbQuerySchema* qs = querySchema(queryName); if (!qs) { m_result = KDbResult(ERR_OBJECT_NOT_FOUND, tr("Query \"%1\" does not exist.").arg(queryName)); return false; } return dropQuery(qs); } bool KDbConnection::drv_createTable(const KDbTableSchema& tableSchema) { const KDbNativeStatementBuilder builder(this); KDbEscapedString sql; if (!builder.generateCreateTableStatement(&sql,tableSchema)) { return false; } //kdbDebug() << "******** " << sql; return executeSql(sql); } bool KDbConnection::drv_createTable(const QString& tableName) { KDbTableSchema *ts = tableSchema(tableName); if (!ts) return false; return drv_createTable(*ts); } bool KDbConnection::beginAutoCommitTransaction(KDbTransactionGuard* tg) { if ((d->driver->behavior()->features & KDbDriver::IgnoreTransactions) || !d->autoCommit) { tg->setTransaction(KDbTransaction()); return true; } // commit current transaction (if present) for drivers // that allow single transaction per connection if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (d->defaultTransactionStartedInside) //only commit internally started transaction if (!commitTransaction(d->default_trans, KDbTransaction::CommitOption::IgnoreInactive)) { tg->setTransaction(KDbTransaction()); return false; //we have a real error } d->defaultTransactionStartedInside = d->default_trans.isNull(); if (!d->defaultTransactionStartedInside) { tg->setTransaction(d->default_trans); tg->doNothing(); return true; //reuse externally started transaction } } else if (!(d->driver->behavior()->features & KDbDriver::MultipleTransactions)) { tg->setTransaction(KDbTransaction()); return true; //no trans. supported at all - just return } tg->setTransaction(beginTransaction()); return !m_result.isError(); } bool KDbConnection::commitAutoCommitTransaction(const KDbTransaction& trans) { if (d->driver->behavior()->features & KDbDriver::IgnoreTransactions) return true; if (trans.isNull() || !d->driver->transactionsSupported()) return true; if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (!d->defaultTransactionStartedInside) //only commit internally started transaction return true; //give up } return commitTransaction(trans, KDbTransaction::CommitOption::IgnoreInactive); } bool KDbConnection::rollbackAutoCommitTransaction(const KDbTransaction& trans) { if (trans.isNull() || !d->driver->transactionsSupported()) return true; return rollbackTransaction(trans); } #define SET_ERR_TRANS_NOT_SUPP \ { m_result = KDbResult(ERR_UNSUPPORTED_DRV_FEATURE, \ KDbConnection::tr("Transactions are not supported for \"%1\" driver.").arg( d->driver->metaData()->name() )); } #define SET_BEGIN_TR_ERROR \ { if (!m_result.isError()) \ m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, \ KDbConnection::tr("Begin transaction failed.")); } KDbTransaction KDbConnection::beginTransaction() { if (!checkIsDatabaseUsed()) return KDbTransaction(); KDbTransaction trans; if (d->driver->behavior()->features & KDbDriver::IgnoreTransactions) { //we're creating dummy transaction data here, //so it will look like active trans.m_data = new KDbTransactionData(this); d->transactions.append(trans); return trans; } if (d->driver->behavior()->features & KDbDriver::SingleTransactions) { if (d->default_trans.isActive()) { m_result = KDbResult(ERR_TRANSACTION_ACTIVE, tr("Transaction already started.")); return KDbTransaction(); } if (!(trans.m_data = drv_beginTransaction())) { SET_BEGIN_TR_ERROR; return KDbTransaction(); } d->default_trans = trans; d->transactions.append(trans); return d->default_trans; } if (d->driver->behavior()->features & KDbDriver::MultipleTransactions) { if (!(trans.m_data = drv_beginTransaction())) { SET_BEGIN_TR_ERROR; return KDbTransaction(); } d->transactions.append(trans); return trans; } SET_ERR_TRANS_NOT_SUPP; return KDbTransaction(); } bool KDbConnection::commitTransaction(const KDbTransaction trans, KDbTransaction::CommitOptions options) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.isActive()) { //try default tr. if (!d->default_trans.isActive()) { if (options & KDbTransaction::CommitOption::IgnoreInactive) { return true; } clearResult(); m_result = KDbResult(ERR_NO_TRANSACTION_ACTIVE, tr("Transaction not started.")); return false; } t = d->default_trans; d->default_trans = KDbTransaction(); //now: no default tr. } bool ret = true; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) ret = drv_commitTransaction(t.m_data); if (t.m_data) t.m_data->setActive(false); //now this transaction if inactive if (!d->dontRemoveTransactions) //true=transaction obj will be later removed from list d->transactions.removeAt(d->transactions.indexOf(t)); if (!ret && !m_result.isError()) m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, tr("Error on commit transaction.")); return ret; } bool KDbConnection::rollbackTransaction(const KDbTransaction trans, KDbTransaction::CommitOptions options) { if (!isDatabaseUsed()) return false; if (!d->driver->transactionsSupported() && !(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) { SET_ERR_TRANS_NOT_SUPP; return false; } KDbTransaction t = trans; if (!t.isActive()) { //try default tr. if (!d->default_trans.isActive()) { if (options & KDbTransaction::CommitOption::IgnoreInactive) { return true; } clearResult(); m_result = KDbResult(ERR_NO_TRANSACTION_ACTIVE, tr("Transaction not started.")); return false; } t = d->default_trans; d->default_trans = KDbTransaction(); //now: no default tr. } bool ret = true; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions)) ret = drv_rollbackTransaction(t.m_data); if (t.m_data) t.m_data->setActive(false); //now this transaction if inactive if (!d->dontRemoveTransactions) //true=transaction obj will be later removed from list d->transactions.removeAt(d->transactions.indexOf(t)); if (!ret && !m_result.isError()) m_result = KDbResult(ERR_ROLLBACK_OR_COMMIT_TRANSACTION, tr("Error on rollback transaction.")); return ret; } #undef SET_ERR_TRANS_NOT_SUPP #undef SET_BEGIN_TR_ERROR /*bool KDbConnection::duringTransaction() { return drv_duringTransaction(); }*/ KDbTransaction KDbConnection::defaultTransaction() const { return d->default_trans; } void KDbConnection::setDefaultTransaction(const KDbTransaction& trans) { if (!isDatabaseUsed()) return; if (!(d->driver->behavior()->features & KDbDriver::IgnoreTransactions) && (!trans.isActive() || !d->driver->transactionsSupported())) { return; } d->default_trans = trans; } QList KDbConnection::transactions() { return d->transactions; } bool KDbConnection::autoCommit() const { return d->autoCommit; } bool KDbConnection::setAutoCommit(bool on) { if (d->autoCommit == on || d->driver->behavior()->features & KDbDriver::IgnoreTransactions) return true; if (!drv_setAutoCommit(on)) return false; d->autoCommit = on; return true; } KDbTransactionData* KDbConnection::drv_beginTransaction() { if (!executeSql(KDbEscapedString("BEGIN"))) return nullptr; return new KDbTransactionData(this); } bool KDbConnection::drv_commitTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("COMMIT")); } bool KDbConnection::drv_rollbackTransaction(KDbTransactionData *) { return executeSql(KDbEscapedString("ROLLBACK")); } bool KDbConnection::drv_setAutoCommit(bool /*on*/) { return true; } KDbCursor* KDbConnection::executeQuery(const KDbEscapedString& sql, KDbCursor::Options options) { if (sql.isEmpty()) return nullptr; KDbCursor *c = prepareQuery(sql, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor *c = prepareQuery(query, params, options); if (!c) return nullptr; if (!c->open()) {//err - kill that m_result = c->result(); CursorDeleter deleter(c); return nullptr; } return c; } KDbCursor* KDbConnection::executeQuery(KDbQuerySchema* query, KDbCursor::Options options) { return executeQuery(query, QList(), options); } KDbCursor* KDbConnection::executeQuery(KDbTableSchema* table, KDbCursor::Options options) { return executeQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbTableSchema* table, KDbCursor::Options options) { return prepareQuery(table->query(), options); } KDbCursor* KDbConnection::prepareQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options) { KDbCursor* cursor = prepareQuery(query, options); if (cursor) cursor->setQueryParameters(params); return cursor; } bool KDbConnection::deleteCursor(KDbCursor *cursor) { if (!cursor) return false; if (cursor->connection() != this) {//illegal call kdbWarning() << "Could not delete the cursor not owned by the same connection!"; return false; } const bool ret = cursor->close(); CursorDeleter deleter(cursor); return ret; } //! @todo IMPORTANT: fix KDbConnection::setupObjectData() after refactoring bool KDbConnection::setupObjectData(const KDbRecordData &data, KDbObject *object) { if (data.count() < 5) { kdbWarning() << "Aborting, object data should have at least 5 elements, found" << data.count(); return false; } bool ok; const int id = data[0].toInt(&ok); if (!ok) return false; object->setId(id); const QString name(data[2].toString()); if (!KDb::isIdentifier(name)) { m_result = KDbResult(ERR_INVALID_IDENTIFIER, tr("Invalid object name \"%1\".").arg(name)); return false; } object->setName(name); object->setCaption(data[3].toString()); object->setDescription(data[4].toString()); // kdbDebug()<<"@@@ KDbConnection::setupObjectData() == " << sdata.schemaDataDebugString(); return true; } tristate KDbConnection::loadObjectData(int type, int id, KDbObject* object) { KDbRecordData data; if (type == KDb::AnyObjectType) { if (true != querySingleRecord(KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, " "o_desc FROM kexi__objects WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, id)), &data)) { return cancelled; } } else { if (true != querySingleRecord(KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc " "FROM kexi__objects WHERE o_type=%1 AND o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, type)) .arg(d->driver->valueToSql(KDbField::Integer, id)), &data)) { return cancelled; } } return setupObjectData(data, object); } tristate KDbConnection::loadObjectData(int type, const QString& name, KDbObject* object) { KDbRecordData data; if (true != querySingleRecord( KDbEscapedString("SELECT o_id, o_type, o_name, o_caption, o_desc " "FROM kexi__objects WHERE o_type=%1 AND o_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, type)) .arg(escapeString(name)), &data)) { return cancelled; } return setupObjectData(data, object); } bool KDbConnection::storeObjectDataInternal(KDbObject* object, bool newObject) { KDbTableSchema *ts = d->table(QLatin1String("kexi__objects")); if (!ts) return false; if (newObject) { int existingID; if (true == querySingleNumber( KDbEscapedString("SELECT o_id FROM kexi__objects WHERE o_type=%1 AND o_name=%2") .arg(d->driver->valueToSql(KDbField::Integer, object->type())) .arg(escapeString(object->name())), &existingID)) { //we already have stored an object data with the same name and type: //just update it's properties as it would be existing object object->setId(existingID); newObject = false; } } if (newObject) { if (object->id() <= 0) {//get new ID QScopedPointer fl(ts->subList( QList() << "o_type" << "o_name" << "o_caption" << "o_desc")); if (!fl) { return false; } QSharedPointer result = insertRecord(fl.data(), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); if (!result) { return false; } //fetch newly assigned ID //! @todo safe to cast it? quint64 obj_id = KDb::lastInsertedAutoIncValue(result, QLatin1String("o_id"), *ts); //kdbDebug() << "NEW obj_id == " << obj_id; if (obj_id == std::numeric_limits::max()) { return false; } object->setId(obj_id); return true; } else { QScopedPointer fl(ts->subList( QList() << "o_id" << "o_type" << "o_name" << "o_caption" << "o_desc")); return fl && insertRecord(fl.data(), QVariant(object->id()), QVariant(object->type()), QVariant(object->name()), QVariant(object->caption()), QVariant(object->description())); } } //existing object: return executeSql( KDbEscapedString("UPDATE kexi__objects SET o_type=%2, o_caption=%3, o_desc=%4 WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, object->id())) .arg(d->driver->valueToSql(KDbField::Integer, object->type())) .arg(escapeString(object->caption())) .arg(escapeString(object->description()))); } bool KDbConnection::storeObjectData(KDbObject* object) { return storeObjectDataInternal(object, false); } bool KDbConnection::storeNewObjectData(KDbObject* object) { return storeObjectDataInternal(object, true); } QString KDbConnection::escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const { return escapingType == KDb::KDbEscaping ? KDb::escapeIdentifier(id) : escapeIdentifier(id); } KDbCursor* KDbConnection::executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params) { Q_ASSERT(!sql.isEmpty() || query); clearResult(); if (!sql.isEmpty()) { return executeQuery(sql); } if (!query) { return nullptr; } if (params) { return executeQuery(query, *params); } return executeQuery(query); } tristate KDbConnection::querySingleRecordInternal(KDbRecordData *data, const KDbEscapedString *sql, KDbQuerySchema *query, const QList *params, QueryRecordOptions options) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, options & QueryRecordOption::AddLimitTo1)); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!querySingleRecordInternal() " << m_result.sql(); return false; } if (!cursor->moveFirst() || cursor->eof() || !cursor->storeCurrentRecord(data)) { const tristate result = cursor->result().isError() ? tristate(false) : tristate(cancelled); // kdbDebug() << "!cursor->moveFirst() || cursor->eof() || cursor->storeCurrentRecord(data) // " // "m_result.sql()=" << m_result.sql(); m_result = cursor->result(); deleteCursor(cursor); return result; } return deleteCursor(cursor); } tristate KDbConnection::querySingleRecord(const KDbEscapedString &sql, KDbRecordData *data, QueryRecordOptions options) { return querySingleRecordInternal(data, &sql, nullptr, nullptr, options); } tristate KDbConnection::querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, QueryRecordOptions options) { return querySingleRecordInternal(data, nullptr, query, nullptr, options); } tristate KDbConnection::querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, const QList ¶ms, QueryRecordOptions options) { return querySingleRecordInternal(data, nullptr, query, ¶ms, options); } bool KDbConnection::checkIfColumnExists(KDbCursor *cursor, int column) { if (column >= cursor->fieldCount()) { m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Column \"%1\" does not exist in the query.").arg(column)); return false; } return true; } tristate KDbConnection::querySingleStringInternal(const KDbEscapedString *sql, QString *value, KDbQuerySchema *query, const QList *params, int column, QueryRecordOptions options) { Q_ASSERT(sql || query); if (sql) { //! @todo does not work with non-SQL data sources m_result.setSql(d->driver->addLimitTo1(*sql, options & QueryRecordOption::AddLimitTo1)); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!querySingleStringInternal()" << m_result.sql(); return false; } if (!cursor->moveFirst() || cursor->eof()) { const tristate result = cursor->result().isError() ? tristate(false) : tristate(cancelled); // kdbDebug() << "!cursor->moveFirst() || cursor->eof()" << m_result.sql(); deleteCursor(cursor); return result; } if (!checkIfColumnExists(cursor, column)) { deleteCursor(cursor); return false; } if (value) { *value = cursor->value(column).toString(); } return deleteCursor(cursor); } tristate KDbConnection::querySingleString(const KDbEscapedString &sql, QString *value, int column, QueryRecordOptions options) { return querySingleStringInternal(&sql, value, nullptr, nullptr, column, options); } tristate KDbConnection::querySingleString(KDbQuerySchema *query, QString *value, int column, QueryRecordOptions options) { return querySingleStringInternal(nullptr, value, query, nullptr, column, options); } tristate KDbConnection::querySingleString(KDbQuerySchema *query, QString *value, const QList ¶ms, int column, QueryRecordOptions options) { return querySingleStringInternal(nullptr, value, query, ¶ms, column, options); } tristate KDbConnection::querySingleNumberInternal(const KDbEscapedString *sql, int *number, KDbQuerySchema *query, const QList *params, int column, QueryRecordOptions options) { QString str; const tristate result = querySingleStringInternal(sql, &str, query, params, column, options); if (result != true) return result; bool ok; const int _number = str.toInt(&ok); if (!ok) return false; if (number) { *number = _number; } return true; } tristate KDbConnection::querySingleNumber(const KDbEscapedString &sql, int *number, int column, QueryRecordOptions options) { return querySingleNumberInternal(&sql, number, nullptr, nullptr, column, options); } tristate KDbConnection::querySingleNumber(KDbQuerySchema *query, int *number, int column, QueryRecordOptions options) { return querySingleNumberInternal(nullptr, number, query, nullptr, column, options); } tristate KDbConnection::querySingleNumber(KDbQuerySchema *query, int *number, const QList ¶ms, int column, QueryRecordOptions options) { return querySingleNumberInternal(nullptr, number, query, ¶ms, column, options); } bool KDbConnection::queryStringListInternal(const KDbEscapedString *sql, QStringList *list, KDbQuerySchema *query, const QList *params, int column, bool (*filterFunction)(const QString &)) { if (sql) { m_result.setSql(*sql); } KDbCursor *cursor = executeQueryInternal(m_result.sql(), query, params); if (!cursor) { kdbWarning() << "!queryStringListInternal() " << m_result.sql(); return false; } cursor->moveFirst(); if (cursor->result().isError()) { m_result = cursor->result(); deleteCursor(cursor); return false; } if (!cursor->eof() && !checkIfColumnExists(cursor, column)) { deleteCursor(cursor); return false; } if (list) { list->clear(); } QStringList listResult; while (!cursor->eof()) { const QString str(cursor->value(column).toString()); if (!filterFunction || filterFunction(str)) { listResult.append(str); } if (!cursor->moveNext() && cursor->result().isError()) { m_result = cursor->result(); deleteCursor(cursor); return false; } } if (list) { *list = listResult; } return deleteCursor(cursor); } bool KDbConnection::queryStringList(const KDbEscapedString& sql, QStringList* list, int column) { return queryStringListInternal(&sql, list, nullptr, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, int column) { return queryStringListInternal(nullptr, list, query, nullptr, column, nullptr); } bool KDbConnection::queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column) { return queryStringListInternal(nullptr, list, query, ¶ms, column, nullptr); } tristate KDbConnection::resultExists(const KDbEscapedString &sql, QueryRecordOptions options) { // optimization if (d->driver->behavior()->SELECT_1_SUBQUERY_SUPPORTED) { // this is at least for sqlite if ((options & QueryRecordOption::AddLimitTo1) && sql.left(6).toUpper() == "SELECT") { m_result.setSql(d->driver->addLimitTo1("SELECT 1 FROM (" + sql + ')')); } else { m_result.setSql(sql); } } else { if ((options & QueryRecordOption::AddLimitTo1) && sql.startsWith("SELECT")) { m_result.setSql(d->driver->addLimitTo1(sql)); } else { m_result.setSql(sql); } } KDbCursor *cursor = executeQuery(m_result.sql()); if (!cursor) { kdbWarning() << "!executeQuery()" << m_result.sql(); return cancelled; } if (!cursor->moveFirst() || cursor->eof()) { kdbWarning() << "!cursor->moveFirst() || cursor->eof()" << m_result.sql(); m_result = cursor->result(); deleteCursor(cursor); return m_result.isError() ? cancelled : tristate(false); } return deleteCursor(cursor) ? tristate(true) : cancelled; } tristate KDbConnection::isEmpty(KDbTableSchema* table) { const KDbNativeStatementBuilder builder(this); KDbEscapedString sql; if (!builder.generateSelectStatement(&sql, table)) { return cancelled; } const tristate result = resultExists(sql); if (~result) { return cancelled; } return result == false; } //! Used by addFieldPropertyToExtendedTableSchemaData() static void createExtendedTableSchemaMainElementIfNeeded( QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, bool* extendedTableSchemaStringIsEmpty) { if (!*extendedTableSchemaStringIsEmpty) return; //init document *extendedTableSchemaMainEl = doc->createElement(QLatin1String("EXTENDED_TABLE_SCHEMA")); doc->appendChild(*extendedTableSchemaMainEl); extendedTableSchemaMainEl->setAttribute(QLatin1String("version"), QString::number(KDB_EXTENDED_TABLE_SCHEMA_VERSION)); *extendedTableSchemaStringIsEmpty = false; } //! Used by addFieldPropertyToExtendedTableSchemaData() static void createExtendedTableSchemaFieldElementIfNeeded(QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, const QString& fieldName, QDomElement* extendedTableSchemaFieldEl, bool append = true) { if (!extendedTableSchemaFieldEl->isNull()) return; *extendedTableSchemaFieldEl = doc->createElement(QLatin1String("field")); if (append) extendedTableSchemaMainEl->appendChild(*extendedTableSchemaFieldEl); extendedTableSchemaFieldEl->setAttribute(QLatin1String("name"), fieldName); } /*! @internal used by storeExtendedTableSchemaData() Creates DOM node for @a propertyName and @a propertyValue. Creates enclosing EXTENDED_TABLE_SCHEMA element if EXTENDED_TABLE_SCHEMA is true. Updates extendedTableSchemaStringIsEmpty and extendedTableSchemaMainEl afterwards. If extendedTableSchemaFieldEl is null, creates element (with optional "custom" attribute is @a custom is false). */ static void addFieldPropertyToExtendedTableSchemaData( const KDbField& f, const QByteArray &propertyName, const QVariant& propertyValue, QDomDocument* doc, QDomElement* extendedTableSchemaMainEl, QDomElement* extendedTableSchemaFieldEl, bool* extendedTableSchemaStringIsEmpty, bool custom = false) { createExtendedTableSchemaMainElementIfNeeded(doc, extendedTableSchemaMainEl, extendedTableSchemaStringIsEmpty); createExtendedTableSchemaFieldElementIfNeeded( doc, extendedTableSchemaMainEl, f.name(), extendedTableSchemaFieldEl); //create QDomElement extendedTableSchemaFieldPropertyEl = doc->createElement(QLatin1String("property")); extendedTableSchemaFieldEl->appendChild(extendedTableSchemaFieldPropertyEl); if (custom) extendedTableSchemaFieldPropertyEl.setAttribute(QLatin1String("custom"), QLatin1String("true")); extendedTableSchemaFieldPropertyEl.setAttribute(QLatin1String("name"), QLatin1String(propertyName)); QDomElement extendedTableSchemaFieldPropertyValueEl; switch (propertyValue.type()) { case QVariant::String: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("string")); break; case QVariant::ByteArray: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("cstring")); break; case QVariant::Int: case QVariant::Double: case QVariant::UInt: case QVariant::LongLong: case QVariant::ULongLong: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("number")); break; case QVariant::Bool: extendedTableSchemaFieldPropertyValueEl = doc->createElement(QLatin1String("bool")); break; default: //! @todo add more QVariant types kdbCritical() << "addFieldPropertyToExtendedTableSchemaData(): impl. error"; } extendedTableSchemaFieldPropertyEl.appendChild(extendedTableSchemaFieldPropertyValueEl); extendedTableSchemaFieldPropertyValueEl.appendChild( doc->createTextNode(propertyValue.toString())); } bool KDbConnection::storeExtendedTableSchemaData(KDbTableSchema* tableSchema) { //! @todo future: save in older versions if neeed QDomDocument doc(QLatin1String("EXTENDED_TABLE_SCHEMA")); QDomElement extendedTableSchemaMainEl; bool extendedTableSchemaStringIsEmpty = true; //for each field: foreach(KDbField* f, *tableSchema->fields()) { QDomElement extendedTableSchemaFieldEl; const KDbField::Type type = f->type(); // cache: evaluating type of expressions can be expensive if (f->visibleDecimalPlaces() >= 0/*nondefault*/ && KDb::supportsVisibleDecimalPlacesProperty(type)) { addFieldPropertyToExtendedTableSchemaData( *f, "visibleDecimalPlaces", f->visibleDecimalPlaces(), &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty); } if (type == KDbField::Text) { if (f->maxLengthStrategy() == KDbField::DefaultMaxLength) { addFieldPropertyToExtendedTableSchemaData( *f, "maxLengthIsDefault", true, &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty); } } // boolean field with "not null" // add custom properties const KDbField::CustomPropertiesMap customProperties(f->customProperties()); for (KDbField::CustomPropertiesMap::ConstIterator itCustom = customProperties.constBegin(); itCustom != customProperties.constEnd(); ++itCustom) { addFieldPropertyToExtendedTableSchemaData( *f, itCustom.key(), itCustom.value(), &doc, &extendedTableSchemaMainEl, &extendedTableSchemaFieldEl, &extendedTableSchemaStringIsEmpty, /*custom*/true); } // save lookup table specification, if present KDbLookupFieldSchema *lookupFieldSchema = tableSchema->lookupFieldSchema(*f); if (lookupFieldSchema) { createExtendedTableSchemaFieldElementIfNeeded( &doc, &extendedTableSchemaMainEl, f->name(), &extendedTableSchemaFieldEl, false/* !append */); lookupFieldSchema->saveToDom(&doc, &extendedTableSchemaFieldEl); if (extendedTableSchemaFieldEl.hasChildNodes()) { // this element provides the definition, so let's append it now createExtendedTableSchemaMainElementIfNeeded(&doc, &extendedTableSchemaMainEl, &extendedTableSchemaStringIsEmpty); extendedTableSchemaMainEl.appendChild(extendedTableSchemaFieldEl); } } } // Store extended schema information (see ExtendedTableSchemaInformation in Kexi Wiki) if (extendedTableSchemaStringIsEmpty) { #ifdef KDB_DEBUG_GUI KDb::alterTableActionDebugGUI(QLatin1String("** Extended table schema REMOVED.")); #endif if (!removeDataBlock(tableSchema->id(), QLatin1String("extended_schema"))) return false; } else { #ifdef KDB_DEBUG_GUI KDb::alterTableActionDebugGUI( QLatin1String("** Extended table schema set to:\n") + doc.toString(4)); #endif if (!storeDataBlock(tableSchema->id(), doc.toString(1), QLatin1String("extended_schema"))) return false; } return true; } bool KDbConnection::loadExtendedTableSchemaData(KDbTableSchema* tableSchema) { #define loadExtendedTableSchemaData_ERR \ { m_result = KDbResult(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } #define loadExtendedTableSchemaData_ERR2(details) \ { m_result = KDbResult(details); \ m_result.setMessageTitle(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } #define loadExtendedTableSchemaData_ERR3(data) \ { m_result = KDbResult(tr("Invalid XML data: %1").arg(data.left(1024))); \ m_result.setMessageTitle(tr("Error while loading extended table schema.", \ "Extended schema for a table: loading error")); \ return false; } // Load extended schema information, if present (see ExtendedTableSchemaInformation in Kexi Wiki) QString extendedTableSchemaString; tristate res = loadDataBlock(tableSchema->id(), &extendedTableSchemaString, QLatin1String("extended_schema")); if (!res) loadExtendedTableSchemaData_ERR; // extendedTableSchemaString will be just empty if there is no such data block if (extendedTableSchemaString.isEmpty()) return true; QDomDocument doc; QString errorMsg; int errorLine, errorColumn; if (!doc.setContent(extendedTableSchemaString, &errorMsg, &errorLine, &errorColumn)) { loadExtendedTableSchemaData_ERR2( tr("Error in XML data: \"%1\" in line %2, column %3.\nXML data: %4") .arg(errorMsg).arg(errorLine).arg(errorColumn).arg(extendedTableSchemaString.left(1024))); } //! @todo look at the current format version (KDB_EXTENDED_TABLE_SCHEMA_VERSION) if (doc.doctype().name() != QLatin1String("EXTENDED_TABLE_SCHEMA")) loadExtendedTableSchemaData_ERR3(extendedTableSchemaString); QDomElement docEl = doc.documentElement(); if (docEl.tagName() != QLatin1String("EXTENDED_TABLE_SCHEMA")) loadExtendedTableSchemaData_ERR3(extendedTableSchemaString); for (QDomNode n = docEl.firstChild(); !n.isNull(); n = n.nextSibling()) { QDomElement fieldEl = n.toElement(); if (fieldEl.tagName() == QLatin1String("field")) { KDbField *f = tableSchema->field(fieldEl.attribute(QLatin1String("name"))); if (f) { //set properties of the field: //! @todo more properties for (QDomNode propNode = fieldEl.firstChild(); !propNode.isNull(); propNode = propNode.nextSibling()) { const QDomElement propEl = propNode.toElement(); bool ok; int intValue; if (propEl.tagName() == QLatin1String("property")) { QByteArray propertyName = propEl.attribute(QLatin1String("name")).toLatin1(); if (propEl.attribute(QLatin1String("custom")) == QLatin1String("true")) { //custom property const QVariant v(KDb::loadPropertyValueFromDom(propEl.firstChild(), &ok)); if (ok) { f->setCustomProperty(propertyName, v); } } else if (propertyName == "visibleDecimalPlaces") { if (KDb::supportsVisibleDecimalPlacesProperty(f->type())) { intValue = KDb::loadIntPropertyValueFromDom(propEl.firstChild(), &ok); if (ok) f->setVisibleDecimalPlaces(intValue); } } else if (propertyName == "maxLengthIsDefault") { if (f->type() == KDbField::Text) { const bool maxLengthIsDefault = KDb::loadPropertyValueFromDom(propEl.firstChild(), &ok).toBool(); if (ok) { f->setMaxLengthStrategy( maxLengthIsDefault ? KDbField::DefaultMaxLength : KDbField::DefinedMaxLength); } } } //! @todo more properties... } else if (propEl.tagName() == QLatin1String("lookup-column")) { KDbLookupFieldSchema *lookupFieldSchema = KDbLookupFieldSchema::loadFromDom(propEl); if (lookupFieldSchema) { kdbDebug() << f->name() << *lookupFieldSchema; tableSchema->setLookupFieldSchema(f->name(), lookupFieldSchema); } } } } else { kdbWarning() << "no such field:" << fieldEl.attribute(QLatin1String("name")) << "in table:" << tableSchema->name(); } } } return true; } KDbField* KDbConnection::setupField(const KDbRecordData &data) { bool ok = true; int f_int_type = data.at(1).toInt(&ok); if (f_int_type <= KDbField::InvalidType || f_int_type > KDbField::LastType) ok = false; if (!ok) return nullptr; KDbField::Type f_type = (KDbField::Type)f_int_type; const int f_len = qMax(0, data.at(3).toInt(&ok)); // defined limit if (!ok) { return nullptr; } //! @todo load maxLengthStrategy info to see if the maxLength is the default int f_prec = data.at(4).toInt(&ok); if (!ok) return nullptr; KDbField::Constraints f_constr = (KDbField::Constraints)data.at(5).toInt(&ok); if (!ok) return nullptr; KDbField::Options f_opts = (KDbField::Options)data.at(6).toInt(&ok); if (!ok) return nullptr; QString name(data.at(2).toString()); if (!KDb::isIdentifier(name)) { name = KDb::stringToIdentifier(name); } KDbField *f = new KDbField( name, f_type, f_constr, f_opts, f_len, f_prec); QVariant defaultVariant = data.at(7); if (defaultVariant.isValid()) { defaultVariant = KDb::stringToVariant(defaultVariant.toString(), KDbField::variantType(f_type), &ok); if (ok) { f->setDefaultValue(defaultVariant); } else { kdbWarning() << "problem with KDb::stringToVariant(" << defaultVariant << ')'; ok = true; //problem with defaultValue is not critical } } f->setCaption(data.at(9).toString()); f->setDescription(data.at(10).toString()); return f; } KDbTableSchema* KDbConnection::tableSchema(const QString& tableName) { KDbTableSchema *t = d->table(tableName); if (t) return t; //not found: retrieve schema QScopedPointer newTable(new KDbTableSchema); clearResult(); if (true != loadObjectData(KDb::TableObjectType, tableName, newTable.data())) { return nullptr; } return d->setupTableSchema(newTable.take()); } KDbTableSchema* KDbConnection::tableSchema(int tableId) { KDbTableSchema *t = d->table(tableId); if (t) return t; //not found: retrieve schema QScopedPointer newTable(new KDbTableSchema); clearResult(); if (true != loadObjectData(KDb::TableObjectType, tableId, newTable.data())) { return nullptr; } return d->setupTableSchema(newTable.take()); } tristate KDbConnection::loadDataBlock(int objectID, QString* dataString, const QString& dataID) { if (objectID <= 0) return false; return querySingleString( KDbEscapedString("SELECT o_data FROM kexi__objectdata WHERE o_id=%1 AND ") .arg(d->driver->valueToSql(KDbField::Integer, objectID)) + KDbEscapedString(KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID.isEmpty() ? QVariant() : QVariant(dataID))), dataString); } bool KDbConnection::storeDataBlock(int objectID, const QString &dataString, const QString& dataID) { if (objectID <= 0) return false; KDbEscapedString sql( KDbEscapedString("SELECT kexi__objectdata.o_id FROM kexi__objectdata WHERE o_id=%1") .arg(d->driver->valueToSql(KDbField::Integer, objectID))); KDbEscapedString sql_sub(KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID.isEmpty() ? QVariant() : QVariant(dataID))); const tristate result = resultExists(sql + " AND " + sql_sub); if (~result) { return false; } if (result == true) { return executeSql(KDbEscapedString("UPDATE kexi__objectdata SET o_data=%1 WHERE o_id=%2 AND ") .arg(d->driver->valueToSql(KDbField::LongText, dataString)) .arg(d->driver->valueToSql(KDbField::Integer, objectID)) + sql_sub); } return executeSql( KDbEscapedString("INSERT INTO kexi__objectdata (o_id, o_data, o_sub_id) VALUES (") + KDbEscapedString::number(objectID) + ',' + d->driver->valueToSql(KDbField::LongText, dataString) + ',' + d->driver->valueToSql(KDbField::Text, dataID) + ')'); } bool KDbConnection::copyDataBlock(int sourceObjectID, int destObjectID, const QString &dataID) { if (sourceObjectID <= 0 || destObjectID <= 0) return false; if (sourceObjectID == destObjectID) return true; if (!removeDataBlock(destObjectID, dataID)) // remove before copying return false; KDbEscapedString sql = KDbEscapedString( "INSERT INTO kexi__objectdata SELECT %1, t.o_data, t.o_sub_id " "FROM kexi__objectdata AS t WHERE o_id=%2") .arg(d->driver->valueToSql(KDbField::Integer, destObjectID)) .arg(d->driver->valueToSql(KDbField::Integer, sourceObjectID)); if (!dataID.isEmpty()) { sql += KDbEscapedString(" AND ") + KDb::sqlWhere(d->driver, KDbField::Text, QLatin1String("o_sub_id"), dataID); } return executeSql(sql); } bool KDbConnection::removeDataBlock(int objectID, const QString& dataID) { if (objectID <= 0) return false; if (dataID.isEmpty()) return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), QString::number(objectID)); else return KDb::deleteRecords(this, QLatin1String("kexi__objectdata"), QLatin1String("o_id"), KDbField::Integer, objectID, QLatin1String("o_sub_id"), KDbField::Text, dataID); } KDbQuerySchema* KDbConnection::querySchema(const QString& aQueryName) { QString queryName = aQueryName.toLower(); KDbQuerySchema *q = d->query(queryName); if (q) return q; //not found: retrieve schema - QScopedPointer newQuery(KDbQuerySchema::Private::createQuery(this)); + QScopedPointer newQuery(new KDbQuerySchema); clearResult(); if (true != loadObjectData(KDb::QueryObjectType, aQueryName, newQuery.data())) { return nullptr; } return d->setupQuerySchema(newQuery.take()); } KDbQuerySchema* KDbConnection::querySchema(int queryId) { KDbQuerySchema *q = d->query(queryId); if (q) return q; //not found: retrieve schema - QScopedPointer newQuery(KDbQuerySchema::Private::createQuery(this)); + QScopedPointer newQuery(new KDbQuerySchema); clearResult(); if (true != loadObjectData(KDb::QueryObjectType, queryId, newQuery.data())) { return nullptr; } return d->setupQuerySchema(newQuery.take()); } bool KDbConnection::setQuerySchemaObsolete(const QString& queryName) { KDbQuerySchema* oldQuery = querySchema(queryName); if (!oldQuery) return false; d->setQueryObsolete(oldQuery); return true; } QString KDbConnection::escapeIdentifier(const QString& id) const { return d->driver->escapeIdentifier(id); } bool KDbConnection::isInternalTableSchema(const QString& tableName) { KDbTableSchema* schema = d->table(tableName); return (schema && schema->isInternal()) // these are here for compatiblility because we're no longer instantiate // them but can exist in projects created with previous Kexi versions: || tableName == QLatin1String("kexi__final") || tableName == QLatin1String("kexi__useractions"); } void KDbConnection::removeMe(KDbTableSchema *table) { if (table && d) { d->takeTable(table); } } QString KDbConnection::anyAvailableDatabaseName() { if (!d->availableDatabaseName.isEmpty()) { return d->availableDatabaseName; } return d->driver->behavior()->ALWAYS_AVAILABLE_DATABASE_NAME; } void KDbConnection::setAvailableDatabaseName(const QString& dbName) { d->availableDatabaseName = dbName; } //! @internal used in updateRecord(), insertRecord(), -inline static void updateRecordDataWithNewValues(KDbQuerySchema* query, KDbRecordData* data, - const KDbRecordEditBuffer::DbHash& b, - QHash* columnsOrderExpanded) +inline static void updateRecordDataWithNewValues( + KDbConnection *conn, KDbQuerySchema* query, KDbRecordData* data, + const KDbRecordEditBuffer::DbHash& b, + QHash* columnsOrderExpanded) { - *columnsOrderExpanded = query->columnsOrder(KDbQuerySchema::ExpandedList); + *columnsOrderExpanded + = query->columnsOrder(conn, KDbQuerySchema::ColumnsOrderMode::ExpandedList); QHash::ConstIterator columnsOrderExpandedIt; for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { columnsOrderExpandedIt = columnsOrderExpanded->constFind(it.key()); if (columnsOrderExpandedIt == columnsOrderExpanded->constEnd()) { kdbWarning() << "(KDbConnection) \"now also assign new value in memory\" step" "- could not find item" << it.key()->aliasOrName(); continue; } (*data)[ columnsOrderExpandedIt.value() ] = it.value(); } } bool KDbConnection::updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { // Each SQL identifier needs to be escaped in the generated query. // kdbDebug() << *query; clearResult(); //--get PKEY if (buf->dbBuffer().isEmpty()) { kdbDebug() << " -- NO CHANGES DATA!"; return true; } KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_UPDATE_NO_MASTER_TABLE, tr("Could not update record because there is no master table defined.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; if (!useRecordId && !pkey) { kdbWarning() << " -- NO MASTER TABLE's PKEY!"; m_result = KDbResult(ERR_UPDATE_NO_MASTER_TABLES_PKEY, tr("Could not update record because master table has no primary key defined.")); //! @todo perhaps we can try to update without using PKEY? return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("UPDATE ") + escapeIdentifier(mt->name()) + " SET "; KDbEscapedString sqlset, sqlwhere; sqlset.reserve(1024); sqlwhere.reserve(1024); KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); //gather the fields which are updated ( have values in KDbRecordEditBuffer) KDbFieldList affectedFields; for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { if (it.key()->field()->table() != mt) continue; // skip values for fields outside of the master table (e.g. a "visible value" of the lookup field) if (!sqlset.isEmpty()) sqlset += ','; KDbField* currentField = it.key()->field(); const bool affectedFieldsAddOk = affectedFields.addField(currentField); Q_ASSERT(affectedFieldsAddOk); sqlset += KDbEscapedString(escapeIdentifier(currentField->name())) + '=' + d->driver->valueToSql(currentField, it.value()); } if (pkey) { - const QVector pkeyFieldsOrder(query->pkeyFieldsOrder()); + const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); - if (pkey->fieldCount() != query->pkeyFieldCount()) { //sanity check + if (pkey->fieldCount() != query->pkeyFieldCount(this)) { //sanity check kdbWarning() << " -- NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_UPDATE_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not update record because it does not contain entire primary key of master table.")); return false; } if (!pkey->fields()->isEmpty()) { int i = 0; foreach(KDbField *f, *pkey->fields()) { if (!sqlwhere.isEmpty()) sqlwhere += " AND "; QVariant val(data->at(pkeyFieldsOrder.at(i))); if (val.isNull() || !val.isValid()) { m_result = KDbResult(ERR_UPDATE_NULL_PKEY_FIELD, tr("Primary key's field \"%1\" cannot be empty.").arg(f->name())); //js todo: pass the field's name somewhere! return false; } sqlwhere += KDbEscapedString(escapeIdentifier(f->name())) + '=' + d->driver->valueToSql(f, val); i++; } } } else { //use RecordId sqlwhere = KDbEscapedString(escapeIdentifier(d->driver->behavior()->ROW_ID_FIELD_NAME)) + '=' + d->driver->valueToSql(KDbField::BigInteger, (*data)[data->size() - 1]); } sql += (sqlset + " WHERE " + sqlwhere); //kdbDebug() << " -- SQL == " << ((sql.length() > 400) ? (sql.left(400) + "[.....]") : sql); // preprocessing before update if (!drv_beforeUpdate(mt->name(), &affectedFields)) return false; bool res = executeSql(sql); // postprocessing after update if (!drv_afterUpdate(mt->name(), &affectedFields)) return false; if (!res) { m_result = KDbResult(ERR_UPDATE_SERVER_ERROR, tr("Record updating on the server failed.")); return false; } //success: now also assign new values in memory: QHash columnsOrderExpanded; - updateRecordDataWithNewValues(query, data, b, &columnsOrderExpanded); + updateRecordDataWithNewValues(this, query, data, b, &columnsOrderExpanded); return true; } bool KDbConnection::insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); //--get PKEY /*disabled: there may be empty records (with autoinc) if (buf.dbBuffer().isEmpty()) { kdbDebug() << " -- NO CHANGES DATA!"; return true; }*/ KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_INSERT_NO_MASTER_TABLE, tr("Could not insert record because there is no master table specified.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; if (!getRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sqlcols, sqlvals; sqlcols.reserve(1024); sqlvals.reserve(1024); //insert the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("INSERT INTO ") + escapeIdentifier(mt->name()) + " ("; KDbRecordEditBuffer::DbHash b = buf->dbBuffer(); // add default values, if available (for any column without value explicitly set) - const KDbQueryColumnInfo::Vector fieldsExpanded(query->fieldsExpanded(KDbQuerySchema::Unique)); + const KDbQueryColumnInfo::Vector fieldsExpanded( + query->fieldsExpanded(this, KDbQuerySchema::FieldsExpandedMode::Unique)); int fieldsExpandedCount = fieldsExpanded.count(); for (int i = 0; i < fieldsExpandedCount; i++) { KDbQueryColumnInfo *ci = fieldsExpanded.at(i); if (ci->field() && KDb::isDefaultValueAllowed(*ci->field()) && !ci->field()->defaultValue().isNull() && !b.contains(ci)) { //kdbDebug() << "adding default value" << ci->field->defaultValue().toString() << "for column" << ci->field->name(); b.insert(ci, ci->field()->defaultValue()); } } //collect fields which have values in KDbRecordEditBuffer KDbFieldList affectedFields; if (b.isEmpty()) { // empty record inserting requested: if (!getRecordId && !pkey) { kdbWarning() << "MASTER TABLE's PKEY REQUIRED FOR INSERTING EMPTY RECORDS: INSERT CANCELLED"; m_result = KDbResult(ERR_INSERT_NO_MASTER_TABLES_PKEY, tr("Could not insert record because master table has no primary key specified.")); return false; } if (pkey) { - const QVector pkeyFieldsOrder(query->pkeyFieldsOrder()); + const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); // kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); - if (pkey->fieldCount() != query->pkeyFieldCount()) { // sanity check + if (pkey->fieldCount() != query->pkeyFieldCount(this)) { // sanity check kdbWarning() << "NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_INSERT_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not insert record because it does not contain " "entire master table's primary key.")); return false; } } //at least one value is needed for VALUES section: find it and set to NULL: KDbField *anyField = mt->anyNonPKField(); if (!anyField) { if (!pkey) { kdbWarning() << "WARNING: NO FIELD AVAILABLE TO SET IT TO NULL"; return false; } else { //try to set NULL in pkey field (could not work for every SQL engine!) anyField = pkey->fields()->first(); } } sqlcols += escapeIdentifier(anyField->name()); sqlvals += d->driver->valueToSql(anyField, QVariant()/*NULL*/); const bool affectedFieldsAddOk = affectedFields.addField(anyField); Q_ASSERT(affectedFieldsAddOk); } else { // non-empty record inserting requested: for (KDbRecordEditBuffer::DbHash::ConstIterator it = b.constBegin();it != b.constEnd();++it) { if (it.key()->field()->table() != mt) continue; // skip values for fields outside of the master table (e.g. a "visible value" of the lookup field) if (!sqlcols.isEmpty()) { sqlcols += ','; sqlvals += ','; } KDbField* currentField = it.key()->field(); const bool affectedFieldsAddOk = affectedFields.addField(currentField); Q_ASSERT(affectedFieldsAddOk); sqlcols += escapeIdentifier(currentField->name()); sqlvals += d->driver->valueToSql(currentField, it.value()); } } sql += (sqlcols + ") VALUES (" + sqlvals + ')'); // kdbDebug() << " -- SQL == " << sql; // low-level insert QSharedPointer result = insertRecordInternal(mt->name(), &affectedFields, sql); if (!result) { m_result = KDbResult(ERR_INSERT_SERVER_ERROR, tr("Record inserting on the server failed.")); return false; } //success: now also assign a new value in memory: QHash columnsOrderExpanded; - updateRecordDataWithNewValues(query, data, b, &columnsOrderExpanded); + updateRecordDataWithNewValues(this, query, data, b, &columnsOrderExpanded); //fetch autoincremented values - KDbQueryColumnInfo::List *aif_list = query->autoIncrementFields(); + KDbQueryColumnInfo::List *aif_list = query->autoIncrementFields(this); quint64 recordId = 0; if (pkey && !aif_list->isEmpty()) { //! @todo now only if PKEY is present, this should also work when there's no PKEY KDbQueryColumnInfo *id_columnInfo = aif_list->first(); //! @todo safe to cast it? quint64 last_id = KDb::lastInsertedAutoIncValue(result, id_columnInfo->field()->name(), id_columnInfo->field()->table()->name(), &recordId); if (last_id == std::numeric_limits::max()) { //! @todo show error //! @todo remove just inserted record. How? Using ROLLBACK? return false; } KDbRecordData aif_data; KDbEscapedString getAutoIncForInsertedValue("SELECT " + query->autoIncrementSqlFieldsList(this) + " FROM " + escapeIdentifier(id_columnInfo->field()->table()->name()) + " WHERE " + escapeIdentifier(id_columnInfo->field()->name()) + '=' + QByteArray::number(last_id)); if (true != querySingleRecord(getAutoIncForInsertedValue, &aif_data)) { //! @todo show error return false; } int i = 0; foreach(KDbQueryColumnInfo *ci, *aif_list) { // kdbDebug() << "AUTOINCREMENTED FIELD" << fi->field->name() << "==" << aif_data[i].toInt(); ((*data)[ columnsOrderExpanded.value(ci)] = aif_data.value(i)).convert(ci->field()->variantType()); //cast to get proper type i++; } } else { recordId = result->lastInsertRecordId(); // kdbDebug() << "new recordId ==" << recordId; if (d->driver->behavior()->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE) { kdbWarning() << "d->driver->behavior()->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE"; return false; } } if (getRecordId && /*sanity check*/data->size() > fieldsExpanded.size()) { // kdbDebug() << "new ROWID ==" << ROWID; (*data)[data->size() - 1] = recordId; } return true; } bool KDbConnection::deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId) { // Each SQL identifier needs to be escaped in the generated query. clearResult(); KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; m_result = KDbResult(ERR_DELETE_NO_MASTER_TABLE, tr("Could not delete record because there is no master table specified.")); return false; } KDbIndexSchema *pkey = (mt->primaryKey() && !mt->primaryKey()->fields()->isEmpty()) ? mt->primaryKey() : nullptr; //! @todo allow to delete from a table without pkey if (!useRecordId && !pkey) { kdbWarning() << " -- WARNING: NO MASTER TABLE's PKEY"; m_result = KDbResult(ERR_DELETE_NO_MASTER_TABLES_PKEY, tr("Could not delete record because there is no primary key for master table specified.")); return false; } //update the record: KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()) + " WHERE "; KDbEscapedString sqlwhere; sqlwhere.reserve(1024); if (pkey) { - const QVector pkeyFieldsOrder(query->pkeyFieldsOrder()); + const QVector pkeyFieldsOrder(query->pkeyFieldsOrder(this)); //kdbDebug() << pkey->fieldCount() << " ? " << query->pkeyFieldCount(); - if (pkey->fieldCount() != query->pkeyFieldCount()) { //sanity check + if (pkey->fieldCount() != query->pkeyFieldCount(this)) { //sanity check kdbWarning() << " -- NO ENTIRE MASTER TABLE's PKEY SPECIFIED!"; m_result = KDbResult(ERR_DELETE_NO_ENTIRE_MASTER_TABLES_PKEY, tr("Could not delete record because it does not contain entire master table's primary key.")); return false; } int i = 0; foreach(KDbField *f, *pkey->fields()) { if (!sqlwhere.isEmpty()) sqlwhere += " AND "; QVariant val(data->at(pkeyFieldsOrder.at(i))); if (val.isNull() || !val.isValid()) { m_result = KDbResult(ERR_DELETE_NULL_PKEY_FIELD, tr("Primary key's field \"%1\" cannot be empty.").arg(f->name())); //js todo: pass the field's name somewhere! return false; } sqlwhere += KDbEscapedString(escapeIdentifier(f->name())) + '=' + d->driver->valueToSql(f, val); i++; } } else {//use RecordId sqlwhere = KDbEscapedString(escapeIdentifier(d->driver->behavior()->ROW_ID_FIELD_NAME)) + '=' + d->driver->valueToSql(KDbField::BigInteger, (*data)[data->size() - 1]); } sql += sqlwhere; //kdbDebug() << " -- SQL == " << sql; if (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } bool KDbConnection::deleteAllRecords(KDbQuerySchema* query) { clearResult(); KDbTableSchema *mt = query->masterTable(); if (!mt) { kdbWarning() << " -- NO MASTER TABLE!"; return false; } KDbIndexSchema *pkey = mt->primaryKey(); if (!pkey || pkey->fields()->isEmpty()) { kdbWarning() << "-- WARNING: NO MASTER TABLE's PKEY"; } KDbEscapedString sql = KDbEscapedString("DELETE FROM ") + escapeIdentifier(mt->name()); //kdbDebug() << "-- SQL == " << sql; if (!executeSql(sql)) { m_result = KDbResult(ERR_DELETE_SERVER_ERROR, tr("Record deletion on the server failed.")); return false; } return true; } +int KDbConnection::recordCount(const KDbEscapedString& sql) +{ + int count = -1; //will be changed only on success of querySingleNumber() + const tristate result = querySingleNumber( + KDbEscapedString("SELECT COUNT() FROM (") + sql + ") AS kdb__subquery", &count); + if (~result) { + count = 0; + } + return count; +} + +int KDbConnection::recordCount(const KDbTableSchema& tableSchema) +{ + //! @todo does not work with non-SQL data sources + int count = -1; // will be changed only on success of querySingleNumber() + const tristate result + = querySingleNumber(KDbEscapedString("SELECT COUNT(*) FROM ") + + tableSchema.connection()->escapeIdentifier(tableSchema.name()), + &count); + if (~result) { + count = 0; + } + return count; +} + +int KDbConnection::recordCount(KDbQuerySchema* querySchema, const QList& params) +{ +//! @todo does not work with non-SQL data sources + int count = -1; //will be changed only on success of querySingleNumber() + KDbNativeStatementBuilder builder(this); + KDbEscapedString subSql; + if (!builder.generateSelectStatement(&subSql, querySchema, params)) { + return -1; + } + const tristate result = querySingleNumber( + KDbEscapedString("SELECT COUNT(*) FROM (") + subSql + ") AS kdb__subquery", &count); + if (~result) { + count = 0; + } + return count; +} + +int KDbConnection::recordCount(KDbTableOrQuerySchema* tableOrQuery, const QList& params) +{ + if (tableOrQuery) { + if (tableOrQuery->table()) + return recordCount(*tableOrQuery->table()); + if (tableOrQuery->query()) + return recordCount(tableOrQuery->query(), params); + } + return -1; +} + KDbConnectionOptions* KDbConnection::options() { return &d->options; } void KDbConnection::addCursor(KDbCursor* cursor) { d->cursors.insert(cursor); } void KDbConnection::takeCursor(KDbCursor* cursor) { if (d && !d->cursors.isEmpty()) { // checking because this may be called from ~KDbConnection() d->cursors.remove(cursor); } } KDbPreparedStatement KDbConnection::prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames) { //! @todo move to ConnectionInterface just like we moved execute() and prepare() to KDbPreparedStatementInterface... KDbPreparedStatementInterface *iface = prepareStatementInternal(); if (!iface) return KDbPreparedStatement(); return KDbPreparedStatement(iface, type, fields, whereFieldNames); } KDbEscapedString KDbConnection::recentSqlString() const { return result().errorSql().isEmpty() ? m_result.sql() : result().errorSql(); } KDbEscapedString KDbConnection::escapeString(const QString& str) const { return d->driver->escapeString(str); } //! @todo extraMessages #if 0 static const char *extraMessages[] = { QT_TRANSLATE_NOOP("KDbConnection", "Unknown error.") }; #endif diff --git a/src/KDbConnection.h b/src/KDbConnection.h index 17ab7ebb..15c20ae5 100644 --- a/src/KDbConnection.h +++ b/src/KDbConnection.h @@ -1,1357 +1,1419 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTION_H #define KDB_CONNECTION_H #include "KDbCursor.h" #include "KDbDriver.h" #include "KDbPreparedStatement.h" #include "KDbTableSchema.h" #include "KDbTransaction.h" #include "KDbTristate.h" class KDbConnectionData; class KDbConnectionOptions; class KDbConnectionPrivate; class KDbConnectionProxy; class KDbDriver; class KDbProperties; class KDbRecordData; class KDbRecordEditBuffer; class KDbServerVersionInfo; class KDbSqlResult; class KDbTableSchemaChangeListener; class KDbTransactionGuard; class KDbVersionInfo; /*! @short Provides database connection, allowing queries and data modification. This class represents a database connection established within a data source. It supports data queries and modification by creating client-side database cursors. Database transactions are supported. */ class KDB_EXPORT KDbConnection : public KDbResultable { Q_DECLARE_TR_FUNCTIONS(KDbConnection) public: /*! Opened connection is automatically disconnected and removed from driver's connections list. Note for driver developers: you should call destroy() from you KDbConnection's subclass destructor. */ ~KDbConnection() override; /*! @return parameters that were used to create this connection. */ KDbConnectionData data() const; /*! @return the driver used for this connection. */ KDbDriver* driver() const; /*! @brief Connects to driver with given parameters. @return true if successful. Note: many database drivers may require connData.databaseName() to be specified because explicit database name is needed to perform connection (e.g. SQLite, PostgreSQL). MySQL does not require database name; KDbConnection::useDatabase() can be called later. */ bool connect(); /*! @return true, if connection is properly established. */ bool isConnected() const; /*! @return true, both if connection is properly established and any database within this connection is properly used with useDatabase(). */ bool isDatabaseUsed() const; /*! @return generic options for a single connection. The options are accessible using key/value pairs. This enables extensibility depending on driver's type and version. */ KDbConnectionOptions *options(); /*! Reimplemented, also clears sql string. @sa recentSqlString() */ void clearResult(); /*! @brief Disconnects from driver with given parameters. The database (if used) is closed, and any active transactions (if supported) are rolled back, so commit these before disconnecting, if you'd like to save your changes. */ bool disconnect(); /*! @return list of database names for opened connection. If @a also_system_db is true, the system database names are also returned. */ QStringList databaseNames(bool also_system_db = false); /*! @return true if database @a dbName exists. If @a ignoreErrors is true, error flag of connection won't be modified for any errors (it will quietly return), else (ignoreErrors == false) we can check why the database does not exist using error(), errorNum() and/or errorMsg(). */ bool databaseExists(const QString &dbName, bool ignoreErrors = true); /*! @brief Creates new database with name @a dbName, using this connection. If database with @a dbName already exists, or other error occurred, false is returned. For file-based drivers, @a dbName should be equal to the database filename (the same as specified for KDbConnectionData). See docs/kdb_issues.txt document, chapter "Table schema, query schema, etc. storage" for database schema documentation (detailed description of kexi__* 'system' tables). @see useDatabase() */ bool createDatabase(const QString &dbName); /*! @brief Opens an existing database specified by @a dbName. If @a kexiCompatible is true (the default) initial checks will be performed to recognize database Kexi-specific format. Set @a kexiCompatible to false if you're using native database (one that have no Kexi System tables). For file-based drivers, @a dbName can be skipped, so the same as specified for KDbConnectionData is used. @return true on success, false on failure. If user has cancelled this action and @a cancelled is not 0, *cancelled is set to true. */ bool useDatabase(const QString &dbName = QString(), bool kexiCompatible = true, bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr); /*! @brief Closes currently used database for this connection. Any active transactions (if supported) are rolled back, so commit these before closing, if you'd like to save your changes. */ bool closeDatabase(); /*! @brief Get the name of the current database @return name of currently used database for this connection or empty string if there is no used database */ QString currentDatabase() const; /*! @brief Drops database with name @a dbName. if dbName is not specified, currently used database name is used (it is closed before dropping). */ bool dropDatabase(const QString &dbName = QString()); /*! @return names of all the @a objectType (see @a ObjectType in KDbGlobal.h) schemas stored in currently used database. KDb::AnyObjectType can be passed as @a objectType to get names of objects of any type. The list ordered is based on object identifiers. Only names that are identifiers (checked using KDb::isIdentifier()) are returned. If @a ok is not 0 then variable pointed by it will be set to the result. On error, the function returns empty list. @see kdbSystemTableNames() tableNames(int,bool*) */ QStringList objectNames(int objectType = KDb::AnyObjectType, bool* ok = nullptr); /*! @return names of all table schemas stored in currently used database. If @a alsoSystemTables is true, internal KDb system table names (kexi__*) are also returned. The list ordered is based on object identifiers. Only names that are identifiers (checked using KDb::isIdentifier()) are returned. If @a ok is not 0 then variable pointed by it will be set to the result. On error, the function returns empty list. @see kdbSystemTableNames() objectNames(int,bool*) */ QStringList tableNames(bool alsoSystemTables = false, bool* ok = nullptr); /*! @return true if table with name @a tableName exists in the database. @return @c false if it does not exist or @c cancelled if error occurred. The lookup is case insensitive. This method can be much faster than tableNames(). */ tristate containsTable(const QString &tableName); /*! @return list of internal KDb system table names (kexi__*). This does not mean that these tables can be found in currently opened database. Just static list of table names is returned. The list contents may depend on KDb library version; opened database can contain fewer 'system' tables than in current KDb implementation, if the current one is newer than the one used to build the database. @todo this will depend on KDb lib version */ static QStringList kdbSystemTableNames(); /*! @return server version information for this connection. If database is not connected (i.e. isConnected() is false) null KDbServerVersionInfo is returned. */ KDbServerVersionInfo serverVersion() const; /*! @return version information for this connection. If database is not used (i.e. isDatabaseUsed() is false) null KDbVersionInfo is returned. It can be compared to drivers' and KDb library version to maintain backward/upward compatiblility. */ KDbVersionInfo databaseVersion() const; /*! @return KDbProperties object allowing to read and write global database properties for this connection. */ KDbProperties databaseProperties() const; /*! @return ids of all table schema names stored in currently used database. These ids can be later used as argument for tableSchema(). This is a shortcut for objectIds(KDb::TableObjectType). Internal KDb system tables (kexi__*) are not available here because these have no identifiers assigned (more formally: id=-1). If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that tableSchema( id ) returns anything. The table definition can be broken, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see queryIds() */ QList tableIds(bool* ok = nullptr); /*! @return ids of all database query schemas stored in currently used database. These ids can be later used as argument for querySchema(). This is a shortcut for objectIds(KDb::QueryObjectType). If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that querySchema( id ) returns anything. The query definition can be broken, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see tableIds() */ QList queryIds(bool* ok = nullptr); /*! @return names of all schemas of object with @a objectType type that are stored in currently used database. If @a ok is not 0 then variable pointed by it will be set to the result. @note The fact that given id is on the returned list does not mean that the definition of the object is valid, so you have to double check this. Only IDs of objects with names that are identifiers (checked using KDb::isIdentifier()) are returned. @see tableIds() queryIds() */ QList objectIds(int objectType, bool* ok = nullptr); /** * @brief Starts a new database transaction * * @return KDbTransaction object. If transaction has been started successfully returned object * points to it, otherwise null transaction is returned. * * For drivers that allow single transaction per connection * (KDbDriver::features() && SingleTransactions) this method can be called once and that * transaction will be default one (setDefaultTransaction() will be called). * For drivers that allow multiple transactions per connection no default transaction is * set automatically in beginTransaction(). setDefaultTransaction() can be called by hand. * * @see setDefaultTransaction(), defaultTransaction(). */ KDbTransaction beginTransaction(); /** * @brief Commits specified transaction for this connection * * If @a transaction is not active and default transaction (obtained from defaultTransaction()) * exists, the default one will be committed. If neither the default one is not present returns * @c true if IgnoreInactive is set in @a options or @c false if IgnoreInactive is not set in * @a options. * * @return @c false on any error. * * On successful commit, @a transaction object will point to a null transaction. * After commiting a default transaction, there is no default transaction anymore. */ bool commitTransaction(KDbTransaction transaction = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); /** * @brief Rolls back specified transaction for this connection * * If @a transaction is not active and default transaction (obtained from defaultTransaction()) * exists, the default one will be rolled back. If neither default one is present @c true is * returned if IgnoreInactive is set for @a options or @c false if IgnoreInactive is not set in * @a options. * * @return @c false on any error. * * On successful rollback, @a transaction object will point to a null transaction. * After rollong back a default transaction, there is no default transaction anymore. */ bool rollbackTransaction(KDbTransaction trans = KDbTransaction(), KDbTransaction::CommitOptions options = KDbTransaction::CommitOptions()); /** * @brief Returns handle of default transaction for this connection * * Null transaction is returned if there is no such a transaction declared. * If transactions are supported any operation on database (e.g. inserts) that are started * without specifying a transaction context, are be performed in the context of this transaction. * Returned null transaction doesn't mean that there are no transactions started at all. * Default transaction can be defined automatically for certain drivers, see beginTransaction(). * * @see KDbDriver::transactionsSupported() */ KDbTransaction defaultTransaction() const; /** * @brief Sets default transaction * * Default transaction is used as a context for data modifications for this connection when no * specific transaction is provided. */ void setDefaultTransaction(const KDbTransaction& trans); /** * @brief Returns set of handles of currently active transactions * * @note In multithreading environment some of these transactions can be already inactive after * calling this method. Use KDbTransaction::isActive() to check that. Inactive transaction * handle is useless and can be safely ignored. */ QList transactions(); /*! @return true if "auto commit" option is on. When auto commit is on (the default on for any new KDbConnection object), every SQL statement that manipulates data in the database implicitly starts a new transaction. This transaction is automatically committed after successful statement execution or rolled back on error. For drivers that do not support transactions (see KDbDriver::features()) this method shouldn't be called because it does nothing ans always returns false. No internal KDb object should changes this option, although auto commit's behavior depends on database engine's specifics. Engines that support only single transaction per connection (see KDbDriver::SingleTransactions), use this single connection for autocommiting, so if there is already transaction started by the KDb user program (with beginTransaction()), this transaction is committed before any statement that manipulates data. In this situation default transaction is also affected (see defaultTransaction()). Only for drivers that support nested transactions (KDbDriver::NestedTransactions), autocommiting works independently from previously started transaction, For other drivers set this option off if you need use transaction for grouping more statements together. NOTE: nested transactions are not yet implemented in KDb API. */ bool autoCommit() const; /*! Changes auto commit option. This does not affect currently started transactions. This option can be changed even when connection is not established. @see autoCommit() */ bool setAutoCommit(bool on); /*! Connection-specific string escaping. Default implementation uses driver's escaping. Use KDbEscapedString::isValid() to check if escaping has been performed successfully. Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true, not just isEmpty(). */ virtual KDbEscapedString escapeString(const QString& str) const; /*! Prepares SELECT query described by a raw statement @a sql. @return opened cursor created for results of this query or @c nullptr if there was any error. Ownership of the returned object is passed to the caller. KDbCursor can have optionally applied @a options (one of more selected from KDbCursor::Options). Preparation means that returned cursor is created but not opened. Open this when you would like to do it with KDbCursor::open(). Note for driver developers: you should initialize cursor engine-specific resources and return KDbCursor subclass' object (passing @a sql and @a options to its constructor). */ virtual KDbCursor* prepareQuery(const KDbEscapedString& sql, KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0; /*! @overload Prepares query described by @a query schema. @a params are values of parameters that will be inserted into places marked with [] before execution of the query. Note for driver developers: you should initialize cursor engine-specific resources and return KDbCursor subclass' object (passing @a query and @a options to it's constructor). Kexi SQL and driver-specific escaping is performed on table names. */ KDbCursor* prepareQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! @overload Prepares query described by @a query schema without parameters. */ virtual KDbCursor* prepareQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None) /*Q_REQUIRED_RESULT*/ = 0; /*! @overload Statement is build from data provided by @a table schema, it is like "select * from table_name".*/ KDbCursor* prepareQuery(KDbTableSchema* table, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! Executes SELECT query described by a raw SQL statement @a sql. @return opened cursor created for results of this query or 0 if there was any error on the cursor creation or opening. Ownership of the returned object is passed to the caller. KDbCursor can have optionally applied @a options. Identifiers in @a sql that are the same as keywords in KDbSQL dialect or the backend's SQL have to be escaped. */ KDbCursor* executeQuery(const KDbEscapedString& sql, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! @overload executeQuery(const KDbEscapedString&, int) @a params are values of parameters that will be inserted into places marked with [] before execution of the query. Statement is build from data provided by @a query schema. Kexi SQL and driver-specific escaping is performed on table names. */ KDbCursor* executeQuery(KDbQuerySchema* query, const QList& params, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! @overload */ KDbCursor* executeQuery(KDbQuerySchema* query, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! @overload Executes query described by @a query schema without parameters. Statement is build from data provided by @a table schema, it is like "select * from table_name".*/ KDbCursor* executeQuery(KDbTableSchema* table, KDbCursor::Options options = KDbCursor::Option::None) Q_REQUIRED_RESULT; /*! Deletes cursor @a cursor previously created by functions like executeQuery() for this connection. There is an attempt to close the cursor with KDbCursor::close() if it was opened. Anyway, at last cursor is deleted. @return true if cursor is properly closed before deletion. */ bool deleteCursor(KDbCursor *cursor); /*! @return schema of a table pointed by @a tableId, retrieved from currently used database. The schema is cached inside connection, so retrieval is performed only once, on demand. */ KDbTableSchema* tableSchema(int tableId); /*! @return schema of a table pointed by @a tableName, retrieved from currently used database. KDb system table schema can be also retrieved. @see tableSchema( int tableId ) */ KDbTableSchema* tableSchema(const QString& tableName); /*! @return schema of a query pointed by @a queryId, retrieved from currently used database. The schema is cached inside connection, so retrieval is performed only once, on demand. */ KDbQuerySchema* querySchema(int queryId); /*! @return schema of a query pointed by @a queryName, retrieved from currently used database. @see querySchema( int queryId ) */ KDbQuerySchema* querySchema(const QString& queryName); /*! Sets @a queryName query obsolete by moving it out of the query sets, so it will not be accessible by querySchema( const QString& queryName ). The existing query object is not destroyed, to avoid problems when it's referenced. In this case, a new query schema will be retrieved directly from the backend. For now it's used in KexiQueryDesignerGuiEditor::storeLayout(). This solves the problem when user has changed a query schema but already form still uses previously instantiated query schema. @return true if there is such query. Otherwise the method does nothing. */ bool setQuerySchemaObsolete(const QString& queryName); //! Options for querying records //! @since 3.1 enum class QueryRecordOption { AddLimitTo1 = 1, //!< Adds a "LIMIT 1" clause to the query for optimization purposes //!< (it should not include one already) Default = AddLimitTo1 }; Q_DECLARE_FLAGS(QueryRecordOptions, QueryRecordOption) /*! Executes query for a raw statement @a sql and stores first record's data inside @a data. This is a convenient method when we need only first record from query result, or when we know that query result has only one record. If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return @c true if query was successfully executed and first record has been found, @c false on data retrieving failure, and @c cancelled if there's no single record available. */ tristate querySingleRecord(const KDbEscapedString& sql, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleRecord(KDbQuerySchema* query, KDbRecordData* data, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ tristate querySingleRecord(KDbQuerySchema *query, KDbRecordData *data, const QList ¶ms, QueryRecordOptions options = QueryRecordOption::Default); /*! Executes query for a raw statement @a sql and stores first record's field's (number @a column) string value inside @a value. For efficiency it's recommended that a query defined by @a sql should have just one field (SELECT one_field FROM ....). If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return @c true if query was successfully executed and first record has been found, @c false on data retrieving failure, and @c cancelled if there's no single record available. @see queryStringList() */ tristate querySingleString(const KDbEscapedString& sql, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleString(KDbQuerySchema* query, QString* value, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with [] before query execution. */ tristate querySingleString(KDbQuerySchema* query, QString* value, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! Convenience function: executes query for a raw SQL statement @a sql and stores first record's field's (number @a column) value inside @a number. @see querySingleString(). If @a options includes AddLimitTo1 value, "LIMIT 1" clause is added to the query (this is the default). Caller should make sure it is not there in the @a sql already. @return true if query was successfully executed and first record has been found, false on data retrieving failure, and cancelled if there's no single record available. */ tristate querySingleNumber(const KDbEscapedString& sql, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Uses a KDbQuerySchema object. */ tristate querySingleNumber(KDbQuerySchema* query, int* number, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ tristate querySingleNumber(KDbQuerySchema* query, int* number, const QList& params, int column = 0, QueryRecordOptions options = QueryRecordOption::Default); /*! Executes query for a raw SQL statement @a sql and stores Nth field's string value of every record inside @a list, where N is equal to @a column. The list is initially cleared. For efficiency it's recommended that a query defined by @a sql should have just one field (SELECT one_field FROM ....). @return true if all values were fetched successfuly, false on data retrieving failure. Returning empty list can be still a valid result. On errors, the list is not cleared, it may contain a few retrieved values. */ bool queryStringList(const KDbEscapedString& sql, QStringList* list, int column = 0); /*! @overload Uses a QuerySchema object. */ bool queryStringList(KDbQuerySchema* query, QStringList* list, int column = 0); /*! @overload Accepts @a params as parameters that will be inserted into places marked with "[]" before query execution. */ bool queryStringList(KDbQuerySchema* query, QStringList* list, const QList& params, int column = 0); /*! @return @c true if there is at least one record has been returned by executing query for a raw SQL statement @a sql or @c false if no such record exists. If @a options includes AddLimitTo1 value, the query is optimized into "SELECT 1 FROM (sql) LIMIT 1" (this is the default). Caller should make sure "SELECT 1" and "LIMIT 1" is not there in the @a sql already. This method does not fetch any records. On error returns @c cancelled. */ tristate resultExists(const KDbEscapedString &sql, QueryRecordOptions options = QueryRecordOption::Default); /*! @return true if there is at least one record in @a table. */ tristate isEmpty(KDbTableSchema* table); /** * @brief Return recently used SQL string * * If there was a successful query execution it is equal to result().sql(), * otherwise it is equal to result().errorSql(). */ virtual KDbEscapedString recentSqlString() const; //PROTOTYPE: #define A , const QVariant& #define H_INS_REC(args) QSharedPointer insertRecord(KDbTableSchema* tableSchema args) #define H_INS_REC_ALL \ H_INS_REC(A); \ H_INS_REC(A A); \ H_INS_REC(A A A); \ H_INS_REC(A A A A); \ H_INS_REC(A A A A A); \ H_INS_REC(A A A A A A); \ H_INS_REC(A A A A A A A); \ H_INS_REC(A A A A A A A A) H_INS_REC_ALL; #undef H_INS_REC #define H_INS_REC(args) QSharedPointer insertRecord(KDbFieldList* fields args) H_INS_REC_ALL; #undef H_INS_REC_ALL #undef H_INS_REC #undef A QSharedPointer insertRecord(KDbTableSchema *tableSchema, const QList &values); QSharedPointer insertRecord(KDbFieldList *fields, const QList &values); //! Options for creating table //! @since 3.1 enum class CreateTableOption { DropDestination = 1, //!< Drop destination table if exists Default = 0 }; Q_DECLARE_FLAGS(CreateTableOptions, CreateTableOption) /** * @brief Creates a new table * * Creates a new table defined by @a tableSchema. @c true is returned on success. In this case * @a tableSchema object is added to KDbConnection's structures and becomes owned the * KDbConnection object, so should not be destroyed by hand. * * If @a options include the DropDestination value and table schema with the same name as @a * tableSchema exists, it is dropped and the original identifier of the dropped schem is * assigned to the @a tableSchema object. * * If @a options do not include the DropDestination value and table schema with the same name * as @a tableSchema exists, @c false is returned. * * Table and column definitions are added to "Kexi system" tables. * * Prior to dropping the method checks if the table for the schema is in use, and if the new * schema defines at least one column. * * Note that on error: * - @a tableSchema is not inserted into KDbConnection's structures, so caller is still owner * of the object, * - existing table schema object is not destroyed (e.g. it is still available for * KDbConnection::tableSchema(const QString&), even if the table was physically dropped. * * @return true on success. */ bool createTable(KDbTableSchema *tableSchema, CreateTableOptions options = CreateTableOption::Default); /*! Creates a copy of table schema defined by @a tableSchema with data. Name, caption and description will be copied from @a newData. @return a table schema object. It is inserted into the KDbConnection structures and is owned by the KDbConnection object. The created table schema object should not be destroyed by hand afterwards. 0 is returned on failure. Table with destination name must not exist. @see createTable() */ KDbTableSchema *copyTable(const KDbTableSchema &tableSchema, const KDbObject &newData); /*! It is a convenience function, does exactly the same as KDbTableSchema *copyTable(const KDbTableSchema&, const KDbObject&). */ KDbTableSchema *copyTable(const QString& tableName, const KDbObject &newData); /*! Drops a table defined by @a tableSchema (both table object as well as physically). If true is returned, schema information @a tableSchema is destoyed (because it's owned), so don't keep this anymore! No error is raised if the table does not exist physically - its schema is removed even in this case. Removes the table and column definitions in kexi__* "system schema" tables. First checks that the table is not a system table. @todo Check that a database is currently in use? (c.f. createTable) @todo Update any structure (e.g. query) that depends on this table */ tristate dropTable(KDbTableSchema* tableSchema); /*! @overload * It is a convenience function. */ tristate dropTable(const QString& tableName); /*! Alters @a tableSchema using @a newTableSchema in memory and on the db backend. @return true on success, cancelled if altering was cancelled. */ //! @todo (js): implement real altering //! @todo (js): update any structure (e.g. query) that depend on this table! tristate alterTable(KDbTableSchema* tableSchema, KDbTableSchema* newTableSchema); //! Options for altering table name //! @since 3.1 enum class AlterTableNameOption { DropDestination = 1, //!< Drop destination table if exists Default = 0 }; Q_DECLARE_FLAGS(AlterTableNameOptions, AlterTableNameOption) /** * @brief Alters name of table * * Alters name of table described by @a tableSchema to @a newName. * If @a options include the DropDestination value and table having name @a newName already * exists, it is physically dropped, removed from connection's list of tables and replaced * by @a tableSchema. In this case identifier of @a tableSchema is set to the dropped table's * identifier. This can be useful if @a tableSchema was created with a temporary name and * identifier. It is for example used in KDbAlterTableHandler. * * If @a options do not include the DropDestination value (the default) and table having name * @a newName already exists, @c false is returned and @c ERR_OBJECT_EXISTS error is set in * the connection object. * * Table name in the schema of @a tableSchema is updated on successful altering. * @return true on success. */ bool alterTableName(KDbTableSchema* tableSchema, const QString& newName, AlterTableNameOptions options = AlterTableNameOption::Default); /*! Drops a query defined by @a querySchema. If true is returned, schema information @a querySchema is destoyed (because it's owned), so don't keep this anymore! */ bool dropQuery(KDbQuerySchema* querySchema); /*! It is a convenience function, does exactly the same as bool dropQuery( KDbQuerySchema* querySchema ) */ bool dropQuery(const QString& queryName); /*! Removes information about object with @a objId from internal "kexi__object" and "kexi__objectdata" tables. @return true on success. */ bool removeObject(int objId); /*! @return first field from @a fieldlist that has system name, @c nullptr if there are no such field. For checking, KDbDriver::isSystemFieldName() is used, so this check can be driver-dependent. */ KDbField* findSystemFieldName(const KDbFieldList& fieldlist); /*! @return name of any (e.g. first found) database for this connection. This method does not close or open this connection. The method can be used (it is also internally used, e.g. for database dropping) when we need a database name before we can connect and execute any SQL statement (e.g. DROP DATABASE). The method can return nul lstring, but in this situation no automatic (implicit) connections could be made, what is useful by e.g. dropDatabase(). Note for driver developers: return here a name of database which you are sure is existing. Default implementation returns: - value that previously had been set using setAvailableDatabaseName() for this connection, if it is not empty - else (2nd priority): value of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME if it is not empty. See description of KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME member. You may want to reimplement this method only when you need to depend on this connection specifics (e.g. you need to check something remotely). */ virtual QString anyAvailableDatabaseName(); /*! Sets @a dbName as name of a database that can be accessible. This is option that e.g. application that make use of KDb library can set to tune connection's behavior when it needs to temporary connect to any database in the server to do some work. You can pass empty dbName - then anyAvailableDatabaseName() will try return KDbDriverBehavior::ALWAYS_AVAILABLE_DATABASE_NAME (the default) value instead of the one previously set with setAvailableDatabaseName(). @see anyAvailableDatabaseName() */ void setAvailableDatabaseName(const QString& dbName); /*! Because some engines need to have opened any database before executing administrative SQL statements like "create database" or "drop database", this method is used to use appropriate, existing database for this connection. For file-based db drivers this always return true and does not set @a name to any value. For other db drivers: this sets @a name to db name computed using anyAvailableDatabaseName(), and if the name computed is empty, false is returned; if it is not empty, useDatabase() is called. False is returned also when useDatabase() fails. You can call this method from your application's level if you really want to perform tasks that require any used database. In such a case don't forget to closeDatabase() if returned @a name is not empty. Note: This method has nothing to do with creating or using temporary databases in such meaning that these database are not persistent */ bool useTemporaryDatabaseIfNeeded(QString* name); /** * Prepares execution of a new native (raw, backend-specific) SQL query. * * The query is described by a raw statement @a sql which should be is valid and properly * escaped. Access to results can be obtained using * the returned KDbSqlResult object. The object is guarded with a shared pointer to facilitate * transfer of ownership and memory management. A null pointer is returned if preparation of * the query fails. Use KDbConnection::result() immediately after calling prepareSql() to * obtain detailed result information about the preparation. * * The returned object should be deleted before the database connection is closed. * Connection object does not deletes the KDbSqlResult objects. It is also possible and * recommended that caller deletes the KDbSqlResult object as soon as the result is not needed. * * The returned object can be ignored if the query is not supposed to return records (e.g. * manipulates data through INSERT, UPDATE, DELETE, ...) or the caller is not interested in the * records. Thanks to the use of the shared pointer the object will be immediately deleted and * execution will be finalized prior to that. However to execute queries that return no * results, executeSql() is a better choice because of performance and easier reporting to * results. * * @note Only use this method if a non-portable raw query is required. * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. */ QSharedPointer prepareSql(const KDbEscapedString& sql) Q_REQUIRED_RESULT; /** * Executes a new native (raw, backend-specific) SQL query * * The query is described by a raw statement @a sql which should be is valid and properly * escaped. This method is a convenience version of prepareSql() that immediately starts and * finalizes execution of a raw query in one step and provides a result. Use it for queries * that do not return records, i.e. for queries that manipulate data (INSERT, UPDATE, DELETE, * ...) or if the caller is not interested in the returned records. * * @note Only use this method if a non-portable raw query is required. * In other cases use prepareQuery() or executeQuery() and the KDbCursor object. */ bool executeSql(const KDbEscapedString& sql); /*! Stores object (id, name, caption, description) described by @a object on the backend. It is expected that entry on the backend already exists, so it's updated. Changes to identifier attribute are not allowed. @return true on success. */ bool storeObjectData(KDbObject* object); /*! Stores new entry for object (id, name, caption, description) described by @a object on the backend. If object.id() was less than 0, new, unique object identifier is obtained and assigned to @a object (see KDbObject::id()). @return true on success. */ bool storeNewObjectData(KDbObject* object); /*! Finds object data for object of type @a type and identifier @a id. Added for convenience. If @a type is KDb::AnyObjectType, object type is ignored during the find. @see setupObjectData(const KDbRecordData*, KDbObject*). @return true on success, false on failure and cancelled when such object couldn't be found. @since 3.1 */ tristate loadObjectData(int type, int id, KDbObject* object); /*! Finds object data for object of type @a type and name @a name. If the object is found, resulted schema is stored in @a object and true is returned, otherwise false is returned. */ tristate loadObjectData(int type, const QString& name, KDbObject* object); /*! Loads (potentially large) data block (e.g. xml form's representation), referenced by objectID and puts it to @a dataString. The can be block indexed with optional @a dataID. @return true on success, false on failure and cancelled when there is no such data block @see storeDataBlock(). */ tristate loadDataBlock(int objectID, QString* dataString, const QString& dataID = QString()); /*! Stores (potentially large) data block @a dataString (e.g. xml form's representation), referenced by objectID. Block will be stored in "kexi__objectdata" table and an optional @a dataID identifier. If there is already such record in the table, it's simply overwritten. @return true on success @see loadDataBlock() removeDataBlock() copyDataBlock(). */ bool storeDataBlock(int objectID, const QString &dataString, const QString& dataID = QString()); /*! Copies (potentially large) data, e.g. form's XML representation, referenced by @a sourceObjectID pointed by optional @a dataID. @return true on success. Does not fail if blocks do not exist. Prior to copying, existing data blocks are removed even if there are no new blocks to copy. Copied data blocks will have @a destObjectID object identifier assigned. Note that if @a dataID is not specified, all data blocks found for the @a sourceObjectID will be copied. @see loadDataBlock() storeDataBlock() removeDataBlock(). */ bool copyDataBlock(int sourceObjectID, int destObjectID, const QString& dataID = QString()); /*! Removes (potentially large) string data (e.g. xml form's representation), referenced by @a objectID, and pointed by optional @a dataID. @return true on success. Does not fail if the block does not exist. Note that if @a dataID is not specified, all data blocks for the @a objectID will be removed. @see loadDataBlock() storeDataBlock() copyDataBlock(). */ bool removeDataBlock(int objectID, const QString& dataID = QString()); /*! Prepare an SQL statement and return a @a KDbPreparedStatement instance. */ KDbPreparedStatement prepareStatement(KDbPreparedStatement::Type type, KDbFieldList* fields, const QStringList& whereFieldNames = QStringList()); bool isInternalTableSchema(const QString& tableName); + /** + * @brief Returns number of records returned by given SQL statement + * + * @return number of records that can be retrieved after executing @a sql statement within + * a connection @a conn. The statement should be of type SELECT. For SQL data sources it does not + * fetch any records, only "COUNT(*)" SQL aggregation is used at the backed. + * -1 is returned if any error occurred or if @a conn is @c nullptr. + * + * @since 3.1 + */ + //! @todo perhaps use quint64 here? + KDB_EXPORT int recordCount(const KDbEscapedString& sql); + + /** + * @brief Returns number of records that contains given table + * + * @return number of records that can be retrieved from @a tableSchema. + * To obtain the result the table must be created or retrieved using a KDbConnection object, + * i.e. tableSchema.connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" + * SQL aggregation is used at the backed. + * -1 is returned if error occurred or if tableSchema.connection() is @c nullptr. + * + * @since 3.1 + */ + //! @todo perhaps use quint64 here? + //! @todo does not work with non-SQL data sources + KDB_EXPORT int recordCount(const KDbTableSchema& tableSchema); + + /** + * @overload + * + * Operates on a query schema. @a params are optional values of parameters that will be inserted + * into [] placeholders before execution of query that counts the records. + * To obtain the result the query must be created or retrieved using a KDbConnection object, + * i.e. querySchema->connection() must not return @c nullptr. For SQL data sources only "COUNT(*)" + * SQL aggregation is used at the backed. + * -1 is returned if error occurred or if querySchema->connection() is @c nullptr. + * + * @since 3.1 + */ + //! @todo perhaps use quint64 here? + KDB_EXPORT int recordCount(KDbQuerySchema* querySchema, + const QList& params = QList()); + + /** + * @overload + * + * Operates on a table or query schema. @a params is a list of optional parameters that + * will be inserted into [] placeholders before execution of query that counts the records. + * + * If @a tableOrQuery is @c nullptr or provides neither table nor query, -1 is returned. + * + * @since 3.1 + */ + //! @todo perhaps use quint64 here? + KDB_EXPORT int recordCount(KDbTableOrQuerySchema* tableOrQuery, + const QList& params = QList()); + //! Identifier escaping function in the associated KDbDriver. /*! Calls the identifier escaping function in this connection to escape table and column names. This should be used when explicitly constructing SQL strings (e.g. "FROM " + escapeIdentifier(tablename)). It should not be used for other functions (e.g. don't do useDatabase(escapeIdentifier(database))), because the identifier will be escaped when the called function generates, for example, "USE " + escapeIdentifier(database). For efficiency, KDb "system" tables (prefixed with kexi__) and columns therein are not escaped - we assume these are valid identifiers for all drivers. Use KDbEscapedString::isValid() to check if escaping has been performed successfully. Invalid strings are set to null in addition, that is KDbEscapedString::isNull() is true, not just isEmpty(). */ virtual QString escapeIdentifier(const QString& id) const; protected: /*! Used by KDbDriver */ KDbConnection(KDbDriver *driver, const KDbConnectionData& connData, const KDbConnectionOptions &options); /*! Method to be called form KDbConnection's subclass destructor. @see ~KDbConnection() */ void destroy(); /*! For implementation: connects to database. @return true on success. */ virtual bool drv_connect() = 0; /*! For implementation: disconnects database @return true on success. */ virtual bool drv_disconnect() = 0; /*! For implementation: Sets @a version to real server's version. Depending on backend type this method is called after (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is true) or before database is used (if KDbDriverBehavior::USING_DATABASE_REQUIRED_TO_CONNECT is false), i.e. for PostgreSQL it is called after. In any case it is called after successful drv_connect(). @return true on success. */ virtual bool drv_getServerVersion(KDbServerVersionInfo* version) = 0; /*! LOW LEVEL METHOD. For implementation: returns true if table with name @a tableName exists in the database. @return @c false if it does not exist or @c cancelled if error occurred. The lookup is case insensitive. */ virtual tristate drv_containsTable(const QString &tableName) = 0; /** * Creates table using @a tableSchema information. * * @return true on success. * * Default implementation builds a statement using createTableStatement() and calls * executeSql(). Note for driver developers: reimplement this only to perform creation in other * way. */ virtual bool drv_createTable(const KDbTableSchema& tableSchema); /*! Alters table's described @a tableSchema name to @a newName. This is the default implementation, using "ALTER TABLE RENAME TO ", what's supported by SQLite >= 3.2, PostgreSQL, MySQL. Backends lacking ALTER TABLE, for example SQLite, reimplement this with by an inefficient data copying to a new table. In any case, renaming is performed at the backend. It's good idea to keep the operation within a transaction. @return true on success. */ virtual bool drv_alterTableName(KDbTableSchema* tableSchema, const QString& newName); /*! Copies table data from @a tableSchema to @a destinationTableSchema Default implementation executes "INSERT INTO .. SELECT * FROM .." @return true on success. */ virtual bool drv_copyTableData(const KDbTableSchema &tableSchema, const KDbTableSchema &destinationTableSchema); /*! Physically drops table named with @a name. Default impelmentation executes "DROP TABLE.." command, so you rarely want to change this. */ virtual bool drv_dropTable(const QString& tableName); /*! @internal drops table @a tableSchema physically, but destroys @a tableSchema object only if @a alsoRemoveSchema is true. Used (alsoRemoveSchema==false) on table altering: if recreating table can fail we're giving up and keeping the original table schema (even if it is no longer points to any real data). */ tristate dropTableInternal(KDbTableSchema* tableSchema, bool alsoRemoveSchema); /*! Setups data for object that owns @a object (e.g. table, query) opened on 'kexi__objects' table, pointing to a record corresponding to given object. */ bool setupObjectData(const KDbRecordData& data, KDbObject* object); /*! @return a new field table schema for a table retrieved from @a data. Ownership of the returned object is passed to the caller. Used internally by tableSchema(). */ KDbField* setupField(const KDbRecordData& data) Q_REQUIRED_RESULT; /** * Prepares query for a raw SQL statement @a sql with possibility of returning records. * * It is useful mostly for SELECT queries. While INSERT queries do not return records, the * KDbSqlResult object offers KDbSqlResult::lastInsertRecordId(). The @sql should be is valid * and properly escaped. Only use this method if you really need. For low-level access to the * results (without cursors). The result may be not stored (not buffered) yet. Use * KDbSqlResult::fetchRecord() to fetch each record. @return Null pointer if there is no proper * result or error. Ownership of the returned object is passed to the caller. * * @see prepareSql */ virtual KDbSqlResult* drv_prepareSql(const KDbEscapedString &sql) /*Q_REQUIRED_RESULT*/ = 0; /** * Executes query for a raw SQL statement @a sql without returning resulting records. * * It is useful mostly for INSERT queries but it is possible to execute SELECT queries when * returned records can be ignored. The @sql should be is valid and properly escaped. * * @note Only use this method if you really need. * @see executeSql */ virtual bool drv_executeSql(const KDbEscapedString& sql) = 0; /*! For reimplementation: loads list of databases' names available for this connection and adds these names to @a list. If your server is not able to offer such a list, consider reimplementing drv_databaseExists() instead. The method should return true only if there was no error on getting database names list from the server. Default implementation puts empty list into @a list and returns true. @see databaseNames */ virtual bool drv_getDatabasesList(QStringList* list); /*! For optional reimplementation: asks server if database @a dbName exists. This method is used internally in databaseExists(). The default implementation calls databaseNames and checks if that list contains @a dbName. If you need to ask the server specifically if a database exists, eg. if you can't retrieve a list of all available database names, please reimplement this method and do all needed checks. See databaseExists() description for details about ignoreErrors argument. You should use it properly in your implementation. Note: This method should also work if there is already database used (with useDatabase()); in this situation no changes should be made in current database selection. */ virtual bool drv_databaseExists(const QString &dbName, bool ignoreErrors = true); /*! For implementation: creates new database using connection */ virtual bool drv_createDatabase(const QString &dbName = QString()) = 0; /*! For implementation: opens existing database using connection @return true on success, false on failure; sets @a cancelled to true if this action has been cancelled. */ virtual bool drv_useDatabase(const QString &dbName = QString(), bool *cancelled = nullptr, KDbMessageHandler* msgHandler = nullptr) = 0; /*! For implementation: closes previously opened database using connection. */ virtual bool drv_closeDatabase() = 0; /*! @return true if internal driver's structure is still in opened/connected state and database is used. Note for driver developers: Put here every test that you can do using your internal engine's database API, eg (a bit schematic): my_connection_struct->isConnected()==true. Do not check things like KDbConnection::isDatabaseUsed() here or other things that "KDb already knows" at its level. If you cannot test anything, just leave default implementation (that returns true). Result of this method is used as an additional chance to check for isDatabaseUsed(). Do not call this method from your driver's code, it should be used at KDb level only. */ virtual bool drv_isDatabaseUsed() const { return true; } /*! For implementation: drops database from the server using connection. After drop, database shouldn't be accessible anymore. */ virtual bool drv_dropDatabase(const QString &dbName = QString()) = 0; /*! Creates table named by @a tableName. Schema object must be on schema tables' list before calling this method (otherwise false if returned). Just uses drv_createTable( const KDbTableSchema& tableSchema ). Used internally, e.g. in createDatabase(). @return true on success */ virtual bool drv_createTable(const QString& tableName); /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "BEGIN" sql statement and returns just empty data (KDbTransactionData object). Ownership of the returned object is passed to the caller. Drivers that do not support transactions (see KDbDriver::features()) do never call this method. Reimplement this method if you need to do something more (e.g. if you driver will support multiple transactions per connection). Make subclass of KDbTransactionData (declared in KDbTransaction.h) and return object of this subclass. @c nullptr should be returned on error. Do not check anything in connection (isConnected(), etc.) - all is already done. @todo Add support for nested transactions, e.g. KDbTransactionData* beginTransaction(KDbTransactionData *parent) */ virtual KDbTransactionData* drv_beginTransaction() Q_REQUIRED_RESULT; /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "COMMIT" sql statement and returns true on success. @see drv_beginTransaction() */ virtual bool drv_commitTransaction(KDbTransactionData* trans); /*! Note for driver developers: begins new transaction and returns handle to it. Default implementation just executes "ROLLBACK" sql statement and returns true on success. @see drv_beginTransaction() */ virtual bool drv_rollbackTransaction(KDbTransactionData* trans); /*! Preprocessing (if any) required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed before an Insert statement. @see drv_afterInsert() */ virtual bool drv_beforeInsert(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Postprocessing (if any) required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed after an Insert statement. @see drv_beforeInsert() */ virtual bool drv_afterInsert(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Preprocessing required by drivers before execution of an Update statement. Reimplement this method in your driver if there are any special processing steps to be executed before an Update statement. @see drv_afterUpdate() */ virtual bool drv_beforeUpdate(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Postprocessing required by drivers before execution of an Insert statement. Reimplement this method in your driver if there are any special processing steps to be executed after an Update statement. @see drv_beforeUpdate() */ virtual bool drv_afterUpdate(const QString& tableName, KDbFieldList* fields) { Q_UNUSED(tableName); Q_UNUSED(fields); return true; } /*! Changes autocommiting option for established connection. @return true on success. Note for driver developers: reimplement this only if your engine allows to set special auto commit option (like "SET AUTOCOMMIT=.." in MySQL). If not, auto commit behavior will be simulated if at least single transactions per connection are supported by the engine. Do not set any internal flags for autocommiting -- it is already done inside setAutoCommit(). Default implementation does nothing with connection, just returns true. @see drv_beginTransaction(), autoCommit(), setAutoCommit() */ virtual bool drv_setAutoCommit(bool on); /*! Prepare an SQL statement and return a @a KDbPreparedStatementInterface-derived object. Ownership of the returned object is passed to the caller. */ virtual KDbPreparedStatementInterface* prepareStatementInternal() /*Q_REQUIRED_RESULT*/ = 0; /*! Internal, for handling autocommited transactions: begins transaction if one is supported. @return true if new transaction started successfully or no transactions are supported at all by the driver or if autocommit option is turned off. A handle to a newly created transaction (or @c nullptr on error) is passed to @a tg parameter. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): and there is already transaction started, it is committed before starting a new one, but only if this transaction has been started inside KDbConnection object. (i.e. by beginAutoCommitTransaction()). Otherwise, a new transaction will not be started, but true will be returned immediately. */ bool beginAutoCommitTransaction(KDbTransactionGuard* tg); /*! Internal, for handling autocommited transactions: Commits transaction prevoiusly started with beginAutoCommitTransaction(). @return true on success or when no transactions are supported at all by the driver. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): if @a trans has been started outside KDbConnection object (i.e. not by beginAutoCommitTransaction()), the transaction will not be committed. */ bool commitAutoCommitTransaction(const KDbTransaction& trans); /*! Internal, for handling autocommited transactions: Rolls back transaction prevoiusly started with beginAutoCommitTransaction(). @return true on success or when no transactions are supported at all by the driver. Special case when used database driver has only single transaction support (KDbDriver::SingleTransactions): @a trans will not be rolled back if it has been started outside this KDbConnection object. */ bool rollbackAutoCommitTransaction(const KDbTransaction& trans); /*! Helper: checks if connection is established; if not: error message is set up and false returned */ bool checkConnected(); /*! Helper: checks both if connection is established and database any is used; if not: error message is set up and false returned */ bool checkIsDatabaseUsed(); /*! Update a record. */ bool updateRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); /*! Insert a new record. */ bool insertRecord(KDbQuerySchema* query, KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecordId = false); /*! Delete an existing record. */ bool deleteRecord(KDbQuerySchema* query, KDbRecordData* data, bool useRecordId = false); /*! Delete all existing records. */ bool deleteAllRecords(KDbQuerySchema* query); /*! Called by KDbTableSchema -- signals destruction to KDbConnection object To avoid having deleted table object on its list. */ void removeMe(KDbTableSchema *ts); + // -- internal methods follow + /*! @internal @return true if the cursor @a cursor contains column @a column, else, sets appropriate error with a message and returns false. */ bool checkIfColumnExists(KDbCursor *cursor, int column); /*! @internal used by insertRecord() methods. */ QSharedPointer insertRecordInternal(const QString &tableSchemaName, KDbFieldList *fields, const KDbEscapedString &sql); /*! @internal used by querySingleRecord() methods. */ tristate querySingleRecordInternal(KDbRecordData* data, const KDbEscapedString* sql, KDbQuerySchema* query, const QList* params, QueryRecordOptions options); /*! @internal used by querySingleString() methods. */ tristate querySingleStringInternal(const KDbEscapedString* sql, QString* value, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); /*! @internal used by queryNumberString() methods. */ tristate querySingleNumberInternal(const KDbEscapedString* sql, int* number, KDbQuerySchema* query, const QList* params, int column, QueryRecordOptions options); /*! @internal used by queryStringList() methods. */ bool queryStringListInternal(const KDbEscapedString *sql, QStringList* list, KDbQuerySchema* query, const QList* params, int column, bool (*filterFunction)(const QString&)); /*! @internal used by *Internal() methods. Executes query based on a raw SQL statement @a sql or @a query with optional @a params. Ownership of the returned object is passed to the caller.*/ KDbCursor* executeQueryInternal(const KDbEscapedString& sql, KDbQuerySchema* query, const QList* params) Q_REQUIRED_RESULT; /*! Loads extended schema information for table @a tableSchema, if present (see ExtendedTableSchemaInformation in Kexi Wiki). @return true on success */ bool loadExtendedTableSchemaData(KDbTableSchema* tableSchema); /*! Stores extended schema information for table @a tableSchema, (see ExtendedTableSchemaInformation in Kexi Wiki). The action is performed within the current transaction, so it's up to you to commit. Used, e.g. by createTable(), within its transaction. @return true on success */ bool storeExtendedTableSchemaData(KDbTableSchema* tableSchema); /*! @internal Stores main field's schema information for field @a field. Used in table altering code when information in kexi__fields has to be updated. @return true on success and false on failure. */ bool storeMainFieldSchema(KDbField *field); //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! This is a part of alter table interface implementing lower-level operations used to perform table schema altering. Used by KDbAlterTableHandler. Changes value of field property. @return true on success, false on failure, cancelled if the action has been cancelled. Note for driver developers: implement this if the driver has to supprot the altering. */ virtual tristate drv_changeFieldProperty(KDbTableSchema* table, KDbField* field, const QString& propertyName, const QVariant& value) { Q_UNUSED(table); Q_UNUSED(field); Q_UNUSED(propertyName); Q_UNUSED(value); return cancelled; } //! Used by KDbCursor class void addCursor(KDbCursor* cursor); //! Used by KDbCursor class void takeCursor(KDbCursor* cursor); private: //! Internal, used by storeObjectData(KDbObject*) and storeNewObjectData(KDbObject* object). bool storeObjectDataInternal(KDbObject* object, bool newObject); //! @internal //! @return identifier escaped by driver (if @a escapingType is KDb::DriverEscaping) //! or by the KDb's built-in escape routine. QString escapeIdentifier(const QString& id, KDb::IdentifierEscapingType escapingType) const; KDbConnectionPrivate* d; //!< @internal d-pointer class. Q_DISABLE_COPY(KDbConnection) friend class KDbConnectionPrivate; friend class KDbAlterTableHandler; friend class KDbConnectionProxy; friend class KDbCursor; friend class KDbDriver; friend class KDbProperties; //!< for setError() + friend class KDbQuerySchema; + friend class KDbQuerySchemaPrivate; friend class KDbTableSchemaChangeListener; friend class KDbTableSchema; //!< for removeMe() }; Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::QueryRecordOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::AlterTableNameOptions) Q_DECLARE_OPERATORS_FOR_FLAGS(KDbConnection::CreateTableOptions) #endif diff --git a/src/KDbConnection_p.h b/src/KDbConnection_p.h index ce6928e1..618c0aa9 100644 --- a/src/KDbConnection_p.h +++ b/src/KDbConnection_p.h @@ -1,201 +1,209 @@ /* This file is part of the KDE project Copyright (C) 2005 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CONNECTION_P_H #define KDB_CONNECTION_P_H #include "KDbConnectionData.h" #include "KDbConnection.h" #include "KDbConnectionOptions.h" #include "kdb_export.h" #include "KDbParser.h" #include "KDbProperties.h" +#include "KDbQuerySchema_p.h" #include "KDbVersionInfo.h" //! Interface for accessing connection's internal result, for use by drivers. class KDB_EXPORT KDbConnectionInternal { public: explicit KDbConnectionInternal(KDbConnection *conn); KDbConnection* const connection; private: Q_DISABLE_COPY(KDbConnectionInternal) }; class KDbConnectionPrivate { Q_DECLARE_TR_FUNCTIONS(KDbConnectionPrivate) public: KDbConnectionPrivate(KDbConnection* const conn, KDbDriver *drv, const KDbConnectionData& _connData, const KDbConnectionOptions &_options); ~KDbConnectionPrivate(); void deleteAllCursors(); void errorInvalidDBContents(const QString& details); QString strItIsASystemObject() const; inline KDbParser *parser() { return m_parser ? m_parser : (m_parser = new KDbParser(conn)); } inline KDbTableSchema* table(const QString& name) const { return m_tablesByName.value(name); } inline KDbTableSchema* table(int id) const { return m_tables.value(id); } //! used just for removing system KDbTableSchema objects on db close. inline QSet internalKDbTables() const { return m_internalKDbTables; } /*! Allocates all needed table KDb system objects for kexi__* KDb library's system tables schema. These objects are used internally in this connection and are added to list of tables (by name, not by id because these have no ids). */ void setupKDbSystemSchema(); void insertTable(KDbTableSchema* tableSchema); /*! Removes table schema pointed by tableSchema.id() and tableSchema.name() from internal structures and destroys it. Does not make any change at the backend. Note that the table schema being removed may be not the same as @a tableSchema. */ void removeTable(const KDbTableSchema& tableSchema); void takeTable(KDbTableSchema* tableSchema); void renameTable(KDbTableSchema* tableSchema, const QString& newName); void changeTableId(KDbTableSchema* tableSchema, int newId); void clearTables(); inline KDbQuerySchema* query(const QString& name) const { return m_queriesByName.value(name); } inline KDbQuerySchema* query(int id) const { return m_queries.value(id); } void insertQuery(KDbQuerySchema* query); /*! Removes @a querySchema from internal structures and destroys it. Does not make any change at the backend. */ void removeQuery(KDbQuerySchema* querySchema); void setQueryObsolete(KDbQuerySchema* query); void clearQueries(); /*! @return a full table schema for a table retrieved using 'kexi__*' system tables. Connection keeps ownership of the returned object. Used internally by tableSchema() methods. On failure deletes @a table and returns @c nullptr. */ KDbTableSchema* setupTableSchema(KDbTableSchema *table) Q_REQUIRED_RESULT; /*! @return a full query schema for a query using 'kexi__*' system tables. Connection keeps ownership of the returned object. Used internally by querySchema() methods. On failure deletes @a query and returns @c nullptr. */ KDbQuerySchema* setupQuerySchema(KDbQuerySchema *query) Q_REQUIRED_RESULT; + //! @return cached fields expanded information for @a query + KDbQuerySchemaFieldsExpanded *fieldsExpanded(const KDbQuerySchema *query); + + //! Inserts cached fields expanded information for @a query + void insertFieldsExpanded(const KDbQuerySchema *query, KDbQuerySchemaFieldsExpanded *cache); + KDbConnection* const conn; //!< The @a KDbConnection instance this @a KDbConnectionPrivate belongs to. KDbConnectionData connData; //!< the @a KDbConnectionData used within that connection. //! True for read only connection. Used especially for file-based drivers. KDbConnectionOptions options; //!< The driver this @a KDbConnection instance uses. KDbDriver * const driver; /*! Default transaction handle. If transactions are supported: Any operation on database (e.g. inserts) that is started without specifying transaction context, will be performed in the context of this transaction. */ KDbTransaction default_trans; QList transactions; QHash* > tableSchemaChangeListeners; //! Used in KDbConnection::setQuerySchemaObsolete( const QString& queryName ) //! to collect obsolete queries. THese are deleted on connection deleting. QSet obsoleteQueries; //! server version information for this connection. KDbServerVersionInfo serverVersion; //! Database version information for this connection. KDbVersionInfo databaseVersion; KDbParser *m_parser = nullptr; //! cursors created for this connection QSet cursors; //! Database properties KDbProperties dbProperties; QString availableDatabaseName; //!< used by anyAvailableDatabaseName() QString usedDatabase; //!< database name that is opened now (the currentDatabase() name) //! true if rollbackTransaction() and commitTransaction() shouldn't remove //! the transaction object from 'transactions' list; used by closeDatabase() bool dontRemoveTransactions = false; //! used to avoid endless recursion between useDatabase() and databaseExists() //! when useTemporaryDatabaseIfNeeded() works bool skipDatabaseExistsCheckInUseDatabase = false; /*! Used when single transactions are only supported (KDbDriver::SingleTransactions). True value means default KDbTransaction has been started inside connection object (by beginAutoCommitTransaction()), otherwise default transaction has been started outside of the object (e.g. before createTable()), so we shouldn't autocommit the transaction in commitAutoCommitTransaction(). Also, beginAutoCommitTransaction() doesn't restarts transaction if default_trans_started_inside is false. Such behavior allows user to execute a sequence of actions like CREATE TABLE...; INSERT DATA...; within a single transaction and commit it or rollback by hand. */ bool defaultTransactionStartedInside = false; bool isConnected = false; bool autoCommit = true; bool insideCloseDatabase = false; //!< helper: true while closeDatabase() is executed private: //! Table schemas retrieved on demand with tableSchema() QHash m_tables; QHash m_tablesByName; //! used just for removing system KDbTableSchema objects on db close. QSet m_internalKDbTables; //! Query schemas retrieved on demand with querySchema() QHash m_queries; QHash m_queriesByName; + KDbUtils::AutodeletedHash m_fieldsExpandedCache; Q_DISABLE_COPY(KDbConnectionPrivate) }; #endif diff --git a/src/KDbCursor.cpp b/src/KDbCursor.cpp index 162527a2..27cfb1d3 100644 --- a/src/KDbCursor.cpp +++ b/src/KDbCursor.cpp @@ -1,607 +1,622 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbCursor.h" #include "KDbConnection.h" #include "KDbDriver.h" #include "KDbDriverBehavior.h" #include "KDbError.h" #include "KDb.h" #include "KDbNativeStatementBuilder.h" #include "KDbQuerySchema.h" #include "KDbRecordData.h" #include "KDbRecordEditBuffer.h" #include "kdb_debug.h" class Q_DECL_HIDDEN KDbCursor::Private { public: Private() : opened(false) , atLast(false) , readAhead(false) , validRecord(false) , atBuffer(false) { } ~Private() { } bool containsRecordIdInfo; //!< true if result contains extra column for record id; //!< used only for PostgreSQL now //! @todo IMPORTANT: use something like QPointer conn; KDbConnection *conn; KDbEscapedString rawSql; bool opened; bool atLast; bool readAhead; bool validRecord; //!< true if valid record is currently retrieved @ current position //! Used by setOrderByColumnList() KDbQueryColumnInfo::Vector orderByColumnList; QList queryParameters; // bool atBuffer; //!< true if we already point to the buffer with curr_coldata // }; KDbCursor::KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, Options options) : m_query(nullptr) , m_options(options) , d(new Private) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QLatin1String("Create cursor for raw SQL: ") + sql.toString()); #endif init(conn); d->rawSql = sql; } KDbCursor::KDbCursor(KDbConnection* conn, KDbQuerySchema* query, Options options) : m_query(query) , m_options(options) , d(new Private) { #ifdef KDB_DEBUG_GUI KDb::debugGUI(QString::fromLatin1("Create cursor for query \"%1\":\n") .arg(KDb::iifNotEmpty(query->name(), QString::fromLatin1(""))) + KDbUtils::debugString(query)); #endif init(conn); } void KDbCursor::init(KDbConnection* conn) { Q_ASSERT(conn); d->conn = conn; d->conn->addCursor(this); m_afterLast = false; m_at = 0; m_records_in_buf = 0; m_buffering_completed = false; m_fetchResult = FetchInvalid; d->containsRecordIdInfo = (m_query && m_query->masterTable()) && d->conn->driver()->behavior()->ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE == false; if (m_query) { //get list of all fields m_visibleFieldsExpanded = new KDbQueryColumnInfo::Vector(); - *m_visibleFieldsExpanded = m_query->visibleFieldsExpanded( - d->containsRecordIdInfo ? KDbQuerySchema::WithInternalFieldsAndRecordId - : KDbQuerySchema::WithInternalFields); + *m_visibleFieldsExpanded = m_query->visibleFieldsExpanded(conn, + d->containsRecordIdInfo ? KDbQuerySchema::FieldsExpandedMode::WithInternalFieldsAndRecordId + : KDbQuerySchema::FieldsExpandedMode::WithInternalFields); m_logicalFieldCount = m_visibleFieldsExpanded->count() - - m_query->internalFields().count() - (d->containsRecordIdInfo ? 1 : 0); + - m_query->internalFields(conn).count() - (d->containsRecordIdInfo ? 1 : 0); m_fieldCount = m_visibleFieldsExpanded->count(); m_fieldsToStoreInRecord = m_fieldCount; } else { m_visibleFieldsExpanded = nullptr; m_logicalFieldCount = 0; m_fieldCount = 0; m_fieldsToStoreInRecord = 0; } } KDbCursor::~KDbCursor() { #ifdef KDB_DEBUG_GUI #if 0 // too many details if (m_query) KDb::debugGUI(QLatin1String("~ Delete cursor for query")); else KDb::debugGUI(QLatin1String("~ Delete cursor: ") + m_rawSql.toString()); #endif #endif /* if (!m_query) kdbDebug() << "KDbCursor::~KDbCursor() '" << m_rawSql.toLatin1() << "'"; else kdbDebug() << "KDbCursor::~KDbCursor() ";*/ d->conn->takeCursor(this); delete m_visibleFieldsExpanded; delete d; } bool KDbCursor::readAhead() const { return d->readAhead; } -KDbConnection* KDbCursor::connection() const +KDbConnection* KDbCursor::connection() +{ + return d->conn; +} + +const KDbConnection* KDbCursor::connection() const { return d->conn; } KDbQuerySchema *KDbCursor::query() const { return m_query; } KDbEscapedString KDbCursor::rawSql() const { return d->rawSql; } KDbCursor::Options KDbCursor::options() const { return m_options; } bool KDbCursor::isOpened() const { return d->opened; } bool KDbCursor::containsRecordIdInfo() const { return d->containsRecordIdInfo; } KDbRecordData* KDbCursor::storeCurrentRecord() const { KDbRecordData* data = new KDbRecordData(m_fieldsToStoreInRecord); if (!drv_storeCurrentRecord(data)) { delete data; return nullptr; } return data; } bool KDbCursor::storeCurrentRecord(KDbRecordData* data) const { if (!data) { return false; } data->resize(m_fieldsToStoreInRecord); return drv_storeCurrentRecord(data); } bool KDbCursor::open() { if (d->opened) { if (!close()) return false; } if (!d->rawSql.isEmpty()) { m_result.setSql(d->rawSql); } else { if (!m_query) { kdbDebug() << "no query statement (or schema) defined!"; m_result = KDbResult(ERR_SQL_EXECUTION_ERROR, tr("No query statement or schema defined.")); return false; } KDbSelectStatementOptions options; options.setAlsoRetrieveRecordId(d->containsRecordIdInfo); /*get record Id if needed*/ KDbNativeStatementBuilder builder(d->conn); KDbEscapedString sql; if (!builder.generateSelectStatement(&sql, m_query, options, d->queryParameters) || sql.isEmpty()) { kdbDebug() << "no statement generated!"; m_result = KDbResult(ERR_SQL_EXECUTION_ERROR, tr("Could not generate query statement.")); return false; } m_result.setSql(sql); #ifdef KDB_DEBUG_GUI KDb::debugGUI(QString::fromLatin1("SQL for query \"%1\": ") .arg(KDb::iifNotEmpty(m_query->name(), QString::fromLatin1(""))) + m_result.sql().toString()); #endif } d->opened = drv_open(m_result.sql()); m_afterLast = false; //we are not @ the end m_at = 0; //we are before 1st rec if (!d->opened) { m_result.setCode(ERR_SQL_EXECUTION_ERROR); m_result.setMessage(tr("Error opening database cursor.")); return false; } d->validRecord = false; if (d->conn->driver()->behavior()->_1ST_ROW_READ_AHEAD_REQUIRED_TO_KNOW_IF_THE_RESULT_IS_EMPTY) { // kdbDebug() << "READ AHEAD:"; d->readAhead = getNextRecord(); //true if any record in this query // kdbDebug() << "READ AHEAD = " << d->readAhead; } m_at = 0; //we are still before 1st rec return !m_result.isError(); } bool KDbCursor::close() { if (!d->opened) { return true; } bool ret = drv_close(); clearBuffer(); d->opened = false; m_afterLast = false; d->readAhead = false; m_fieldCount = 0; m_fieldsToStoreInRecord = 0; m_logicalFieldCount = 0; m_at = -1; // kdbDebug() << ret; return ret; } bool KDbCursor::reopen() { if (!d->opened) { return open(); } return close() && open(); } bool KDbCursor::moveFirst() { if (!d->opened) { return false; } if (!d->readAhead) { if (m_options & KDbCursor::Option::Buffered) { if (m_records_in_buf == 0 && m_buffering_completed) { //eof and bof should now return true: m_afterLast = true; m_at = 0; return false; //buffering completed and there is no records! } if (m_records_in_buf > 0) { //set state as we would be before first rec: d->atBuffer = false; m_at = 0; //..and move to next, i.e. 1st record m_afterLast = !getNextRecord(); return !m_afterLast; } } else if (!(d->conn->driver()->behavior()->_1ST_ROW_READ_AHEAD_REQUIRED_TO_KNOW_IF_THE_RESULT_IS_EMPTY)) { // not buffered m_at = 0; m_afterLast = !getNextRecord(); return !m_afterLast; } if (m_afterLast && m_at == 0) //failure if already no records return false; if (!reopen()) //try reopen return false; if (m_afterLast) //eof return false; } else { //we have a record already read-ahead: we now point @ that: m_at = 1; } //get first record m_afterLast = false; d->readAhead = false; //1st record had been read return d->validRecord; } bool KDbCursor::moveLast() { if (!d->opened) { return false; } if (m_afterLast || d->atLast) { return d->validRecord; //we already have valid last record retrieved } if (!getNextRecord()) { //at least next record must be retrieved m_afterLast = true; d->validRecord = false; d->atLast = false; return false; //no records } while (getNextRecord()) //move after last rec. ; m_afterLast = false; //cursor shows last record data d->atLast = true; return true; } bool KDbCursor::moveNext() { if (!d->opened || m_afterLast) { return false; } if (getNextRecord()) { return true; } return false; } bool KDbCursor::movePrev() { if (!d->opened /*|| m_beforeFirst*/ || !(m_options & KDbCursor::Option::Buffered)) { return false; } //we're after last record and there are records in the buffer //--let's move to last record if (m_afterLast && (m_records_in_buf > 0)) { drv_bufferMovePointerTo(m_records_in_buf - 1); m_at = m_records_in_buf; d->atBuffer = true; //now current record is stored in the buffer d->validRecord = true; m_afterLast = false; return true; } //we're at first record: go BOF if ((m_at <= 1) || (m_records_in_buf <= 1/*sanity*/)) { m_at = 0; d->atBuffer = false; d->validRecord = false; return false; } m_at--; if (d->atBuffer) {//we already have got a pointer to buffer drv_bufferMovePointerPrev(); //just move to prev record in the buffer } else {//we have no pointer //compute a place in the buffer that contain next record's data drv_bufferMovePointerTo(m_at - 1); d->atBuffer = true; //now current record is stored in the buffer } d->validRecord = true; m_afterLast = false; return true; } bool KDbCursor::isBuffered() const { return m_options & KDbCursor::Option::Buffered; } void KDbCursor::setBuffered(bool buffered) { if (!d->opened) { return; } if (isBuffered() == buffered) return; m_options ^= KDbCursor::Option::Buffered; } void KDbCursor::clearBuffer() { if (!isBuffered() || m_fieldCount == 0) return; drv_clearBuffer(); m_records_in_buf = 0; d->atBuffer = false; } bool KDbCursor::getNextRecord() { m_fetchResult = FetchInvalid; //by default: invalid result of record fetching if (m_options & KDbCursor::Option::Buffered) {//this cursor is buffered: // kdbDebug() << "m_at < m_records_in_buf :: " << (long)m_at << " < " << m_records_in_buf; if (m_at < m_records_in_buf) {//we have next record already buffered: if (d->atBuffer) {//we already have got a pointer to buffer drv_bufferMovePointerNext(); //just move to next record in the buffer } else {//we have no pointer //compute a place in the buffer that contain next record's data drv_bufferMovePointerTo(m_at - 1 + 1); d->atBuffer = true; //now current record is stored in the buffer } } else {//we are after last retrieved record: we need to physically fetch next record: if (!d->readAhead) {//we have no record that was read ahead if (!m_buffering_completed) { //retrieve record only if we are not after //the last buffer's item (i.e. when buffer is not fully filled): // kdbDebug()<<"==== buffering: drv_getNextRecord() ===="; drv_getNextRecord(); } if (m_fetchResult != FetchOK) {//there is no record m_buffering_completed = true; //no more records for buffer // kdbDebug()<<"m_fetchResult != FetchOK ********"; d->validRecord = false; m_afterLast = true; m_at = -1; //position is invalid now and will not be used if (m_fetchResult == FetchError) { m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Could not fetch next record.")); return false; } return false; // in case of m_fetchResult = FetchEnd or m_fetchResult = FetchInvalid } //we have a record: store this record's values in the buffer drv_appendCurrentRecordToBuffer(); m_records_in_buf++; } else //we have a record that was read ahead: eat this d->readAhead = false; } } else {//we are after last retrieved record: we need to physically fetch next record: if (!d->readAhead) {//we have no record that was read ahead // kdbDebug()<<"==== no prefetched record ===="; drv_getNextRecord(); if (m_fetchResult != FetchOK) {//there is no record // kdbDebug()<<"m_fetchResult != FetchOK ********"; d->validRecord = false; m_afterLast = true; m_at = -1; if (m_fetchResult == FetchEnd) { return false; } m_result = KDbResult(ERR_CURSOR_RECORD_FETCHING, tr("Could not fetch next record.")); return false; } } else { //we have a record that was read ahead: eat this d->readAhead = false; } } m_at++; // if (m_data->curr_colname && m_data->curr_coldata) // for (int i=0;icurr_cols;i++) { // kdbDebug()<curr_colname[i]<<" == "<< m_data->curr_coldata[i]; // } // kdbDebug()<<"m_at == "<<(long)m_at; d->validRecord = true; return true; } bool KDbCursor::updateRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->updateRecord(m_query, data, buf, useRecordId); } bool KDbCursor::insertRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! if (!m_query) { clearResult(); return false; } return d->conn->insertRecord(m_query, data, buf, useRecordId); } bool KDbCursor::deleteRecord(KDbRecordData* data, bool useRecordId) { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->deleteRecord(m_query, data, useRecordId); } bool KDbCursor::deleteAllRecords() { //! @todo doesn't update cursor's buffer YET! clearResult(); if (!m_query) return false; return d->conn->deleteAllRecords(m_query); } -QDebug operator<<(QDebug dbg, const KDbCursor& cursor) +QDebug debug(QDebug dbg, KDbCursor& cursor, bool buildSql) { dbg.nospace() << "CURSOR("; if (!cursor.query()) { dbg.nospace() << "RAW SQL STATEMENT:" << cursor.rawSql().toString() << "\n"; } - else { + else if (buildSql) { KDbNativeStatementBuilder builder(cursor.connection()); KDbEscapedString sql; QString sqlString; if (builder.generateSelectStatement(&sql, cursor.query())) { sqlString = sql.toString(); } else { sqlString = QLatin1String(""); } dbg.nospace() << "KDbQuerySchema:" << sqlString << "\n"; } if (cursor.isOpened()) { dbg.space() << "OPENED"; } else { dbg.space() << "NOT_OPENED"; } if (cursor.isBuffered()) { dbg.space() << "BUFFERED"; } else { dbg.space() << "NOT_BUFFERED"; } dbg.nospace() << "AT=" << cursor.at() << ")"; return dbg.space(); } +QDebug operator<<(QDebug dbg, KDbCursor &cursor) +{ + return debug(dbg, cursor, true /*buildSql*/); +} + +QDebug operator<<(QDebug dbg, const KDbCursor &cursor) +{ + return debug(dbg, const_cast(cursor), false /* !buildSql*/); +} + void KDbCursor::setOrderByColumnList(const QStringList& columnNames) { Q_UNUSED(columnNames); //! @todo implement this: all field names should be found, exit otherwise // OK //! @todo if (!d->orderByColumnList) } /*! Convenience method, similar to setOrderBy(const QStringList&). */ void KDbCursor::setOrderByColumnList(const QString& column1, const QString& column2, const QString& column3, const QString& column4, const QString& column5) { Q_UNUSED(column1); Q_UNUSED(column2); Q_UNUSED(column3); Q_UNUSED(column4); Q_UNUSED(column5); //! @todo implement this, like above //! @todo add ORDER BY info to debugString() } KDbQueryColumnInfo::Vector KDbCursor::orderByColumnList() const { return d->orderByColumnList; } QList KDbCursor::queryParameters() const { return d->queryParameters; } void KDbCursor::setQueryParameters(const QList& params) { d->queryParameters = params; } //! @todo extraMessages #if 0 static const char *extraMessages[] = { QT_TRANSLATE_NOOP("KDbCursor", "No connection for cursor open operation specified.") }; #endif diff --git a/src/KDbCursor.h b/src/KDbCursor.h index 48b7eaa7..0ad1c0fc 100644 --- a/src/KDbCursor.h +++ b/src/KDbCursor.h @@ -1,336 +1,344 @@ /* This file is part of the KDE project Copyright (C) 2003-2016 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_CURSOR_H #define KDB_CURSOR_H #include #include #include "KDbResult.h" #include "KDbQueryColumnInfo.h" class KDbConnection; class KDbRecordData; class KDbQuerySchema; class KDbRecordEditBuffer; //! Provides database cursor functionality. /*! Cursor can be defined in two ways: -# by passing KDbQuerySchema object to KDbConnection::executeQuery() or KDbConnection::prepareQuery(); then query is defined for in engine-independent way -- this is recommended usage -# by passing raw query statement string to KDbConnection::executeQuery() or KDbConnection::prepareQuery(); then query may be defined for in engine-dependent way -- this is not recommended usage, but convenient when we can't or do not want to allocate KDbQuerySchema object, while we know that the query statement is syntactically and logically ok in our context. You can move cursor to next record with moveNext() and move back with movePrev(). The cursor is always positioned on record, not between records, with exception that after open() it is positioned before the first record (if any) -- then bof() equals true. The cursor can also be positioned after the last record (if any) with moveNext() -- then eof() equals true. For example, if you have four records, 1, 2, 3, 4, then after calling open(), moveNext(), moveNext(), moveNext(), movePrev() you are going through records: 1, 2, 3, 2. Cursor can be buffered or unbuferred. @warning Buffered cursors are not implemented! Buffering in this class is not related to any SQL engine capatibilities for server-side cursors (eg. like 'DECLARE CURSOR' statement) - buffered data is at client (application) side. Any record retrieved in buffered cursor will be stored inside an internal buffer and reused when needed. Unbuffered cursor always requires one record fetching from db connection at every step done with moveNext(), movePrev(), etc. Notes: - Do not use delete operator for KDbCursor objects - this will fail; use KDbConnection::deleteCursor() instead. - KDbQuerySchema object is not owned by KDbCursor object that uses it. */ class KDB_EXPORT KDbCursor: public KDbResultable { Q_DECLARE_TR_FUNCTIONS(KDbCursor) public: //! Options that describe behavior of database cursor enum class Option { None = 0, Buffered = 1 }; Q_DECLARE_FLAGS(Options, Option) /*! @return connection used for the cursor */ - KDbConnection* connection() const; + KDbConnection* connection(); + + //! @overload + //! @since 3.1 + const KDbConnection* connection() const; /*! Opens the cursor using data provided on creation. The data might be either KDbQuerySchema or a raw SQL statement. */ bool open(); /*! Closes and then opens again the same cursor. If the cursor is not opened it is just opened and result of this open is returned. Otherwise, true is returned if cursor is successfully closed and then opened. */ bool reopen(); /*! Closes previously opened cursor. If the cursor is closed, nothing happens. */ virtual bool close(); /*! @return query schema used to define this cursor or 0 if the cursor is not defined by a query schema but by a raw SQL statement. */ KDbQuerySchema *query() const; //! @return query parameters assigned to this cursor QList queryParameters() const; //! Sets query parameters @a params for this cursor. void setQueryParameters(const QList& params); /*! @return raw query statement used to define this cursor or null string if raw statement instead (but KDbQuerySchema is defined instead). */ KDbEscapedString rawSql() const; /*! @return cursor options */ Options options() const; /*! @return true if the cursor is opened. */ bool isOpened() const; /*! @return true if the cursor is buffered. */ bool isBuffered() const; /*! Sets this cursor to buffered type or not. See description of buffered and nonbuffered cursors in class description. This method only works if cursor is not opened (isOpened()==false). You can close already opened cursor and then switch this option on/off. */ void setBuffered(bool buffered); /*! Moves current position to the first record and retrieves it. @return true if the first record was retrieved. False could mean that there was an error or there is no record available. */ bool moveFirst(); /*! Moves current position to the last record and retrieves it. @return true if the last record was retrieved. False could mean that there was an error or there is no record available. */ virtual bool moveLast(); /*! Moves current position to the next record and retrieves it. */ virtual bool moveNext(); /*! Moves current position to the next record and retrieves it. Currently it's only supported for buffered cursors. */ virtual bool movePrev(); /*! @return true if current position is after last record. */ inline bool eof() const { return m_afterLast; } /*! @return true if current position is before first record. */ inline bool bof() const { return m_at == 0; } /*! @return current internal position of the cursor's query. We are counting records from 0. Value -1 means that cursor does not point to any valid record (this happens eg. after open(), close(), and after moving after last record or before first one. */ inline qint64 at() const { return readAhead() ? 0 : (m_at - 1); } /*! @return number of fields available for this cursor. This never includes ROWID column or other internal columns (e.g. lookup). */ inline int fieldCount() const { return m_query ? m_logicalFieldCount : m_fieldCount; } /*! @return true if ROWID information is available for each record. ROWID information is available if KDbDriverBehavior::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE == false for a KDb database driver and the master table has no primary key defined. Phisically, ROWID value is returned after last returned field, so data vector's length is expanded by one. */ bool containsRecordIdInfo() const; /*! @return a value stored in column number @a i (counting from 0). It has unspecified behavior if the cursor is not at valid record. Note for driver developers: If @a i is >= than m_fieldCount, null QVariant value should be returned. To return a value typically you can use a pointer to internal structure that contain current record data (buffered or unbuffered). */ virtual QVariant value(int i) = 0; /*! [PROTOTYPE] @return current record data or @c nullptr if there is no current records. */ virtual const char ** recordData() const = 0; /*! Sets a list of columns for ORDER BY section of the query. Only works when the cursor has been created using KDbQuerySchema object (i.e. when query()!=0; does not work with raw statements). Each name on the list must be a field or alias present within the query and must not be covered by aliases. If one or more names cannot be found within the query, the method will have no effect. Any previous ORDER BY settings will be removed. The order list provided here has priority over a list defined in the KDbQuerySchema object itseld (using KDbQuerySchema::setOrderByColumnList()). The KDbQuerySchema object itself is not modifed by this method: only order of records retrieved by this cursor is affected. Use this method before calling open(). You can also call reopen() after calling this method to see effects of applying records order. */ //! @todo implement this void setOrderByColumnList(const QStringList& columnNames); /*! Convenience method, similar to setOrderByColumnList(const QStringList&). */ //! @todo implement this void setOrderByColumnList(const QString& column1, const QString& column2 = QString(), const QString& column3 = QString(), const QString& column4 = QString(), const QString& column5 = QString()); /*! @return a list of fields contained in ORDER BY section of the query. @see setOrderBy(const QStringList&) */ KDbQueryColumnInfo::Vector orderByColumnList() const; /*! Allocates a new KDbRecordData and stores data in it (makes a deep copy of each field). If the cursor is not at valid record, the result is undefined. @return newly created record data object or 0 on error. */ KDbRecordData* storeCurrentRecord() const; /*! Puts current record's data into @a data (makes a deep copy of each field). If the cursor is not at valid record, the result is undefined. @return true on success. @c false is returned if @a data is @c nullptr. */ bool storeCurrentRecord(KDbRecordData* data) const; bool updateRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool useRecordId = false); bool insertRecord(KDbRecordData* data, KDbRecordEditBuffer* buf, bool getRecrordId = false); bool deleteRecord(KDbRecordData* data, bool useRecordId = false); bool deleteAllRecords(); protected: /*! Cursor will operate on @a conn, raw SQL statement @a sql will be used to execute query. */ KDbCursor(KDbConnection* conn, const KDbEscapedString& sql, Options options = KDbCursor::Option::None); /*! Cursor will operate on @a conn, @a query schema will be used to execute query. */ KDbCursor(KDbConnection* conn, KDbQuerySchema* query, Options options = KDbCursor::Option::None); ~KDbCursor() override; void init(KDbConnection* conn); /*! Internal: cares about proper flag setting depending on result of drv_getNextRecord() and depending on wherher a cursor is buffered. */ bool getNextRecord(); /*! Note for driver developers: this method should initialize engine-specific cursor's resources using an SQL statement @a sql. It is not required to store @a sql statement somewhere in your KDbCursor subclass (it is already stored in m_query or m_rawStatement, depending query type) - only pass it to proper engine's function. */ virtual bool drv_open(const KDbEscapedString& sql) = 0; virtual bool drv_close() = 0; virtual void drv_getNextRecord() = 0; /*! Stores currently fetched record's values in appropriate place of the buffer. Note for driver developers: This place can be computed using m_at. Do not change value of m_at or any other KDbCursor members, only change your internal structures like pointer to current record, etc. If your database engine's API function (for record fetching) do not allocates such a space, you want to allocate a space for current record. Otherwise, reuse existing structure, what could be more efficient. All functions like drv_appendCurrentRecordToBuffer() operates on the buffer, i.e. array of stored records. You are not forced to have any particular fixed structure for buffer item or buffer itself - the structure is internal and only methods like storeCurrentRecord() visible to public. */ virtual void drv_appendCurrentRecordToBuffer() = 0; /*! Moves pointer (that points to the buffer) -- to next item in this buffer. Note for driver developers: probably just execute "your_pointer++" is enough. */ virtual void drv_bufferMovePointerNext() = 0; /*! Like drv_bufferMovePointerNext() but execute "your_pointer--". */ virtual void drv_bufferMovePointerPrev() = 0; /*! Moves pointer (that points to the buffer) to a new place: @a at. */ virtual void drv_bufferMovePointerTo(qint64 at) = 0; /*! Clears cursor's buffer if this was allocated (only for buffered cursor type). Otherwise do nothing. For reimplementing. Default implementation does nothing. */ virtual void drv_clearBuffer() {} //! @internal clears buffer with reimplemented drv_clearBuffer(). */ void clearBuffer(); /*! Puts current record's data into @a data (makes a deep copy of each field). This method has unspecified behavior if the cursor is not at valid record. @return true on success. Note: For reimplementation in driver's code. Shortly, this method translates a record data from internal representation (probably also used in buffer) to simple public KDbRecordData representation. */ virtual bool drv_storeCurrentRecord(KDbRecordData* data) const = 0; KDbQuerySchema *m_query; bool m_afterLast; qint64 m_at; int m_fieldCount; //!< cached field count information int m_fieldsToStoreInRecord; //!< Used by storeCurrentRecord(), reimplement if needed //!< (e.g. PostgreSQL driver, when m_containsRecordIdInfo is true //!< sets m_fieldCount+1 here) int m_logicalFieldCount; //!< logical field count, i.e. without intrernal values like Record Id or lookup KDbCursor::Options m_options; //!< cursor options that describes its behavior //! possible results of record fetching, used for m_fetchResult enum FetchResult { FetchInvalid, //!< used before starting the fetching, result is not known yet FetchError, //!< error of fetching FetchOK, //!< the data is fetched FetchEnd //!< at the end of data }; FetchResult m_fetchResult; //!< result of a record fetching // int m_records_in_buf; //!< number of records currently stored in the buffer bool m_buffering_completed; //!< true if we already have all records stored in the buffer // //! Useful e.g. for value(int) method to obtain access to schema definition. KDbQueryColumnInfo::Vector* m_visibleFieldsExpanded; private: bool readAhead() const; Q_DISABLE_COPY(KDbCursor) friend class CursorDeleter; class Private; Private * const d; }; +//! Sends information about object @a cursor to debug output @a dbg. +//! @since 3.1 +KDB_EXPORT QDebug operator<<(QDebug dbg, KDbCursor& cursor); + //! Sends information about object @a cursor to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbCursor& cursor); Q_DECLARE_OPERATORS_FOR_FLAGS(KDbCursor::Options) #endif diff --git a/src/KDbField.cpp b/src/KDbField.cpp index 968c6279..72e14486 100644 --- a/src/KDbField.cpp +++ b/src/KDbField.cpp @@ -1,1046 +1,1056 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2002 Joseph Wenninger Copyright (C) 2003-2017 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbField.h" #include "KDbField_p.h" #include "KDbConnection.h" #include "KDbDriver.h" #include "KDbExpression.h" #include "KDbQuerySchema.h" #include "KDb.h" #include "kdb_debug.h" #include //! @todo make this configurable static int g_defaultMaxLength = 0; // unlimited //------------------------------------------------------- //! @internal Used in s_typeNames member to handle translated type names class FieldTypeNames { public: FieldTypeNames(); QVector data; QHash str2num; QStringList names; private: Q_DISABLE_COPY(FieldTypeNames) }; //! @internal Used in m_typeGroupNames member to handle translated type group names class FieldTypeGroupNames { public: FieldTypeGroupNames(); QVector data; QHash str2num; QStringList names; private: Q_DISABLE_COPY(FieldTypeGroupNames) }; //! real translated type names (and nontranslated type name strings) Q_GLOBAL_STATIC(FieldTypeNames, s_typeNames) //! real translated type group names (and nontranslated group name strings) Q_GLOBAL_STATIC(FieldTypeGroupNames, s_typeGroupNames) #define ADDTYPE(type, i18, str) \ data[KDbField::type] = i18; \ data[KDbField::type+KDbField::Null+1] = QStringLiteral(str); \ str2num[ QString::fromLatin1(str).toLower() ] = KDbField::type; \ names.append(i18) #define ADDGROUP(type, i18, str) \ data[KDbField::type] = i18; \ data[KDbField::type+KDbField::LastTypeGroup+1] = QStringLiteral(str); \ str2num[ QString::fromLatin1(str).toLower() ] = KDbField::type; \ names.append(i18) FieldTypeNames::FieldTypeNames() : data((KDbField::Null + 1)*2) { ADDTYPE(InvalidType, KDbField::tr("Invalid Type"), "InvalidType"); ADDTYPE(Byte, KDbField::tr("Byte"), "Byte"); ADDTYPE(ShortInteger, KDbField::tr("Short Integer Number"), "ShortInteger"); ADDTYPE(Integer, KDbField::tr("Integer Number"), "Integer"); ADDTYPE(BigInteger, KDbField::tr("Big Integer Number"), "BigInteger"); ADDTYPE(Boolean, KDbField::tr("Yes/No Value"), "Boolean"); ADDTYPE(Date, KDbField::tr("Date"), "Date"); ADDTYPE(DateTime, KDbField::tr("Date and Time"), "DateTime"); ADDTYPE(Time, KDbField::tr("Time"), "Time"); ADDTYPE(Float, KDbField::tr("Single Precision Number"), "Float"); ADDTYPE(Double, KDbField::tr("Double Precision Number"), "Double"); ADDTYPE(Text, KDbField::tr("Text"), "Text"); ADDTYPE(LongText, KDbField::tr("Long Text"), "LongText"); ADDTYPE(BLOB, KDbField::tr("Object"), "BLOB"); ADDTYPE(Null, QLatin1String("NULL")/*don't translate*/, "NULL"); } //------------------------------------------------------- FieldTypeGroupNames::FieldTypeGroupNames() : data((KDbField::LastTypeGroup + 1)*2) { ADDGROUP(InvalidGroup, KDbField::tr("Invalid Group"), "InvalidGroup"); ADDGROUP(TextGroup, KDbField::tr("Text"), "TextGroup"); ADDGROUP(IntegerGroup, KDbField::tr("Integer Number"), "IntegerGroup"); ADDGROUP(FloatGroup, KDbField::tr("Floating Point Number"), "FloatGroup"); ADDGROUP(BooleanGroup, KDbField::tr("Yes/No"), "BooleanGroup"); ADDGROUP(DateTimeGroup, KDbField::tr("Date/Time"), "DateTimeGroup"); ADDGROUP(BLOBGroup, KDbField::tr("Object"), "BLOBGroup"); } //------------------------------------------------------- +class KDbFieldPrivate +{ +public: + static KDbConnection *connection(const KDbTableSchema &table) + { + return table.connection(); + } +}; + + class Q_DECL_HIDDEN KDbField::Private { public: Private(KDbFieldList *aParent = nullptr, int aOrder = -1) : parent(aParent) , type(KDbField::InvalidType) , precision(0) , options(KDbField::NoOptions) , defaultValue(QString()) , order(aOrder) { } Private(const QString &aName, KDbField::Type aType, KDbField::Options aOptions, int aPrecision, const QVariant &aDefaultValue, const QString &aCaption, const QString &aDescription) : parent(nullptr) , type(aType) , name(aName) , caption(aCaption) , description(aDescription) , precision(aPrecision) , options(aOptions) , defaultValue(aDefaultValue) , order(-1) { } Private(const Private &o) { (*this) = o; if (o.customProperties) { customProperties = new CustomPropertiesMap(*o.customProperties); } if (!o.expr.isNull()) {//deep copy the expression //! @todo expr = new KDbExpression(o.expr); expr = KDbExpression(o.expr.clone()); } else { expr = KDbExpression(); } } ~Private() { delete customProperties; } //! In most cases this points to a KDbTableSchema object that field is assigned KDbFieldList *parent; KDbField::Type type; QString name; QString caption; QString description; QString subType; KDbField::Constraints constraints; KDbField::MaxLengthStrategy maxLengthStrategy; int maxLength; //!< also used for storing scale for floating point types int precision; int visibleDecimalPlaces = -1; //!< used in visibleDecimalPlaces() KDbField::Options options; QVariant defaultValue; int order; KDbExpression expr; KDbField::CustomPropertiesMap* customProperties = nullptr; QVector hints; }; //------------------------------------------------------- KDbField::KDbField() : d(new Private) { setMaxLength(0); // do not move this line up! setMaxLengthStrategy(DefinedMaxLength); // do not move this line up! setConstraints(NoConstraints); } KDbField::KDbField(KDbFieldList *aParent, int aOrder) : d(new Private(aParent, aOrder)) { setMaxLength(0); // do not move this line up! setMaxLengthStrategy(DefinedMaxLength); // do not move this line up! setConstraints(NoConstraints); } KDbField::KDbField(KDbTableSchema *tableSchema) : KDbField(tableSchema, tableSchema->fieldCount()) { } KDbField::KDbField(KDbQuerySchema *querySchema, const KDbExpression& expr) : KDbField(querySchema, querySchema->fieldCount()) { setExpression(expr); } KDbField::KDbField(KDbQuerySchema *querySchema) : KDbField(querySchema, querySchema->fieldCount()) { } KDbField::KDbField(const QString &name, Type type, Constraints constr, Options options, int maxLength, int precision, const QVariant &defaultValue, const QString &caption, const QString &description) : d(new Private(name, type, options, precision, defaultValue, caption, description)) { setMaxLength(maxLength); setConstraints(constr); } /*! Copy constructor. */ KDbField::KDbField(const KDbField &f) : d(new Private(*f.d)) { } KDbField::~KDbField() { delete d; } KDbFieldList *KDbField::parent() { return d->parent; } const KDbFieldList *KDbField::parent() const { return d->parent; } void KDbField::setParent(KDbFieldList *parent) { d->parent = parent; } QString KDbField::name() const { return d->name; } KDbField::Options KDbField::options() const { return d->options; } void KDbField::setOptions(Options options) { d->options = options; } QString KDbField::subType() const { return d->subType; } void KDbField::setSubType(const QString& subType) { d->subType = subType; } QVariant KDbField::defaultValue() const { return d->defaultValue; } int KDbField::precision() const { return d->precision; } int KDbField::scale() const { return d->maxLength; } int KDbField::visibleDecimalPlaces() const { return d->visibleDecimalPlaces; } KDbField::Constraints KDbField::constraints() const { return d->constraints; } int KDbField::order() const { return d->order; } void KDbField::setOrder(int order) { d->order = order; } QString KDbField::caption() const { return d->caption; } void KDbField::setCaption(const QString& caption) { d->caption = caption; } QString KDbField::captionOrName() const { return d->caption.isEmpty() ? d->name : d->caption; } QString KDbField::description() const { return d->description; } void KDbField::setDescription(const QString& description) { d->description = description; } QVector KDbField::enumHints() const { return d->hints; } QString KDbField::enumHint(int num) { return (num < d->hints.size()) ? d->hints.at(num) : QString(); } void KDbField::setEnumHints(const QVector &hints) { d->hints = hints; } // static int KDbField::typesCount() { return LastType - InvalidType + 1; } // static int KDbField::specialTypesCount() { return LastSpecialType - Null + 1; } // static int KDbField::typeGroupsCount() { return LastTypeGroup - InvalidGroup + 1; } KDbField* KDbField::copy() { return new KDbField(*this); } KDbField::Type KDbField::type() const { if (!d->expr.isNull()) { return d->expr.type(); } return d->type; } QVariant::Type KDbField::variantType(Type type) { switch (type) { case Byte: case ShortInteger: case Integer: case BigInteger: return QVariant::Int; case Boolean: return QVariant::Bool; case Date: return QVariant::Date; case DateTime: return QVariant::DateTime; case Time: return QVariant::Time; case Float: case Double: return QVariant::Double; case Text: case LongText: return QVariant::String; case BLOB: return QVariant::ByteArray; default: break; } return QVariant::Invalid; } template static inline QVariant tryConvert(const QVariant &value) { return value.canConvert() ? value.value() : value; } //static //! @todo use an array of functions? QVariant KDbField::convertToType(const QVariant &value, Type type) { switch (type) { case Byte: case ShortInteger: case Integer: return tryConvert(value); case BigInteger: return tryConvert(value); case Boolean: return tryConvert(value); case Date: return tryConvert(value); case DateTime: return tryConvert(value); case Time: return tryConvert(value); case Float: return tryConvert(value); case Double: return tryConvert(value); case Text: case LongText: return tryConvert(value); case BLOB: return tryConvert(value); default: break; } return QVariant(); } QString KDbField::typeName(Type type) { return s_typeNames->data.value(type, QString::number(type)); } QStringList KDbField::typeNames() { return s_typeNames->names; } QString KDbField::typeString(Type type) { return (type <= Null) ? s_typeNames->data.at(int(Null) + 1 + type) : (QLatin1String("Type") + QString::number(type)); } QString KDbField::typeGroupName(TypeGroup typeGroup) { return (typeGroup <= LastTypeGroup) ? s_typeGroupNames->data.at(typeGroup) : typeGroupString(typeGroup); } QStringList KDbField::typeGroupNames() { return s_typeGroupNames->names; } QString KDbField::typeGroupString(TypeGroup typeGroup) { return s_typeGroupNames->data.value(int(LastTypeGroup) + 1 + typeGroup, QLatin1String("TypeGroup") + QString::number(typeGroup)); } KDbField::Type KDbField::typeForString(const QString& typeString) { return s_typeNames->str2num.value(typeString.toLower(), InvalidType); } KDbField::TypeGroup KDbField::typeGroupForString(const QString& typeGroupString) { return s_typeGroupNames->str2num.value(typeGroupString.toLower(), InvalidGroup); } bool KDbField::isIntegerType(Type type) { switch (type) { case KDbField::Byte: case KDbField::ShortInteger: case KDbField::Integer: case KDbField::BigInteger: return true; default:; } return false; } bool KDbField::isNumericType(Type type) { switch (type) { case KDbField::Byte: case KDbField::ShortInteger: case KDbField::Integer: case KDbField::BigInteger: case KDbField::Float: case KDbField::Double: return true; default:; } return false; } bool KDbField::isFPNumericType(Type type) { return type == KDbField::Float || type == KDbField::Double; } bool KDbField::isDateTimeType(Type type) { switch (type) { case KDbField::Date: case KDbField::DateTime: case KDbField::Time: return true; default:; } return false; } bool KDbField::isTextType(Type type) { switch (type) { case KDbField::Text: case KDbField::LongText: return true; default:; } return false; } bool KDbField::hasEmptyProperty(Type type) { return KDbField::isTextType(type) || type == BLOB; } bool KDbField::isAutoIncrementAllowed(Type type) { return KDbField::isIntegerType(type); } KDbField::TypeGroup KDbField::typeGroup(Type type) { if (KDbField::isTextType(type)) return TextGroup; else if (KDbField::isIntegerType(type)) return IntegerGroup; else if (KDbField::isFPNumericType(type)) return FloatGroup; else if (type == Boolean) return BooleanGroup; else if (KDbField::isDateTimeType(type)) return DateTimeGroup; else if (type == BLOB) return BLOBGroup; return InvalidGroup; //unknown } KDbTableSchema* KDbField::table() { return dynamic_cast(d->parent); } const KDbTableSchema* KDbField::table() const { return dynamic_cast(d->parent); } void KDbField::setTable(KDbTableSchema *tableSchema) { d->parent = tableSchema; } KDbQuerySchema* KDbField::query() { return dynamic_cast(d->parent); } const KDbQuerySchema* KDbField::query() const { return dynamic_cast(d->parent); } void KDbField::setQuery(KDbQuerySchema *querySchema) { d->parent = querySchema; } void KDbField::setName(const QString& name) { d->name = name.toLower(); } void KDbField::setType(Type t) { if (!d->expr.isNull()) { kdbWarning() << "Could not set type" << KDbField::typeName(t) << "because the field has expression assigned!"; return; } d->type = t; } void KDbField::setConstraints(Constraints c) { d->constraints = c; //pkey must be unique notnull if (isPrimaryKey()) { setPrimaryKey(true); } if (isIndexed()) { setIndexed(true); } if (isAutoIncrement() && !isAutoIncrementAllowed()) { setAutoIncrement(false); } } int KDbField::defaultMaxLength() { return g_defaultMaxLength; } void KDbField::setDefaultMaxLength(int maxLength) { g_defaultMaxLength = maxLength; } KDbField::MaxLengthStrategy KDbField::maxLengthStrategy() const { return d->maxLengthStrategy; } void KDbField::setMaxLengthStrategy(MaxLengthStrategy strategy) { d->maxLengthStrategy = strategy; } int KDbField::maxLength() const { return d->maxLength; } void KDbField::setMaxLength(int maxLength) { d->maxLength = maxLength; d->maxLengthStrategy = DefinedMaxLength; } void KDbField::setPrecision(int p) { if (!isFPNumericType()) { return; } d->precision = p; } void KDbField::setScale(int s) { if (!isFPNumericType()) { return; } d->maxLength = s; } void KDbField::setVisibleDecimalPlaces(int p) { if (!KDb::supportsVisibleDecimalPlacesProperty(type())) { return; } d->visibleDecimalPlaces = p < 0 ? -1 : p; } void KDbField::setUnsigned(bool u) { if (!isIntegerType()) { return; } d->options |= Unsigned; if (!u) { d->options ^= Unsigned; } } void KDbField::setDefaultValue(const QVariant& def) { d->defaultValue = def; } bool KDbField::setDefaultValue(const QByteArray& def) { if (def.isNull()) { d->defaultValue = QVariant(); return true; } bool ok; switch (type()) { case Byte: { unsigned int v = def.toUInt(&ok); if (!ok || v > 255) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(v); } break; } case ShortInteger: { int v = def.toInt(&ok); if (!ok || (!(d->options & Unsigned) && (v < -32768 || v > 32767)) || ((d->options & Unsigned) && (v < 0 || v > 65535))) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(v); } break; } case Integer: {//4 bytes long v = def.toLong(&ok); //! @todo if (!ok || (!(d->options & Unsigned) && (-v > 0x080000000 || v > //! (0x080000000-1))) || ((d->options & Unsigned) && (v < 0 || v > 0x100000000))) if (!ok || (!(d->options & Unsigned) && (-v > (int)0x07FFFFFFF || v > (int)(0x080000000 - 1)))) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant((qint64)v); } break; } case BigInteger: {//8 bytes //! @todo BigInteger support /* qint64 long v = def.toLongLong(&ok); //! @todo 2-part decoding if (!ok || (!(d->options & Unsigned) && (-v > 0x080000000 || v > (0x080000000-1)))) d->defaultValue = QVariant(); else if (d->options & Unsigned) d->defaultValue=QVariant((quint64) v); else d->defaultValue = QVariant((qint64)v);*/ break; } case Boolean: { unsigned short v = def.toUShort(&ok); if (!ok || v > 1) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant((bool)v); } break; } case Date: {//YYYY-MM-DD QDate date = QDate::fromString(QLatin1String(def), Qt::ISODate); if (!date.isValid()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(date); } break; } case DateTime: {//YYYY-MM-DDTHH:MM:SS QDateTime dt = QDateTime::fromString(QLatin1String(def), Qt::ISODate); if (!dt.isValid()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(dt); } break; } case Time: {//HH:MM:SS QTime time = QTime::fromString(QLatin1String(def), Qt::ISODate); if (!time.isValid()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(time); } break; } case Float: { float v = def.toFloat(&ok); if (!ok || ((d->options & Unsigned) && (v < 0.0))) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(v); } break; } case Double: { double v = def.toDouble(&ok); if (!ok || ((d->options & Unsigned) && (v < 0.0))) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(v); } break; } case Text: { if (def.isNull() || def.length() > maxLength()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(QLatin1String(def)); } break; } case LongText: { if (def.isNull()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(QLatin1String(def)); } break; } case BLOB: { //! @todo if (def.isNull()) { d->defaultValue = QVariant(); } else { d->defaultValue = QVariant(def); } break; } default: d->defaultValue = QVariant(); } return d->defaultValue.isNull(); } void KDbField::setAutoIncrement(bool a) { if (a && !isAutoIncrementAllowed()) { return; } if (isAutoIncrement() != a) { d->constraints ^= KDbField::AutoInc; } } void KDbField::setPrimaryKey(bool p) { if (isPrimaryKey() != p) { d->constraints ^= KDbField::PrimaryKey; } if (p) {//also set implied constraints setUniqueKey(true); setNotNull(true); setNotEmpty(true); setIndexed(true); } else { //! @todo is this ok for all engines? setAutoIncrement(false); } } void KDbField::setUniqueKey(bool u) { if (isUniqueKey() != u) { d->constraints ^= KDbField::Unique; if (u) { //also set implied constraints setNotNull(true); setIndexed(true); } } } void KDbField::setForeignKey(bool f) { if (isForeignKey() != f) { d->constraints ^= KDbField::ForeignKey; } } void KDbField::setNotNull(bool n) { if (isNotNull() != n) { d->constraints ^=KDbField::NotNull; } } void KDbField::setNotEmpty(bool n) { if (isNotEmpty() != n) { d->constraints ^= KDbField::NotEmpty; } } void KDbField::setIndexed(bool s) { if (isIndexed() != s) { d->constraints ^= KDbField::Indexed; } if (!s) {//also set implied constraints setPrimaryKey(false); setUniqueKey(false); setNotNull(false); setNotEmpty(false); } } void debug(QDebug dbg, const KDbField& field, KDbFieldDebugOptions options) { - KDbConnection *conn = field.table() ? field.table()->connection() : nullptr; + const KDbConnection *conn = field.table() ? KDbFieldPrivate::connection(*field.table()) : nullptr; if (options & KDbFieldDebugAddName) { if (field.name().isEmpty()) { dbg.nospace() << " "; } else { dbg.nospace() << field.name() << ' '; } } if (field.options() & KDbField::Unsigned) dbg.nospace() << " UNSIGNED"; dbg.nospace() << ' ' << qPrintable((conn && conn->driver()) ? conn->driver()->sqlTypeName(field.type(), field) : KDbDriver::defaultSqlTypeName(field.type())); if (field.isFPNumericType() && field.precision() > 0) { if (field.scale() > 0) dbg.nospace() << QString::fromLatin1("(%1,%2)").arg(field.precision()).arg(field.scale()); else dbg.nospace() << QString::fromLatin1("(%1)").arg(field.precision()); } else if (field.type() == KDbField::Text && field.maxLength() > 0) dbg.space() << QString::fromLatin1("(%1)").arg(field.maxLength()); if (field.constraints() & KDbField::AutoInc) dbg.nospace() << " AUTOINC"; if (field.constraints() & KDbField::Unique) dbg.nospace() << " UNIQUE"; if (field.constraints() & KDbField::PrimaryKey) dbg.nospace() << " PKEY"; if (field.constraints() & KDbField::ForeignKey) dbg.nospace() << " FKEY"; if (field.constraints() & KDbField::NotNull) dbg.nospace() << " NOTNULL"; if (field.constraints() & KDbField::NotEmpty) dbg.nospace() << " NOTEMPTY"; if (!field.defaultValue().isNull()) { dbg.nospace() << qPrintable(QString::fromLatin1(" DEFAULT=[%1]") .arg(QLatin1String(field.defaultValue().typeName()))); dbg.nospace() << qPrintable(KDb::variantToString(field.defaultValue())); } if (field.isExpression()) { dbg.nospace() << " EXPRESSION="; dbg.nospace() << field.expression(); } const KDbField::CustomPropertiesMap customProperties(field.customProperties()); if (!customProperties.isEmpty()) { dbg.space() << QString::fromLatin1("CUSTOM PROPERTIES (%1): ").arg(customProperties.count()); bool first = true; for (KDbField::CustomPropertiesMap::ConstIterator it(customProperties.constBegin()); it != customProperties.constEnd(); ++it) { if (first) first = false; else dbg.nospace() << ','; dbg.space() << qPrintable(QString::fromLatin1("%1 = %2 (%3)") .arg(QLatin1String(it.key()), it.value().toString(), QLatin1String(it.value().typeName()))); } } } KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbField& field) { debug(dbg, field, KDbFieldDebugAddName); return dbg.space(); } KDB_EXPORT QDebug operator<<(QDebug dbg, KDbField::Type type) { return dbg.space() << qPrintable(KDbField::typeString(type)); } KDB_EXPORT QDebug operator<<(QDebug dbg, KDbField::TypeGroup typeGroup) { return dbg.space() << qPrintable(KDbField::typeGroupString(typeGroup)); } bool KDbField::isExpression() const { return !d->expr.isNull(); } KDbExpression KDbField::expression() { return d->expr; } const KDbExpression KDbField::expression() const { return d->expr; } void KDbField::setExpression(const KDbExpression& expr) { if (d->parent && !dynamic_cast(d->parent)) { kdbWarning() << "Cannot set expression if parent is set and it is not a query"; return; } if (d->expr == expr) { return; } d->expr = expr; } QVariant KDbField::customProperty(const QByteArray& propertyName, const QVariant& defaultValue) const { if (!d->customProperties) { return defaultValue; } return d->customProperties->value(propertyName, defaultValue); } void KDbField::setCustomProperty(const QByteArray& propertyName, const QVariant& value) { if (propertyName.isEmpty()) { return; } if (!d->customProperties) { d->customProperties = new CustomPropertiesMap(); } d->customProperties->insert(propertyName, value); } KDbField::CustomPropertiesMap KDbField::customProperties() const { return d->customProperties ? *d->customProperties : CustomPropertiesMap(); } diff --git a/src/KDbNativeStatementBuilder.cpp b/src/KDbNativeStatementBuilder.cpp index 1cbc5c94..8c83a593 100644 --- a/src/KDbNativeStatementBuilder.cpp +++ b/src/KDbNativeStatementBuilder.cpp @@ -1,507 +1,508 @@ /* 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 "KDbNativeStatementBuilder.h" #include "KDbConnection.h" #include "kdb_debug.h" #include "KDbDriverBehavior.h" #include "KDbDriver_p.h" #include "KDbExpression.h" #include "KDbLookupFieldSchema.h" #include "KDbOrderByColumn.h" #include "KDbQueryAsterisk.h" #include "KDbQuerySchema.h" #include "KDbQuerySchemaParameter.h" #include "KDbRelationship.h" KDbSelectStatementOptions::~KDbSelectStatementOptions() { } //================================================ class Q_DECL_HIDDEN KDbNativeStatementBuilder::Private { public: Private() {} //! @todo use equivalent of QPointer KDbConnection *connection; inline KDbDriver *driver() { return connection ? connection->driver() : nullptr; } private: Q_DISABLE_COPY(Private) }; //================================================ KDbNativeStatementBuilder::KDbNativeStatementBuilder(KDbConnection *connection) : d(new Private) { d->connection = connection; } KDbNativeStatementBuilder::~KDbNativeStatementBuilder() { delete d; } static bool selectStatementInternal(KDbEscapedString *target, KDbConnection *connection, KDbQuerySchema* querySchema, const KDbSelectStatementOptions& options, const QList& parameters) { Q_ASSERT(target); Q_ASSERT(querySchema); //"SELECT FROM ..." is theoretically allowed " //if (querySchema.fieldCount()<1) // return QString(); // Each SQL identifier needs to be escaped in the generated query. const KDbDriver *driver = connection ? connection->driver() : nullptr; if (!querySchema->statement().isEmpty()) { //! @todo replace with KDbNativeQuerySchema? It shouldn't be here. *target = querySchema->statement(); return true; } //! @todo looking at singleTable is visually nice but a field name can conflict //! with function or variable name... int number = 0; bool singleTable = querySchema->tables()->count() <= 1; if (singleTable) { //make sure we will have single table: foreach(KDbField *f, *querySchema->fields()) { if (querySchema->isColumnVisible(number) && f->table() && f->table()->lookupFieldSchema(*f)) { //uups, no, there's at least one left join singleTable = false; break; } number++; } } KDbEscapedString sql; //final sql string sql.reserve(4096); KDbEscapedString s_additional_joins; //additional joins needed for lookup fields KDbEscapedString s_additional_fields; //additional fields to append to the fields list int internalUniqueTableAliasNumber = 0; //used to build internalUniqueTableAliases int internalUniqueQueryAliasNumber = 0; //used to build internalUniqueQueryAliases number = 0; QList subqueries_for_lookup_data; // subqueries will be added to FROM section KDbEscapedString kdb_subquery_prefix("__kdb_subquery_"); KDbQuerySchemaParameterValueListIterator paramValuesIt(parameters); KDbQuerySchemaParameterValueListIterator *paramValuesItPtr = parameters.isEmpty() ? nullptr : ¶mValuesIt; foreach(KDbField *f, *querySchema->fields()) { if (querySchema->isColumnVisible(number)) { if (!sql.isEmpty()) sql += ", "; if (f->isQueryAsterisk()) { if (!singleTable && static_cast(f)->isSingleTableAsterisk()) { //single-table * sql.append(KDb::escapeIdentifier(driver, f->table()->name())).append(".*"); } else { //all-tables * (or simplified table.* when there's only one table) sql += '*'; } } else { if (f->isExpression()) { sql += f->expression().toString(driver, paramValuesItPtr); } else { if (!f->table()) {//sanity check return false; } QString tableName; int tablePosition = querySchema->tableBoundToColumn(number); if (tablePosition >= 0) { tableName = KDb::iifNotEmpty(querySchema->tableAlias(tablePosition), f->table()->name()); } if (options.addVisibleLookupColumns()) { // try to find table/alias name harder if (tableName.isEmpty()) { tableName = querySchema->tableAlias(f->table()->name()); } if (tableName.isEmpty()) { tableName = f->table()->name(); } } if (!singleTable && !tableName.isEmpty()) { sql.append(KDb::escapeIdentifier(driver, tableName)).append('.'); } sql += KDb::escapeIdentifier(driver, f->name()); } const QString aliasString(querySchema->columnAlias(number)); if (!aliasString.isEmpty()) { sql.append(" AS ").append(aliasString); } //! @todo add option that allows to omit "AS" keyword } KDbLookupFieldSchema *lookupFieldSchema = (options.addVisibleLookupColumns() && f->table()) ? f->table()->lookupFieldSchema(*f) : nullptr; if (lookupFieldSchema && lookupFieldSchema->boundColumn() >= 0) { // Lookup field schema found // Now we also need to fetch "visible" value from the lookup table, not only the value of binding. // -> build LEFT OUTER JOIN clause for this purpose (LEFT, not INNER because the binding can be broken) // "LEFT OUTER JOIN lookupTable ON thisTable.thisField=lookupTable.boundField" KDbLookupFieldSchemaRecordSource recordSource = lookupFieldSchema->recordSource(); if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Table) { - KDbTableSchema *lookupTable = querySchema->connection()->tableSchema(recordSource.name()); + KDbTableSchema *lookupTable = connection->tableSchema(recordSource.name()); KDbFieldList* visibleColumns = nullptr; KDbField *boundField = nullptr; if (lookupTable && lookupFieldSchema->boundColumn() < lookupTable->fieldCount() && (visibleColumns = lookupTable->subList(lookupFieldSchema->visibleColumns())) && (boundField = lookupTable->field(lookupFieldSchema->boundColumn()))) { //add LEFT OUTER JOIN if (!s_additional_joins.isEmpty()) s_additional_joins += ' '; const QString internalUniqueTableAlias( QLatin1String("__kdb_") + lookupTable->name() + QLatin1Char('_') + QString::number(internalUniqueTableAliasNumber++)); s_additional_joins += KDbEscapedString("LEFT OUTER JOIN %1 AS %2 ON %3.%4=%5.%6") .arg(KDb::escapeIdentifier(driver, lookupTable->name())) .arg(internalUniqueTableAlias) .arg(KDb::escapeIdentifier(driver, querySchema->tableAliasOrName(f->table()->name()))) .arg(KDb::escapeIdentifier(driver, f->name())) .arg(internalUniqueTableAlias) .arg(KDb::escapeIdentifier(driver, boundField->name())); //add visibleField to the list of SELECTed fields //if it is not yet present there if (!s_additional_fields.isEmpty()) s_additional_fields += ", "; //! @todo Add lookup schema option for separator other than ' ' or even option for placeholders like "Name ? ?" //! @todo Add possibility for joining the values at client side. s_additional_fields += visibleColumns->sqlFieldsList( connection, QLatin1String(" || ' ' || "), internalUniqueTableAlias, driver ? KDb::DriverEscaping : KDb::KDbEscaping); } delete visibleColumns; } else if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Query) { - KDbQuerySchema *lookupQuery = querySchema->connection()->querySchema(recordSource.name()); + KDbQuerySchema *lookupQuery = connection->querySchema(recordSource.name()); if (!lookupQuery) { kdbWarning() << "!lookupQuery"; return false; } - const KDbQueryColumnInfo::Vector fieldsExpanded(lookupQuery->fieldsExpanded()); + const KDbQueryColumnInfo::Vector fieldsExpanded( + lookupQuery->fieldsExpanded(connection)); if (lookupFieldSchema->boundColumn() >= fieldsExpanded.count()) { kdbWarning() << "lookupFieldSchema->boundColumn() >= fieldsExpanded.count()"; return false; } KDbQueryColumnInfo *boundColumnInfo = fieldsExpanded.at(lookupFieldSchema->boundColumn()); if (!boundColumnInfo) { kdbWarning() << "!boundColumnInfo"; return false; } KDbField *boundField = boundColumnInfo->field(); if (!boundField) { kdbWarning() << "!boundField"; return false; } //add LEFT OUTER JOIN if (!s_additional_joins.isEmpty()) s_additional_joins += ' '; KDbEscapedString internalUniqueQueryAlias = kdb_subquery_prefix + KDb::escapeString(connection, lookupQuery->name()) + '_' + QString::number(internalUniqueQueryAliasNumber++); KDbNativeStatementBuilder builder(connection); KDbEscapedString subSql; if (!builder.generateSelectStatement(&subSql, lookupQuery, options, parameters)) { return false; } s_additional_joins += KDbEscapedString("LEFT OUTER JOIN (%1) AS %2 ON %3.%4=%5.%6") .arg(subSql) .arg(internalUniqueQueryAlias) .arg(KDb::escapeIdentifier(driver, f->table()->name())) .arg(KDb::escapeIdentifier(driver, f->name())) .arg(internalUniqueQueryAlias) .arg(KDb::escapeIdentifier(driver, boundColumnInfo->aliasOrName())); if (!s_additional_fields.isEmpty()) s_additional_fields += ", "; const QList visibleColumns(lookupFieldSchema->visibleColumns()); KDbEscapedString expression; foreach(int visibleColumnIndex, visibleColumns) { //! @todo Add lookup schema option for separator other than ' ' or even option for placeholders like "Name ? ?" //! @todo Add possibility for joining the values at client side. if (fieldsExpanded.count() <= visibleColumnIndex) { kdbWarning() << "fieldsExpanded.count() <= (*visibleColumnsIt) : " << fieldsExpanded.count() << " <= " << visibleColumnIndex; return false; } if (!expression.isEmpty()) expression += " || ' ' || "; expression += ( internalUniqueQueryAlias + '.' + KDb::escapeIdentifier(driver, fieldsExpanded.value(visibleColumnIndex)->aliasOrName()) ); } s_additional_fields += expression; } else { kdbWarning() << "unsupported record source type" << recordSource.typeName(); return false; } } } number++; } //add lookup fields if (!s_additional_fields.isEmpty()) sql += (", " + s_additional_fields); if (driver && options.alsoRetrieveRecordId()) { //append rowid column KDbEscapedString s; if (!sql.isEmpty()) s = ", "; if (querySchema->masterTable()) s += KDbEscapedString(querySchema->tableAliasOrName(querySchema->masterTable()->name())) + '.'; s += KDbDriverPrivate::behavior(driver)->ROW_ID_FIELD_NAME; sql += s; } sql.prepend("SELECT "); QList* tables = querySchema->tables(); if ((tables && !tables->isEmpty()) || !subqueries_for_lookup_data.isEmpty()) { sql += " FROM "; KDbEscapedString s_from; if (tables) { number = 0; foreach(KDbTableSchema *table, *tables) { if (!s_from.isEmpty()) s_from += ", "; s_from += KDb::escapeIdentifier(driver, table->name()); const QString aliasString(querySchema->tableAlias(number)); if (!aliasString.isEmpty()) s_from.append(" AS ").append(aliasString); number++; } } // add subqueries for lookup data int subqueries_for_lookup_data_counter = 0; foreach(KDbQuerySchema* subQuery, subqueries_for_lookup_data) { if (!s_from.isEmpty()) s_from += ", "; KDbEscapedString subSql; if (!selectStatementInternal(&subSql, connection, subQuery, options, parameters)) { return false; } s_from += '(' + subSql + ") AS " + kdb_subquery_prefix + KDbEscapedString::number(subqueries_for_lookup_data_counter++); } sql += s_from; } KDbEscapedString s_where; s_where.reserve(4096); //JOINS if (!s_additional_joins.isEmpty()) { sql += ' ' + s_additional_joins + ' '; } //! @todo: we're using WHERE for joins now; use INNER/LEFT/RIGHT JOIN later //WHERE bool wasWhere = false; //for later use foreach(KDbRelationship *rel, *querySchema->relationships()) { if (s_where.isEmpty()) { wasWhere = true; } else s_where += " AND "; KDbEscapedString s_where_sub; foreach(const KDbField::Pair &pair, *rel->fieldPairs()) { if (!s_where_sub.isEmpty()) s_where_sub += " AND "; s_where_sub += KDbEscapedString(KDb::escapeIdentifier(driver, pair.first->table()->name())) + '.' + KDb::escapeIdentifier(driver, pair.first->name()) + " = " + KDb::escapeIdentifier(driver, pair.second->table()->name()) + '.' + KDb::escapeIdentifier(driver, pair.second->name()); } if (rel->fieldPairs()->count() > 1) { s_where_sub.prepend('('); s_where_sub += ')'; } s_where += s_where_sub; } //EXPLICITLY SPECIFIED WHERE EXPRESSION if (!querySchema->whereExpression().isNull()) { if (wasWhere) { //! @todo () are not always needed s_where = '(' + s_where + ") AND (" + querySchema->whereExpression().toString(driver, paramValuesItPtr) + ')'; } else { s_where = querySchema->whereExpression().toString(driver, paramValuesItPtr); } } if (!s_where.isEmpty()) sql += " WHERE " + s_where; //! @todo (js) add other sql parts //(use wasWhere here) // ORDER BY KDbEscapedString orderByString( querySchema->orderByColumnList()->toSqlString( !singleTable/*includeTableName*/, connection, driver ? KDb::DriverEscaping : KDb::KDbEscaping) ); - const QVector pkeyFieldsOrder(querySchema->pkeyFieldsOrder()); + const QVector pkeyFieldsOrder(querySchema->pkeyFieldsOrder(connection)); if (orderByString.isEmpty() && !pkeyFieldsOrder.isEmpty()) { //add automatic ORDER BY if there is no explicitly defined (especially helps when there are complex JOINs) KDbOrderByColumnList automaticPKOrderBy; - const KDbQueryColumnInfo::Vector fieldsExpanded(querySchema->fieldsExpanded()); + const KDbQueryColumnInfo::Vector fieldsExpanded(querySchema->fieldsExpanded(connection)); foreach(int pkeyFieldsIndex, pkeyFieldsOrder) { if (pkeyFieldsIndex < 0) // no field mentioned in this query continue; if (pkeyFieldsIndex >= fieldsExpanded.count()) { kdbWarning() << "ORDER BY: (*it) >= fieldsExpanded.count() - " << pkeyFieldsIndex << " >= " << fieldsExpanded.count(); continue; } KDbQueryColumnInfo *ci = fieldsExpanded[ pkeyFieldsIndex ]; automaticPKOrderBy.appendColumn(ci); } orderByString = automaticPKOrderBy.toSqlString(!singleTable/*includeTableName*/, connection, driver ? KDb::DriverEscaping : KDb::KDbEscaping); } if (!orderByString.isEmpty()) sql += (" ORDER BY " + orderByString); //kdbDebug() << sql; *target = sql; return true; } bool KDbNativeStatementBuilder::generateSelectStatement(KDbEscapedString *target, KDbQuerySchema* querySchema, const KDbSelectStatementOptions& options, const QList& parameters) const { return selectStatementInternal(target, d->connection, querySchema, options, parameters); } bool KDbNativeStatementBuilder::generateSelectStatement(KDbEscapedString *target, KDbQuerySchema* querySchema, const QList& parameters) const { return selectStatementInternal(target, d->connection, querySchema, KDbSelectStatementOptions(), parameters); } bool KDbNativeStatementBuilder::generateSelectStatement(KDbEscapedString *target, KDbTableSchema* tableSchema, const KDbSelectStatementOptions& options) const { return generateSelectStatement(target, tableSchema->query(), options); } bool KDbNativeStatementBuilder::generateCreateTableStatement(KDbEscapedString *target, const KDbTableSchema& tableSchema) const { if (!target) { return false; } // Each SQL identifier needs to be escaped in the generated query. const KDbDriver *driver = d->connection ? d->connection->driver() : nullptr; KDbEscapedString sql; sql.reserve(4096); sql = KDbEscapedString("CREATE TABLE ") + KDb::escapeIdentifier(driver, tableSchema.name()) + " ("; bool first = true; for (const KDbField *field : *tableSchema.fields()) { if (first) first = false; else sql += ", "; KDbEscapedString v = KDbEscapedString(KDb::escapeIdentifier(driver, field->name())) + ' '; const bool autoinc = field->isAutoIncrement(); const bool pk = field->isPrimaryKey() || (autoinc && driver && driver->behavior()->AUTO_INCREMENT_REQUIRES_PK); //! @todo warning: ^^^^^ this allows only one autonumber per table when AUTO_INCREMENT_REQUIRES_PK==true! const KDbField::Type type = field->type(); // cache: evaluating type of expressions can be expensive if (autoinc && d->driver()->behavior()->SPECIAL_AUTO_INCREMENT_DEF) { if (pk) v.append(d->driver()->behavior()->AUTO_INCREMENT_TYPE).append(' ') .append(d->driver()->behavior()->AUTO_INCREMENT_PK_FIELD_OPTION); else v.append(d->driver()->behavior()->AUTO_INCREMENT_TYPE).append(' ') .append(d->driver()->behavior()->AUTO_INCREMENT_FIELD_OPTION); } else { if (autoinc && !d->driver()->behavior()->AUTO_INCREMENT_TYPE.isEmpty()) v += d->driver()->behavior()->AUTO_INCREMENT_TYPE; else v += d->driver()->sqlTypeName(type, *field); if (KDbField::isIntegerType(type) && field->isUnsigned()) { v.append(' ').append(d->driver()->behavior()->UNSIGNED_TYPE_KEYWORD); } if (KDbField::isFPNumericType(type) && field->precision() > 0) { if (field->scale() > 0) v += QString::fromLatin1("(%1,%2)").arg(field->precision()).arg(field->scale()); else v += QString::fromLatin1("(%1)").arg(field->precision()); } else if (type == KDbField::Text) { int realMaxLen; if (d->driver()->behavior()->TEXT_TYPE_MAX_LENGTH == 0) { realMaxLen = field->maxLength(); // allow to skip (N) } else { // max length specified by driver if (field->maxLength() == 0) { // as long as possible realMaxLen = d->driver()->behavior()->TEXT_TYPE_MAX_LENGTH; } else { // not longer than specified by driver realMaxLen = qMin(d->driver()->behavior()->TEXT_TYPE_MAX_LENGTH, field->maxLength()); } } if (realMaxLen > 0) { v += QString::fromLatin1("(%1)").arg(realMaxLen); } } if (autoinc) { v.append(' ').append(pk ? d->driver()->behavior()->AUTO_INCREMENT_PK_FIELD_OPTION : d->driver()->behavior()->AUTO_INCREMENT_FIELD_OPTION); } else { //! @todo here is automatically a single-field key created if (pk) v += " PRIMARY KEY"; } if (!pk && field->isUniqueKey()) v += " UNIQUE"; ///@todo IS this ok for all engines?: if (!autoinc && !field->isPrimaryKey() && field->isNotNull()) if (!autoinc && !pk && field->isNotNull()) v += " NOT NULL"; //only add not null option if no autocommit is set if (d->driver()->supportsDefaultValue(*field) && field->defaultValue().isValid()) { KDbEscapedString valToSql(d->driver()->valueToSql(field, field->defaultValue())); if (!valToSql.isEmpty()) //for sanity v += " DEFAULT " + valToSql; } } sql += v; } sql += ')'; *target = sql; return true; } diff --git a/src/KDbOrderByColumn.cpp b/src/KDbOrderByColumn.cpp index 9e12b912..d91a5427 100644 --- a/src/KDbOrderByColumn.cpp +++ b/src/KDbOrderByColumn.cpp @@ -1,408 +1,409 @@ /* This file is part of the KDE project Copyright (C) 2003-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. */ #include "KDbOrderByColumn.h" #include "KDbQuerySchema.h" #include "KDbQuerySchema_p.h" #include "KDbConnection.h" #include "kdb_debug.h" class Q_DECL_HIDDEN KDbOrderByColumn::Private { public: Private() : column(nullptr) , pos(-1) , field(nullptr) , order(KDbOrderByColumn::SortOrder::Ascending) { } Private(const Private &other) { copy(other); } #define KDbOrderByColumnPrivateArgs(o) std::tie(o.column, o.pos, o.field, o.order) Private(KDbQueryColumnInfo* aColumn, int aPos, KDbField* aField, KDbOrderByColumn::SortOrder aOrder) { KDbOrderByColumnPrivateArgs((*this)) = std::tie(aColumn, aPos, aField, aOrder); } void copy(const Private &other) { KDbOrderByColumnPrivateArgs((*this)) = KDbOrderByColumnPrivateArgs(other); } bool operator==(const Private &other) const { return KDbOrderByColumnPrivateArgs((*this)) == KDbOrderByColumnPrivateArgs(other); } //! Column to sort, @c nullptr if field is non-0. KDbQueryColumnInfo* column; //! A helper for d->column that allows to know that sorting column //! was defined by providing its position. -1 by default. //! e.g. SELECT a, b FROM T ORDER BY 2 int pos; //! Used only in case when the second contructor is used. KDbField* field; //! Sort order KDbOrderByColumn::SortOrder order; }; //---- KDbOrderByColumn::KDbOrderByColumn() : d(new Private) { } KDbOrderByColumn::KDbOrderByColumn(KDbQueryColumnInfo* column, SortOrder order, int pos) : d(new Private(column, pos, nullptr, order)) { } KDbOrderByColumn::KDbOrderByColumn(KDbField* field, SortOrder order) : d(new Private(nullptr, -1, field, order)) { } KDbOrderByColumn::KDbOrderByColumn(const KDbOrderByColumn &other) : d(new Private(*other.d)) { } KDbOrderByColumn::~KDbOrderByColumn() { delete d; } -KDbOrderByColumn* KDbOrderByColumn::copy(KDbQuerySchema* fromQuery, KDbQuerySchema* toQuery) const +KDbOrderByColumn *KDbOrderByColumn::copy(KDbConnection *conn, KDbQuerySchema *fromQuery, + KDbQuerySchema *toQuery) const { if (d->field) { return new KDbOrderByColumn(d->field, d->order); } if (d->column) { KDbQueryColumnInfo* columnInfo; if (fromQuery && toQuery) { - int columnIndex = fromQuery->columnsOrder().value(d->column); + int columnIndex = fromQuery->columnsOrder(conn).value(d->column); if (columnIndex < 0) { kdbWarning() << "Index not found for column" << *d->column; return nullptr; } - columnInfo = toQuery->expandedOrInternalField(columnIndex); + columnInfo = toQuery->expandedOrInternalField(conn, columnIndex); if (!columnInfo) { kdbWarning() << "Column info not found at index" << columnIndex << "in toQuery"; return nullptr; } } else { columnInfo = d->column; } return new KDbOrderByColumn(columnInfo, d->order, d->pos); } return nullptr; } KDbQueryColumnInfo* KDbOrderByColumn::column() const { return d->column; } int KDbOrderByColumn::position() const { return d->pos; } KDbField* KDbOrderByColumn::field() const { return d->field; } KDbOrderByColumn::SortOrder KDbOrderByColumn::sortOrder() const { return d->order; } KDbOrderByColumn& KDbOrderByColumn::operator=(const KDbOrderByColumn &other) { if (this != &other) { *d = *other.d; } return *this; } bool KDbOrderByColumn::operator==(const KDbOrderByColumn& col) const { return *d == *col.d; } QDebug operator<<(QDebug dbg, const KDbOrderByColumn& order) { const QLatin1String orderString( order.sortOrder() == KDbOrderByColumn::SortOrder::Ascending ? "ASCENDING" : "DESCENDING"); if (order.column()) { if (order.position() > -1) { dbg.nospace() << QString::fromLatin1("COLUMN_AT_POSITION_%1(").arg(order.position() + 1); dbg.space() << *order.column() << ','; dbg.space() << orderString << ')'; return dbg.space(); } else { dbg.nospace() << "COLUMN(" << *order.column() << ','; dbg.space() << orderString << ')'; return dbg.space(); } } if (order.field()) { dbg.nospace() << "FIELD(" << *order.field() << ','; dbg.space() << orderString << ')'; return dbg.space(); } dbg.nospace() << "NONE"; return dbg.space(); } KDbEscapedString KDbOrderByColumn::toSqlString(bool includeTableName, KDbConnection *conn, KDb::IdentifierEscapingType escapingType) const { const QByteArray orderString(d->order == KDbOrderByColumn::SortOrder::Ascending ? "" : " DESC"); KDbEscapedString fieldName, tableName, collationString; if (d->column) { if (d->pos > -1) return KDbEscapedString::number(d->pos + 1) + orderString; else { if (includeTableName && d->column->alias().isEmpty()) { tableName = KDbEscapedString(escapeIdentifier(d->column->field()->table()->name(), conn, escapingType)); tableName += '.'; } fieldName = KDbEscapedString(escapeIdentifier(d->column->aliasOrName(), conn, escapingType)); } if (d->column->field()->isTextType()) { collationString = conn->driver()->collationSql(); } } else { if (d->field && includeTableName) { tableName = KDbEscapedString(escapeIdentifier(d->field->table()->name(), conn, escapingType)); tableName += '.'; } fieldName = KDbEscapedString(escapeIdentifier( d->field ? d->field->name() : QLatin1String("??")/*error*/, conn, escapingType)); if (d->field && d->field->isTextType()) { collationString = conn->driver()->collationSql(); } } return tableName + fieldName + collationString + orderString; } //======================================= class Q_DECL_HIDDEN KDbOrderByColumnList::Private { public: Private() { } ~Private() { qDeleteAll(data); } QList data; }; KDbOrderByColumnList::KDbOrderByColumnList() : d(new Private) { } -KDbOrderByColumnList::KDbOrderByColumnList(const KDbOrderByColumnList& other, +KDbOrderByColumnList::KDbOrderByColumnList(const KDbOrderByColumnList& other, KDbConnection *conn, KDbQuerySchema* fromQuery, KDbQuerySchema* toQuery) : KDbOrderByColumnList() { for (QList::ConstIterator it(other.constBegin()); it != other.constEnd(); ++it) { - KDbOrderByColumn* order = (*it)->copy(fromQuery, toQuery); + KDbOrderByColumn* order = (*it)->copy(conn, fromQuery, toQuery); if (order) { d->data.append(order); } } } KDbOrderByColumnList::~KDbOrderByColumnList() { delete d; } bool KDbOrderByColumnList::operator==(const KDbOrderByColumnList &other) const { return d->data == other.d->data; } const KDbOrderByColumn* KDbOrderByColumnList::value(int index) const { return d->data.value(index); } KDbOrderByColumn* KDbOrderByColumnList::value(int index) { return d->data.value(index); } -bool KDbOrderByColumnList::appendFields(KDbQuerySchema* querySchema, +bool KDbOrderByColumnList::appendFields(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& field1, KDbOrderByColumn::SortOrder order1, const QString& field2, KDbOrderByColumn::SortOrder order2, const QString& field3, KDbOrderByColumn::SortOrder order3, const QString& field4, KDbOrderByColumn::SortOrder order4, const QString& field5, KDbOrderByColumn::SortOrder order5) { if (!querySchema) { return false; } int numAdded = 0; #define ADD_COL(fieldName, order) \ if (ok && !fieldName.isEmpty()) { \ - if (!appendField( querySchema, fieldName, order )) \ + if (!appendField(conn, querySchema, fieldName, order)) \ ok = false; \ else \ numAdded++; \ } bool ok = true; ADD_COL(field1, order1) ADD_COL(field2, order2) ADD_COL(field3, order3) ADD_COL(field4, order4) ADD_COL(field5, order5) #undef ADD_COL if (ok) { return true; } for (int i = 0; i < numAdded; i++) { d->data.removeLast(); } return false; } void KDbOrderByColumnList::appendColumn(KDbQueryColumnInfo* columnInfo, KDbOrderByColumn::SortOrder order) { if (columnInfo) { d->data.append(new KDbOrderByColumn(columnInfo, order)); } } -bool KDbOrderByColumnList::appendColumn(KDbQuerySchema* querySchema, +bool KDbOrderByColumnList::appendColumn(KDbConnection *conn, KDbQuerySchema* querySchema, KDbOrderByColumn::SortOrder order, int pos) { if (!querySchema) { return false; } - KDbQueryColumnInfo::Vector fieldsExpanded(querySchema->fieldsExpanded()); + const KDbQueryColumnInfo::Vector fieldsExpanded(querySchema->fieldsExpanded(conn)); if (pos < 0 || pos >= fieldsExpanded.size()) { return false; } KDbQueryColumnInfo* ci = fieldsExpanded[pos]; d->data.append(new KDbOrderByColumn(ci, order, pos)); return true; } void KDbOrderByColumnList::appendField(KDbField* field, KDbOrderByColumn::SortOrder order) { if (field) { d->data.append(new KDbOrderByColumn(field, order)); } } -bool KDbOrderByColumnList::appendField(KDbQuerySchema* querySchema, +bool KDbOrderByColumnList::appendField(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& fieldName, KDbOrderByColumn::SortOrder order) { if (!querySchema) { return false; } - KDbQueryColumnInfo *columnInfo = querySchema->columnInfo(fieldName); + KDbQueryColumnInfo *columnInfo = querySchema->columnInfo(conn, fieldName); if (columnInfo) { d->data.append(new KDbOrderByColumn(columnInfo, order)); return true; } KDbField *field = querySchema->findTableField(fieldName); if (field) { d->data.append(new KDbOrderByColumn(field, order)); return true; } kdbWarning() << "no such field" << fieldName; return false; } bool KDbOrderByColumnList::isEmpty() const { return d->data.isEmpty(); } int KDbOrderByColumnList::count() const { return d->data.count(); } QList::Iterator KDbOrderByColumnList::begin() { return d->data.begin(); } QList::Iterator KDbOrderByColumnList::end() { return d->data.end(); } QList::ConstIterator KDbOrderByColumnList::constBegin() const { return d->data.constBegin(); } QList::ConstIterator KDbOrderByColumnList::constEnd() const { return d->data.constEnd(); } QDebug operator<<(QDebug dbg, const KDbOrderByColumnList& list) { if (list.isEmpty()) { dbg.nospace() << "NONE"; return dbg.space(); } bool first = true; for (QList::ConstIterator it(list.constBegin()); it != list.constEnd(); ++it) { if (first) first = false; else dbg.nospace() << '\n'; dbg.nospace() << *(*it); } return dbg.space(); } KDbEscapedString KDbOrderByColumnList::toSqlString(bool includeTableNames, KDbConnection *conn, KDb::IdentifierEscapingType escapingType) const { KDbEscapedString string; for (QList::ConstIterator it(constBegin()); it != constEnd(); ++it) { if (!string.isEmpty()) string += ", "; string += (*it)->toSqlString(includeTableNames, conn, escapingType); } return string; } void KDbOrderByColumnList::clear() { qDeleteAll(d->data); d->data.clear(); } diff --git a/src/KDbOrderByColumn.h b/src/KDbOrderByColumn.h index d6bbcf9b..128fd971 100644 --- a/src/KDbOrderByColumn.h +++ b/src/KDbOrderByColumn.h @@ -1,224 +1,225 @@ /* This file is part of the KDE project Copyright (C) 2003-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_ORDERBYCOLUMN_H #define KDB_ORDERBYCOLUMN_H #include "KDbEscapedString.h" #include "KDbGlobal.h" class KDbConnection; class KDbField; class KDbQueryColumnInfo; class KDbQuerySchema; //! @short KDbOrderByColumn provides information about a single query column used for sorting /*! The column can be expression or table field. */ class KDB_EXPORT KDbOrderByColumn { public: //! Column sort order //! @since 3.1 enum class SortOrder { Ascending = Qt::AscendingOrder, Descending = Qt::DescendingOrder }; //! Creates an empty information about a single query column. KDbOrderByColumn(); //! Creates a copy of the @a other //! @since 3.1 KDbOrderByColumn(const KDbOrderByColumn &other); //! Creates information about a single query column @a column used for sorting. explicit KDbOrderByColumn(KDbQueryColumnInfo* column, SortOrder order = SortOrder::Ascending, int pos = -1); //! Like above but used when the field @a field is not present on the list of columns. //! (e.g. SELECT a FROM t ORDER BY b; where T is a table with fields (a,b)). explicit KDbOrderByColumn(KDbField* field, SortOrder order = SortOrder::Ascending); ~KDbOrderByColumn(); /*! @return copy of this KDbOrderByColumn object. In @a fromQuery and @a toQuery is needed if column() is assigned to this info. Then, column info within @a toQuery will be assigned to the new KDbOrderByColumn object, corresponding to column() from "this" KDbOrderByColumn object. */ - KDbOrderByColumn* copy(KDbQuerySchema* fromQuery, KDbQuerySchema* toQuery) const; + KDbOrderByColumn *copy(KDbConnection *conn, KDbQuerySchema *fromQuery, + KDbQuerySchema *toQuery) const; //! A column to sort. KDbQueryColumnInfo* column() const; /*! A helper for column() that allows you to know that sorting column was defined by providing its position. -1 by default. Example query: SELECT a, b FROM T ORDER BY 2 */ int position() const; //! A field to sort, used only in case when the second constructor was used. KDbField *field() const; //! @return sort order for the column KDbOrderByColumn::SortOrder sortOrder() const; //! Assigns @a other to this object returns a reference to this object. //! @since 3.1 KDbOrderByColumn& operator=(const KDbOrderByColumn &other); //! @return true if this column is the same as @a col bool operator==(const KDbOrderByColumn& col) const; //! @return @c true if this object is not equal to @a other; otherwise returns @c false. //! @since 3.1 inline bool operator!=(const KDbOrderByColumn &other) const { return !operator==(other); } /*! @return a string like "name ASC" usable for building an SQL statement. If @a includeTableNames is true (the default) field is output in a form of "tablename.fieldname" (but only if fieldname is not a name of alias). @a escapingType can be used to alter default escaping type. If @a conn is not provided for DriverEscaping, no escaping is performed. */ KDbEscapedString toSqlString(bool includeTableName = true, KDbConnection *conn = nullptr, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; //! Converts @a order to Qt::SortOrder type inline static Qt::SortOrder toQt(SortOrder order) { return static_cast(order); } //! Converts @a order to SortOrder type inline static SortOrder fromQt(Qt::SortOrder order) { return static_cast(order); } private: class Private; Private * const d; }; //! @short KDbOrderByColumnList provides list of sorted columns for a query schema class KDB_EXPORT KDbOrderByColumnList { public: /*! Constructs empty list of ordered columns. */ KDbOrderByColumnList(); /*! A copy constructor. */ - KDbOrderByColumnList(const KDbOrderByColumnList& other, + KDbOrderByColumnList(const KDbOrderByColumnList& other, KDbConnection *conn, KDbQuerySchema* fromQuery, KDbQuerySchema* toQuery); ~KDbOrderByColumnList(); //! @return @c true if this object is equal to @a other; otherwise returns @c false. //! @since 3.1 bool operator==(const KDbOrderByColumnList &other) const; //! @return @c true if this object is not equal to @a other; otherwise returns @c false. //! @since 3.1 inline bool operator!=(const KDbOrderByColumnList &other) const { return !operator==(other); } //! Returns column with given index. //! @since 3.1 const KDbOrderByColumn* value(int index) const; //! @overload KDbOrderByColumn* value(int index); /*! Appends multiple fields for sorting. @a querySchema is used to find appropriate field or alias name. @return false if there is at least one name for which a field or alias name does not exist (all the newly appended fields are removed in this case) Returns @c false if @a querySchema is @c nullptr. */ - bool appendFields(KDbQuerySchema* querySchema, + bool appendFields(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& field1, KDbOrderByColumn::SortOrder order1 = KDbOrderByColumn::SortOrder::Ascending, const QString& field2 = QString(), KDbOrderByColumn::SortOrder order2 = KDbOrderByColumn::SortOrder::Ascending, const QString& field3 = QString(), KDbOrderByColumn::SortOrder order3 = KDbOrderByColumn::SortOrder::Ascending, const QString& field4 = QString(), KDbOrderByColumn::SortOrder order4 = KDbOrderByColumn::SortOrder::Ascending, const QString& field5 = QString(), KDbOrderByColumn::SortOrder order5 = KDbOrderByColumn::SortOrder::Ascending); /*! Appends column @a columnInfo. Does nothing if @a columnInfo is @c nullptr. */ void appendColumn(KDbQueryColumnInfo* columnInfo, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends a field @a field. Read documentation of @ref KDbOrderByColumn(KDbField* field, SortOrder order) for more info. Does nothing if @a field is @c nullptr. */ void appendField(KDbField* field, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends field with a name @a field. @return @c true on successful appending, and @c false if there is no such field or alias name in the @a querySchema. Returns @c false if @a querySchema is @c nullptr. */ - bool appendField(KDbQuerySchema* querySchema, const QString& fieldName, + bool appendField(KDbConnection *conn, KDbQuerySchema* querySchema, const QString& fieldName, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending); /*! Appends a column that is at position @a pos (counted from 0). @return true on successful adding and false if there is no such position @a pos. Returns @c false if @a querySchema is @c nullptr. */ - bool appendColumn(KDbQuerySchema* querySchema, + bool appendColumn(KDbConnection *conn, KDbQuerySchema* querySchema, KDbOrderByColumn::SortOrder order = KDbOrderByColumn::SortOrder::Ascending, int pos = -1); /*! @return true if the list is empty. */ bool isEmpty() const; /*! @return number of elements of the list. */ int count() const; /*! Removes all elements from the list (deletes them). */ void clear(); /*! Returns an STL-style iterator pointing to the first column in the list. */ QList::Iterator begin(); /*! Returns an STL-style iterator pointing to the imaginary item after the last column * in the list. */ QList::Iterator end(); /*! Returns an const STL-style iterator pointing to the first column in the list. */ QList::ConstIterator constBegin() const; /*! Returns a const STL-style iterator pointing to the imaginary item after the last column * in the list. */ QList::ConstIterator constEnd() const; /*! @return an SQL string like "name ASC, 2 DESC" usable for building an SQL statement. If @a includeTableNames is true (the default) fields are output in a form of "tablename.fieldname". @a escapingType can be used to alter default escaping type. If @a conn is not provided for DriverEscaping, no escaping is performed. */ KDbEscapedString toSqlString(bool includeTableNames = true, KDbConnection *conn = nullptr, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping) const; private: class Private; Private * const d; Q_DISABLE_COPY(KDbOrderByColumnList) }; //! Sends order-by-column information @a order to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbOrderByColumn& order); //! Sends order-by-column-list information @a list to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbOrderByColumnList& list); #endif diff --git a/src/KDbQuerySchema.cpp b/src/KDbQuerySchema.cpp index c34679d4..9fc2dcb5 100644 --- a/src/KDbQuerySchema.cpp +++ b/src/KDbQuerySchema.cpp @@ -1,1415 +1,1375 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbQuerySchema.h" #include "KDbQuerySchema_p.h" #include "KDbQueryAsterisk.h" #include "KDbConnection.h" +#include "KDbConnection_p.h" #include "kdb_debug.h" #include "KDbLookupFieldSchema.h" #include "KDbOrderByColumn.h" #include "KDbParser_p.h" #include "KDbQuerySchemaParameter.h" #include "KDbRelationship.h" QString escapeIdentifier(const QString& name, KDbConnection *conn, KDb::IdentifierEscapingType escapingType) { switch (escapingType) { case KDb::DriverEscaping: if (conn) return conn->escapeIdentifier(name); break; case KDb::KDbEscaping: return KDb::escapeIdentifier(name); } return QLatin1Char('"') + name + QLatin1Char('"'); } KDbQuerySchema::KDbQuerySchema() : KDbFieldList(false)//fields are not owned by KDbQuerySchema object , KDbObject(KDb::QueryObjectType) - , d(new Private(this)) + , d(new KDbQuerySchemaPrivate(this)) { } KDbQuerySchema::KDbQuerySchema(KDbTableSchema *tableSchema) : KDbFieldList(false)//fields are not owned by KDbQuerySchema object , KDbObject(KDb::QueryObjectType) - , d(new Private(this)) + , d(new KDbQuerySchemaPrivate(this)) { if (tableSchema) { d->masterTable = tableSchema; - d->conn = tableSchema->connection(); /*if (!d->masterTable) { kdbWarning() << "!d->masterTable"; m_name.clear(); return; }*/ addTable(d->masterTable); //defaults: //inherit name from a table setName(d->masterTable->name()); //inherit caption from a table setCaption(d->masterTable->caption()); // add explicit field list to avoid problems (e.g. with fields added outside of the app): foreach(KDbField* f, *d->masterTable->fields()) { addField(f); } } } -KDbQuerySchema::KDbQuerySchema(const KDbQuerySchema& querySchema) +KDbQuerySchema::KDbQuerySchema(const KDbQuerySchema& querySchema, KDbConnection *conn) : KDbFieldList(querySchema, false /* !deepCopyFields */) , KDbObject(querySchema) - , d(new Private(this, querySchema.d)) + , d(new KDbQuerySchemaPrivate(this, querySchema.d)) { //only deep copy query asterisks foreach(KDbField* f, *querySchema.fields()) { KDbField *copiedField; if (dynamic_cast(f)) { copiedField = f->copy(); if (static_cast(f->parent()) == &querySchema) { copiedField->setParent(this); } } else { copiedField = f; } addField(copiedField); } // this deep copy must be after the 'd' initialization because fieldsExpanded() is used there - d->orderByColumnList = new KDbOrderByColumnList(*querySchema.d->orderByColumnList, - const_cast(&querySchema), this); -} - -KDbQuerySchema::KDbQuerySchema(KDbConnection *conn) - : KDbFieldList(false)//fields are not owned by KDbQuerySchema object - , KDbObject(KDb::QueryObjectType) - , d(new Private(this)) -{ - d->conn = conn; + d->orderByColumnList = new KDbOrderByColumnList(*querySchema.d->orderByColumnList, conn, + const_cast(&querySchema), this); } KDbQuerySchema::~KDbQuerySchema() { delete d; } void KDbQuerySchema::clear() { KDbFieldList::clear(); KDbObject::clear(); d->clear(); } /*virtual*/ bool KDbQuerySchema::insertField(int position, KDbField *field) { return insertFieldInternal(position, field, -1/*don't bind*/, true); } bool KDbQuerySchema::insertInvisibleField(int position, KDbField *field) { return insertFieldInternal(position, field, -1/*don't bind*/, false); } bool KDbQuerySchema::insertField(int position, KDbField *field, int bindToTable) { return insertFieldInternal(position, field, bindToTable, true); } bool KDbQuerySchema::insertInvisibleField(int position, KDbField *field, int bindToTable) { return insertFieldInternal(position, field, bindToTable, false); } bool KDbQuerySchema::insertFieldInternal(int position, KDbField *field, int bindToTable, bool visible) { if (!field) { kdbWarning() << "!field"; return false; } if (position > fieldCount()) { kdbWarning() << "position" << position << "out of range"; return false; } if (!field->isQueryAsterisk() && !field->isExpression() && !field->table()) { kdbWarning() << "field" << field->name() << "must contain table information!"; return false; } if (fieldCount() >= d->visibility.size()) { d->visibility.resize(d->visibility.size()*2); d->tablesBoundToColumns.resize(d->tablesBoundToColumns.size()*2); } d->clearCachedData(); if (!KDbFieldList::insertField(position, field)) { return false; } if (field->isQueryAsterisk()) { d->asterisks.append(field); //if this is single-table asterisk, //add a table to list if doesn't exist there: if (field->table() && !d->tables.contains(field->table())) d->tables.append(field->table()); } else if (field->table()) { //add a table to list if doesn't exist there: if (!d->tables.contains(field->table())) d->tables.append(field->table()); } //update visibility //--move bits to make a place for a new one for (int i = fieldCount() - 1; i > position; i--) d->visibility.setBit(i, d->visibility.testBit(i - 1)); d->visibility.setBit(position, visible); //bind to table if (bindToTable < -1 || bindToTable > d->tables.count()) { kdbWarning() << "bindToTable" << bindToTable << "out of range"; bindToTable = -1; } //--move items to make a place for a new one for (int i = fieldCount() - 1; i > position; i--) d->tablesBoundToColumns[i] = d->tablesBoundToColumns[i-1]; d->tablesBoundToColumns[position] = bindToTable; kdbDebug() << "bound to table" << bindToTable; if (bindToTable == -1) kdbDebug() << " "; else kdbDebug() << " name=" << d->tables.at(bindToTable)->name() << " alias=" << tableAlias(bindToTable); QString s; for (int i = 0; i < fieldCount();i++) s += (QString::number(d->tablesBoundToColumns[i]) + QLatin1Char(' ')); kdbDebug() << "tablesBoundToColumns == [" << s << "]"; if (field->isExpression()) d->regenerateExprAliases = true; return true; } int KDbQuerySchema::tableBoundToColumn(int columnPosition) const { int res = d->tablesBoundToColumns.value(columnPosition, -99); if (res == -99) { kdbWarning() << "columnPosition" << columnPosition << "out of range"; return -1; } return res; } bool KDbQuerySchema::addField(KDbField* field) { return insertField(fieldCount(), field); } bool KDbQuerySchema::addField(KDbField* field, int bindToTable) { return insertField(fieldCount(), field, bindToTable); } bool KDbQuerySchema::addInvisibleField(KDbField* field) { return insertInvisibleField(fieldCount(), field); } bool KDbQuerySchema::addInvisibleField(KDbField* field, int bindToTable) { return insertInvisibleField(fieldCount(), field, bindToTable); } bool KDbQuerySchema::removeField(KDbField *field) { int indexOfAsterisk = -1; if (field->isQueryAsterisk()) { indexOfAsterisk = d->asterisks.indexOf(field); } if (!KDbFieldList::removeField(field)) { return false; } d->clearCachedData(); if (indexOfAsterisk >= 0) { //kdbDebug() << "d->asterisks.removeAt:" << field; //field->debug(); d->asterisks.removeAt(indexOfAsterisk); //this will destroy this asterisk } //! @todo should we also remove table for this field or asterisk? return true; } bool KDbQuerySchema::addExpressionInternal(const KDbExpression& expr, bool visible) { KDbField *field = new KDbField(this, expr); bool ok; if (visible) { ok = addField(field); } else { ok = addInvisibleField(field); } if (!ok) { delete field; } return ok; } bool KDbQuerySchema::addExpression(const KDbExpression& expr) { return addExpressionInternal(expr, true); } bool KDbQuerySchema::addInvisibleExpression(const KDbExpression& expr) { return addExpressionInternal(expr, false); } bool KDbQuerySchema::isColumnVisible(int position) const { return (position < fieldCount()) ? d->visibility.testBit(position) : false; } void KDbQuerySchema::setColumnVisible(int position, bool visible) { if (position < fieldCount()) d->visibility.setBit(position, visible); } bool KDbQuerySchema::addAsteriskInternal(KDbQueryAsterisk *asterisk, bool visible) { if (!asterisk) { return false; } //make unique name asterisk->setName((asterisk->table() ? (asterisk->table()->name() + QLatin1String(".*")) : QString(QLatin1Char('*'))) + QString::number(asterisks()->count())); return visible ? addField(asterisk) : addInvisibleField(asterisk); } bool KDbQuerySchema::addAsterisk(KDbQueryAsterisk *asterisk) { return addAsteriskInternal(asterisk, true); } bool KDbQuerySchema::addInvisibleAsterisk(KDbQueryAsterisk *asterisk) { return addAsteriskInternal(asterisk, false); } -KDbConnection* KDbQuerySchema::connection() const -{ - if (d->conn) { - return d->conn; - } - if (!d->tables.isEmpty()) { - return d->tables.first()->connection(); - } - return nullptr; -} - -QDebug operator<<(QDebug dbg, const KDbQuerySchema& query) +QDebug operator<<(QDebug dbg, const KDbConnectionAndQuerySchema &connectionAndSchema) { + KDbConnection* conn = std::get<0>(connectionAndSchema); + const KDbQuerySchema& query = std::get<1>(connectionAndSchema); //fields KDbTableSchema *mt = query.masterTable(); dbg.nospace() << "QUERY"; dbg.space() << static_cast(query) << '\n'; dbg.nospace() << " - MASTERTABLE=" << (mt ? mt->name() : QLatin1String("")) << "\n - COLUMNS:\n"; if (query.fieldCount() > 0) dbg.nospace() << static_cast(query) << '\n'; else dbg.nospace() << "\n"; if (query.fieldCount() == 0) dbg.nospace() << " - NO FIELDS\n"; else dbg.nospace() << " - FIELDS EXPANDED ("; int fieldsExpandedCount = 0; bool first; if (query.fieldCount() > 0) { - const KDbQueryColumnInfo::Vector fe(query.fieldsExpanded()); + const KDbQueryColumnInfo::Vector fe(query.fieldsExpanded(conn)); fieldsExpandedCount = fe.size(); dbg.nospace() << fieldsExpandedCount << "):\n"; first = true; for (int i = 0; i < fieldsExpandedCount; i++) { KDbQueryColumnInfo *ci = fe[i]; if (first) first = false; else dbg.nospace() << ",\n"; dbg.nospace() << *ci; } dbg.nospace() << '\n'; } //it's safer to delete fieldsExpanded for now // (debugString() could be called before all fields are added) //bindings dbg.nospace() << " - BINDINGS:\n"; bool bindingsExist = false; for (int i = 0; i < query.fieldCount(); i++) { const int tablePos = query.tableBoundToColumn(i); if (tablePos >= 0) { const QString tAlias(query.tableAlias(tablePos)); if (!tAlias.isEmpty()) { bindingsExist = true; dbg.space() << "FIELD"; dbg.space() << static_cast(query).field(i)->name(); dbg.space() << "USES ALIAS"; dbg.space() << tAlias; dbg.space() << "OF TABLE"; dbg.space() << query.tables()->at(tablePos)->name() << '\n'; } } } if (!bindingsExist) { dbg.nospace() << "\n"; } //tables dbg.nospace() << " - TABLES:\n"; first = true; foreach(KDbTableSchema *table, *query.tables()) { if (first) first = false; else dbg.nospace() << ","; dbg.space() << table->name(); } if (query.tables()->isEmpty()) dbg.nospace() << ""; //aliases dbg.nospace() << "\n - COLUMN ALIASES:\n"; if (query.columnAliasesCount() == 0) { dbg.nospace() << "\n"; } else { int i = -1; foreach(KDbField *f, *query.fields()) { i++; const QString alias(query.columnAlias(i)); if (!alias.isEmpty()) { dbg.nospace() << QString::fromLatin1("FIELD #%1:").arg(i); dbg.space() << (f->name().isEmpty() ? QLatin1String("") : f->name()) << " -> " << alias << '\n'; } } } dbg.nospace() << "\n- TABLE ALIASES:\n"; if (query.tableAliasesCount() == 0) { dbg.nospace() << "\n"; } else { int i = -1; foreach(KDbTableSchema* table, *query.tables()) { i++; const QString alias(query.tableAlias(i)); if (!alias.isEmpty()) { dbg.nospace() << QString::fromLatin1("table #%1:").arg(i); dbg.space() << (table->name().isEmpty() ? QLatin1String("") : table->name()) << " -> " << alias << '\n'; } } } if (!query.whereExpression().isNull()) { dbg.nospace() << " - WHERE EXPRESSION:\n" << query.whereExpression() << '\n'; } if (!query.orderByColumnList()->isEmpty()) { dbg.space() << QString::fromLatin1(" - ORDER BY (%1):\n").arg(query.orderByColumnList()->count()); dbg.nospace() << *query.orderByColumnList(); } return dbg.nospace(); } KDbTableSchema* KDbQuerySchema::masterTable() const { if (d->masterTable) return d->masterTable; if (d->tables.isEmpty()) return nullptr; //try to find master table if there's only one table (with possible aliasses) QString tableNameLower; int num = -1; foreach(KDbTableSchema *table, d->tables) { num++; if (!tableNameLower.isEmpty() && table->name().toLower() != tableNameLower) { //two or more different tables return nullptr; } tableNameLower = tableAlias(num); } return d->tables.first(); } void KDbQuerySchema::setMasterTable(KDbTableSchema *table) { if (table) d->masterTable = table; } QList* KDbQuerySchema::tables() const { return &d->tables; } void KDbQuerySchema::addTable(KDbTableSchema *table, const QString& alias) { kdbDebug() << (void *)table << "alias=" << alias; if (!table) return; // only append table if: it has alias or it has no alias but there is no such table on the list if (alias.isEmpty() && d->tables.contains(table)) { int num = -1; foreach(KDbTableSchema *t, d->tables) { num++; if (0 == t->name().compare(table->name(), Qt::CaseInsensitive)) { if (tableAlias(num).isEmpty()) { kdbDebug() << "table" << table->name() << "without alias already added"; return; } } } } d->tables.append(table); if (!alias.isEmpty()) setTableAlias(d->tables.count() - 1, alias); } void KDbQuerySchema::removeTable(KDbTableSchema *table) { if (!table) return; if (d->masterTable == table) d->masterTable = nullptr; d->tables.removeAt(d->tables.indexOf(table)); //! @todo remove fields! } KDbTableSchema* KDbQuerySchema::table(const QString& tableName) const { //! @todo maybe use tables_byname? foreach(KDbTableSchema *table, d->tables) { if (0 == table->name().compare(tableName, Qt::CaseInsensitive)) { return table; } } return nullptr; } bool KDbQuerySchema::contains(KDbTableSchema *table) const { return d->tables.contains(table); } KDbField* KDbQuerySchema::findTableField(const QString &tableOrTableAndFieldName) const { QString tableName, fieldName; if (!KDb::splitToTableAndFieldParts(tableOrTableAndFieldName, &tableName, &fieldName, KDb::SetFieldNameIfNoTableName)) { return nullptr; } if (tableName.isEmpty()) { foreach(KDbTableSchema *table, d->tables) { if (table->field(fieldName)) return table->field(fieldName); } return nullptr; } KDbTableSchema *tableSchema = table(tableName); if (!tableSchema) return nullptr; return tableSchema->field(fieldName); } int KDbQuerySchema::columnAliasesCount() const { return d->columnAliasesCount(); } QString KDbQuerySchema::columnAlias(int position) const { return d->columnAlias(position); } bool KDbQuerySchema::hasColumnAlias(int position) const { return d->hasColumnAlias(position); } void KDbQuerySchema::setColumnAlias(int position, const QString& alias) { if (position >= fieldCount()) { kdbWarning() << "position" << position << "out of range!"; return; } const QString fixedAlias(alias.trimmed()); KDbField *f = KDbFieldList::field(position); if (f->captionOrName().isEmpty() && fixedAlias.isEmpty()) { kdbWarning() << "position" << position << "could not remove alias when no name is specified for expression column!"; return; } d->setColumnAlias(position, fixedAlias); } int KDbQuerySchema::tableAliasesCount() const { return d->tableAliases.count(); } QString KDbQuerySchema::tableAlias(int position) const { return d->tableAliases.value(position); } QString KDbQuerySchema::tableAlias(const QString& tableName) const { const int pos = tablePosition(tableName); if (pos == -1) { return QString(); } return d->tableAliases.value(pos); } QString KDbQuerySchema::tableAliasOrName(const QString& tableName) const { const int pos = tablePosition(tableName); if (pos == -1) { return QString(); } return KDb::iifNotEmpty(d->tableAliases.value(pos), tableName); } int KDbQuerySchema::tablePositionForAlias(const QString& name) const { return d->tablePositionForAlias(name); } int KDbQuerySchema::tablePosition(const QString& tableName) const { int num = -1; foreach(KDbTableSchema* table, d->tables) { num++; if (0 == table->name().compare(tableName, Qt::CaseInsensitive)) { return num; } } return -1; } QList KDbQuerySchema::tablePositions(const QString& tableName) const { QList result; int num = -1; foreach(KDbTableSchema* table, d->tables) { num++; if (0 == table->name().compare(tableName, Qt::CaseInsensitive)) { result += num; } } return result; } bool KDbQuerySchema::hasTableAlias(int position) const { return d->tableAliases.contains(position); } int KDbQuerySchema::columnPositionForAlias(const QString& name) const { return d->columnPositionForAlias(name); } void KDbQuerySchema::setTableAlias(int position, const QString& alias) { if (position >= d->tables.count()) { kdbWarning() << "position" << position << "out of range!"; return; } const QString fixedAlias(alias.trimmed()); if (fixedAlias.isEmpty()) { const QString oldAlias(d->tableAliases.take(position)); if (!oldAlias.isEmpty()) { d->removeTablePositionForAlias(oldAlias); } } else { d->setTableAlias(position, fixedAlias); } } QList* KDbQuerySchema::relationships() const { return &d->relations; } KDbField::List* KDbQuerySchema::asterisks() const { return &d->asterisks; } KDbEscapedString KDbQuerySchema::statement() const { return d->sql; } void KDbQuerySchema::setStatement(const KDbEscapedString& sql) { d->sql = sql; } -const KDbField* KDbQuerySchema::field(const QString& identifier) const +const KDbField* KDbQuerySchema::field(KDbConnection *conn, const QString& identifier, + ExpandMode mode) const { - KDbQueryColumnInfo *ci = columnInfo(identifier, true /*expanded*/); + KDbQueryColumnInfo *ci = columnInfo(conn, identifier, mode); return ci ? ci->field() : nullptr; } -KDbField* KDbQuerySchema::field(const QString& identifier) +KDbField* KDbQuerySchema::field(KDbConnection *conn, const QString& identifier, ExpandMode mode) { - return const_cast(static_cast(this)->field(identifier)); -} - -const KDbField* KDbQuerySchema::unexpandedField(const QString& identifier) const -{ - KDbQueryColumnInfo *ci = columnInfo(identifier, false /*unexpanded*/); - return ci ? ci->field() : nullptr; -} - -KDbField* KDbQuerySchema::unexpandedField(const QString& identifier) -{ - return const_cast(static_cast(this)->unexpandedField(identifier)); + return const_cast( + static_cast(this)->field(conn, identifier, mode)); } KDbField* KDbQuerySchema::field(int id) { return KDbFieldList::field(id); } const KDbField* KDbQuerySchema::field(int id) const { return KDbFieldList::field(id); } -KDbQueryColumnInfo* KDbQuerySchema::columnInfo(const QString& identifier, bool expanded) const +KDbQueryColumnInfo *KDbQuerySchema::columnInfo(KDbConnection *conn, const QString &identifier, + ExpandMode mode) const { - computeFieldsExpanded(); - return expanded ? d->columnInfosByNameExpanded.value(identifier) - : d->columnInfosByName.value(identifier); + const KDbQuerySchemaFieldsExpanded *cache = computeFieldsExpanded(conn); + return mode == ExpandMode::Expanded ? cache->columnInfosByNameExpanded.value(identifier) + : cache->columnInfosByName.value(identifier); } KDbQueryColumnInfo::Vector KDbQuerySchema::fieldsExpandedInternal( - FieldsExpandedOptions options, bool onlyVisible) const + KDbConnection *conn, FieldsExpandedMode mode, bool onlyVisible) const { - computeFieldsExpanded(); - KDbQueryColumnInfo::Vector *realFieldsExpanded = onlyVisible ? d->visibleFieldsExpanded - : d->fieldsExpanded; - if (options == WithInternalFields || options == WithInternalFieldsAndRecordId) { + if (!conn) { + kdbWarning() << "Connection required"; + return KDbQueryColumnInfo::Vector(); + } + KDbQuerySchemaFieldsExpanded *cache = computeFieldsExpanded(conn); + const KDbQueryColumnInfo::Vector *realFieldsExpanded + = onlyVisible ? &cache->visibleFieldsExpanded : &cache->fieldsExpanded; + if (mode == FieldsExpandedMode::WithInternalFields + || mode == FieldsExpandedMode::WithInternalFieldsAndRecordId) + { //a ref to a proper pointer (as we cache the vector for two cases) - KDbQueryColumnInfo::Vector*& tmpFieldsExpandedWithInternal = - (options == WithInternalFields) ? - (onlyVisible ? d->visibleFieldsExpandedWithInternal : d->fieldsExpandedWithInternal) - : (onlyVisible ? d->visibleFieldsExpandedWithInternalAndRecordId : d->fieldsExpandedWithInternalAndRecordId); + KDbQueryColumnInfo::Vector& tmpFieldsExpandedWithInternal = + (mode == FieldsExpandedMode::WithInternalFields) ? + (onlyVisible ? cache->visibleFieldsExpandedWithInternal : cache->fieldsExpandedWithInternal) + : (onlyVisible ? cache->visibleFieldsExpandedWithInternalAndRecordId : cache->fieldsExpandedWithInternalAndRecordId); //special case - if (!tmpFieldsExpandedWithInternal) { + if (tmpFieldsExpandedWithInternal.isEmpty()) { //glue expanded and internal fields and cache it - const int internalFieldCount = d->internalFields ? d->internalFields->size() : 0; + const int internalFieldCount = cache->internalFields.size(); const int fieldsExpandedVectorSize = realFieldsExpanded->size(); const int size = fieldsExpandedVectorSize + internalFieldCount - + ((options == WithInternalFieldsAndRecordId) ? 1 : 0) /*ROWID*/; - tmpFieldsExpandedWithInternal = new KDbQueryColumnInfo::Vector(size); + + ((mode == FieldsExpandedMode::WithInternalFieldsAndRecordId) ? 1 : 0) /*ROWID*/; + tmpFieldsExpandedWithInternal.resize(size); for (int i = 0; i < fieldsExpandedVectorSize; ++i) { - (*tmpFieldsExpandedWithInternal)[i] = realFieldsExpanded->at(i); + tmpFieldsExpandedWithInternal[i] = realFieldsExpanded->at(i); } if (internalFieldCount > 0) { for (int i = 0; i < internalFieldCount; ++i) { - KDbQueryColumnInfo *info = d->internalFields->at(i); - (*tmpFieldsExpandedWithInternal)[fieldsExpandedVectorSize + i] = info; + KDbQueryColumnInfo *info = cache->internalFields[i]; + tmpFieldsExpandedWithInternal[fieldsExpandedVectorSize + i] = info; } } - if (options == WithInternalFieldsAndRecordId) { + if (mode == FieldsExpandedMode::WithInternalFieldsAndRecordId) { if (!d->fakeRecordIdField) { d->fakeRecordIdField = new KDbField(QLatin1String("rowID"), KDbField::BigInteger); d->fakeRecordIdCol = new KDbQueryColumnInfo(d->fakeRecordIdField, QString(), true); } - (*tmpFieldsExpandedWithInternal)[fieldsExpandedVectorSize + internalFieldCount] = d->fakeRecordIdCol; + tmpFieldsExpandedWithInternal[fieldsExpandedVectorSize + internalFieldCount] = d->fakeRecordIdCol; } } - return *tmpFieldsExpandedWithInternal; + return tmpFieldsExpandedWithInternal; } - if (options == Default) { + if (mode == FieldsExpandedMode::Default) { return *realFieldsExpanded; } - //options == Unique: + //mode == Unique: QSet columnsAlreadyFound; const int fieldsExpandedCount(realFieldsExpanded->count()); KDbQueryColumnInfo::Vector result(fieldsExpandedCount); //initial size is set //compute unique list int uniqueListCount = 0; for (int i = 0; i < fieldsExpandedCount; i++) { KDbQueryColumnInfo *ci = realFieldsExpanded->at(i); if (!columnsAlreadyFound.contains(ci->aliasOrName())) { columnsAlreadyFound.insert(ci->aliasOrName()); result[uniqueListCount++] = ci; } } result.resize(uniqueListCount); //update result size return result; } -KDbQueryColumnInfo::Vector KDbQuerySchema::internalFields() const +KDbQueryColumnInfo::Vector KDbQuerySchema::internalFields(KDbConnection *conn) const { - computeFieldsExpanded(); - return d->internalFields ? *d->internalFields : KDbQueryColumnInfo::Vector(); + KDbQuerySchemaFieldsExpanded *cache = computeFieldsExpanded(conn); + return cache->internalFields; } -KDbQueryColumnInfo* KDbQuerySchema::expandedOrInternalField(int index) const +KDbQueryColumnInfo* KDbQuerySchema::expandedOrInternalField(KDbConnection *conn, int index) const { - return fieldsExpanded(WithInternalFields).value(index); + return fieldsExpanded(conn, FieldsExpandedMode::WithInternalFields).value(index); } inline static QString lookupColumnKey(KDbField *foreignField, KDbField* field) { QString res; if (field->table()) // can be 0 for anonymous fields built as joined multiple visible columns res = field->table()->name() + QLatin1Char('.'); return res + field->name() + QLatin1Char('_') + foreignField->table()->name() + QLatin1Char('.') + foreignField->name(); } -void KDbQuerySchema::computeFieldsExpanded() const +KDbQuerySchemaFieldsExpanded *KDbQuerySchema::computeFieldsExpanded(KDbConnection *conn) const { - if (d->fieldsExpanded) - return; - - if (!d->columnsOrder) { - d->columnsOrder = new QHash(); - d->columnsOrderWithoutAsterisks = new QHash(); - } else { - d->columnsOrder->clear(); - d->columnsOrderWithoutAsterisks->clear(); + KDbQuerySchemaFieldsExpanded *cache = conn->d->fieldsExpanded(this); + if (cache) { + return cache; } - if (d->ownedVisibleColumns) - d->ownedVisibleColumns->clear(); + cache = new KDbQuerySchemaFieldsExpanded; + QScopedPointer guard(cache); //collect all fields in a list (not a vector yet, because we do not know its size) KDbQueryColumnInfo::List list; //temporary KDbQueryColumnInfo::List lookup_list; //temporary, for collecting additional fields related to lookup fields QHash columnInfosOutsideAsterisks; //helper for filling d->columnInfosByName int i = 0; int numberOfColumnsWithMultipleVisibleFields = 0; //used to find an unique name for anonymous field int fieldPosition = -1; for (KDbField *f : *fields()) { fieldPosition++; if (f->isQueryAsterisk()) { if (static_cast(f)->isSingleTableAsterisk()) { const KDbField::List *ast_fields = static_cast(f)->table()->fields(); foreach(KDbField *ast_f, *ast_fields) { KDbQueryColumnInfo *ci = new KDbQueryColumnInfo(ast_f, QString()/*no field for asterisk!*/, isColumnVisible(fieldPosition)); list.append(ci); kdbDebug() << "caching (unexpanded) columns order:" << *ci << "at position" << fieldPosition; - d->columnsOrder->insert(ci, fieldPosition); + cache->columnsOrder.insert(ci, fieldPosition); } } else {//all-tables asterisk: iterate through table list foreach(KDbTableSchema *table, d->tables) { //add all fields from this table const KDbField::List *tab_fields = table->fields(); foreach(KDbField *tab_f, *tab_fields) { //! @todo (js): perhaps not all fields should be appended here // d->detailedVisibility += isFieldVisible(fieldPosition); // list.append(tab_f); KDbQueryColumnInfo *ci = new KDbQueryColumnInfo(tab_f, QString()/*no field for asterisk!*/, isColumnVisible(fieldPosition)); list.append(ci); kdbDebug() << "caching (unexpanded) columns order:" << *ci << "at position" << fieldPosition; - d->columnsOrder->insert(ci, fieldPosition); + cache->columnsOrder.insert(ci, fieldPosition); } } } } else { //a single field KDbQueryColumnInfo *ci = new KDbQueryColumnInfo(f, columnAlias(fieldPosition), isColumnVisible(fieldPosition)); list.append(ci); columnInfosOutsideAsterisks.insert(ci, true); kdbDebug() << "caching (unexpanded) column's order:" << *ci << "at position" << fieldPosition; - d->columnsOrder->insert(ci, fieldPosition); - d->columnsOrderWithoutAsterisks->insert(ci, fieldPosition); + cache->columnsOrder.insert(ci, fieldPosition); + cache->columnsOrderWithoutAsterisks.insert(ci, fieldPosition); //handle lookup field schema KDbLookupFieldSchema *lookupFieldSchema = f->table() ? f->table()->lookupFieldSchema(*f) : nullptr; if (!lookupFieldSchema || lookupFieldSchema->boundColumn() < 0) continue; // Lookup field schema found: // Now we also need to fetch "visible" value from the lookup table, not only the value of binding. // -> build LEFT OUTER JOIN clause for this purpose (LEFT, not INNER because the binding can be broken) // "LEFT OUTER JOIN lookupTable ON thisTable.thisField=lookupTable.boundField" KDbLookupFieldSchemaRecordSource recordSource = lookupFieldSchema->recordSource(); if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Table) { - KDbTableSchema *lookupTable = connection()->tableSchema(recordSource.name()); + KDbTableSchema *lookupTable = conn->tableSchema(recordSource.name()); KDbFieldList* visibleColumns = nullptr; KDbField *boundField = nullptr; if (lookupTable && lookupFieldSchema->boundColumn() < lookupTable->fieldCount() && (visibleColumns = lookupTable->subList(lookupFieldSchema->visibleColumns())) && (boundField = lookupTable->field(lookupFieldSchema->boundColumn()))) { KDbField *visibleColumn = nullptr; // for single visible column, just add it as-is if (visibleColumns->fieldCount() == 1) { visibleColumn = visibleColumns->fields()->first(); } else { // for multiple visible columns, build an expression column // (the expression object will be owned by column info) visibleColumn = new KDbField(); visibleColumn->setName( QString::fromLatin1("[multiple_visible_fields_%1]") .arg(++numberOfColumnsWithMultipleVisibleFields)); visibleColumn->setExpression( KDbConstExpression(KDbToken::CHARACTER_STRING_LITERAL, QVariant()/*not important*/)); - if (!d->ownedVisibleColumns) { - d->ownedVisibleColumns = new KDbField::List(); - } - d->ownedVisibleColumns->append(visibleColumn); // remember to delete later + cache->ownedVisibleColumns.append(visibleColumn); // remember to delete later } lookup_list.append( new KDbQueryColumnInfo(visibleColumn, QString(), true/*visible*/, ci/*foreign*/)); /* //add visibleField to the list of SELECTed fields if it is not yes present there if (!findTableField( visibleField->table()->name()+"."+visibleField->name() )) { if (!table( visibleField->table()->name() )) { } if (!sql.isEmpty()) sql += QString::fromLatin1(", "); sql += (escapeIdentifier(visibleField->table()->name(), drvEscaping) + "." + escapeIdentifier(visibleField->name(), drvEscaping)); }*/ } delete visibleColumns; } else if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Query) { - KDbQuerySchema *lookupQuery = connection()->querySchema(recordSource.name()); + KDbQuerySchema *lookupQuery = conn->querySchema(recordSource.name()); if (!lookupQuery) continue; - const KDbQueryColumnInfo::Vector lookupQueryFieldsExpanded(lookupQuery->fieldsExpanded()); + const KDbQueryColumnInfo::Vector lookupQueryFieldsExpanded( + lookupQuery->fieldsExpanded(conn)); if (lookupFieldSchema->boundColumn() >= lookupQueryFieldsExpanded.count()) continue; KDbQueryColumnInfo *boundColumnInfo = nullptr; if (!(boundColumnInfo = lookupQueryFieldsExpanded.value(lookupFieldSchema->boundColumn()))) continue; KDbField *boundField = boundColumnInfo->field(); if (!boundField) continue; const QList visibleColumns(lookupFieldSchema->visibleColumns()); bool ok = true; // all indices in visibleColumns should be in [0..lookupQueryFieldsExpanded.size()-1] foreach(int visibleColumn, visibleColumns) { if (visibleColumn >= lookupQueryFieldsExpanded.count()) { ok = false; break; } } if (!ok) continue; KDbField *visibleColumn = nullptr; // for single visible column, just add it as-is if (visibleColumns.count() == 1) { visibleColumn = lookupQueryFieldsExpanded.value(visibleColumns.first())->field(); } else { // for multiple visible columns, build an expression column // (the expression object will be owned by column info) visibleColumn = new KDbField(); visibleColumn->setName( QString::fromLatin1("[multiple_visible_fields_%1]") .arg(++numberOfColumnsWithMultipleVisibleFields)); visibleColumn->setExpression( KDbConstExpression(KDbToken::CHARACTER_STRING_LITERAL, QVariant()/*not important*/)); - if (!d->ownedVisibleColumns) { - d->ownedVisibleColumns = new KDbField::List(); - } - d->ownedVisibleColumns->append(visibleColumn); // remember to delete later + cache->ownedVisibleColumns.append(visibleColumn); // remember to delete later } lookup_list.append( new KDbQueryColumnInfo(visibleColumn, QString(), true/*visible*/, ci/*foreign*/)); /* //add visibleField to the list of SELECTed fields if it is not yes present there if (!findTableField( visibleField->table()->name()+"."+visibleField->name() )) { if (!table( visibleField->table()->name() )) { } if (!sql.isEmpty()) sql += QString::fromLatin1(", "); sql += (escapeIdentifier(visibleField->table()->name(), drvEscaping) + "." + escapeIdentifier(visibleField->name(), drvEscaping)); }*/ } } } //prepare clean vector for expanded list, and a map for order information - if (!d->fieldsExpanded) { - d->fieldsExpanded = new KDbQueryColumnInfo::Vector(list.count()); - d->visibleFieldsExpanded = new KDbQueryColumnInfo::Vector(list.count()); - d->columnsOrderExpanded = new QHash(); - } else {//for future: - qDeleteAll(*d->fieldsExpanded); - d->fieldsExpanded->clear(); - d->fieldsExpanded->resize(list.count()); - d->visibleFieldsExpanded->clear(); - d->visibleFieldsExpanded->resize(list.count()); - d->columnsOrderExpanded->clear(); - } + cache->fieldsExpanded.resize(list.count()); + cache->visibleFieldsExpanded.resize(list.count()); /*fill (based on prepared 'list' and 'lookup_list'): -the vector -the map -"fields by name" dictionary */ - d->columnInfosByName.clear(); - d->columnInfosByNameExpanded.clear(); i = -1; int visibleIndex = -1; foreach(KDbQueryColumnInfo* ci, list) { i++; - (*d->fieldsExpanded)[i] = ci; + cache->fieldsExpanded[i] = ci; if (ci->isVisible()) { ++visibleIndex; - (*d->visibleFieldsExpanded)[visibleIndex] = ci; + cache->visibleFieldsExpanded[visibleIndex] = ci; } - d->columnsOrderExpanded->insert(ci, i); + cache->columnsOrderExpanded.insert(ci, i); //remember field by name/alias/table.name if there's no such string yet in d->columnInfosByNameExpanded if (!ci->alias().isEmpty()) { //store alias and table.alias - if (!d->columnInfosByNameExpanded.contains(ci->alias())) { - d->columnInfosByNameExpanded.insert(ci->alias(), ci); + if (!cache->columnInfosByNameExpanded.contains(ci->alias())) { + cache->columnInfosByNameExpanded.insert(ci->alias(), ci); } QString tableAndAlias(ci->alias()); if (ci->field()->table()) tableAndAlias.prepend(ci->field()->table()->name() + QLatin1Char('.')); - if (!d->columnInfosByNameExpanded.contains(tableAndAlias)) { - d->columnInfosByNameExpanded.insert(tableAndAlias, ci); + if (!cache->columnInfosByNameExpanded.contains(tableAndAlias)) { + cache->columnInfosByNameExpanded.insert(tableAndAlias, ci); } //the same for "unexpanded" list if (columnInfosOutsideAsterisks.contains(ci)) { - if (!d->columnInfosByName.contains(ci->alias())) { - d->columnInfosByName.insert(ci->alias(), ci); + if (!cache->columnInfosByName.contains(ci->alias())) { + cache->columnInfosByName.insert(ci->alias(), ci); } - if (!d->columnInfosByName.contains(tableAndAlias)) { - d->columnInfosByName.insert(tableAndAlias, ci); + if (!cache->columnInfosByName.contains(tableAndAlias)) { + cache->columnInfosByName.insert(tableAndAlias, ci); } } } else { //no alias: store name and table.name - if (!d->columnInfosByNameExpanded.contains(ci->field()->name())) { - d->columnInfosByNameExpanded.insert(ci->field()->name(), ci); + if (!cache->columnInfosByNameExpanded.contains(ci->field()->name())) { + cache->columnInfosByNameExpanded.insert(ci->field()->name(), ci); } QString tableAndName(ci->field()->name()); if (ci->field()->table()) tableAndName.prepend(ci->field()->table()->name() + QLatin1Char('.')); - if (!d->columnInfosByNameExpanded.contains(tableAndName)) { - d->columnInfosByNameExpanded.insert(tableAndName, ci); + if (!cache->columnInfosByNameExpanded.contains(tableAndName)) { + cache->columnInfosByNameExpanded.insert(tableAndName, ci); } //the same for "unexpanded" list if (columnInfosOutsideAsterisks.contains(ci)) { - if (!d->columnInfosByName.contains(ci->field()->name())) { - d->columnInfosByName.insert(ci->field()->name(), ci); + if (!cache->columnInfosByName.contains(ci->field()->name())) { + cache->columnInfosByName.insert(ci->field()->name(), ci); } - if (!d->columnInfosByName.contains(tableAndName)) { - d->columnInfosByName.insert(tableAndName, ci); + if (!cache->columnInfosByName.contains(tableAndName)) { + cache->columnInfosByName.insert(tableAndName, ci); } } } } - d->visibleFieldsExpanded->resize(visibleIndex + 1); + cache->visibleFieldsExpanded.resize(visibleIndex + 1); //remove duplicates for lookup fields QHash lookup_dict; //used to fight duplicates and to update KDbQueryColumnInfo::indexForVisibleLookupValue() // (a mapping from table.name string to int* lookupFieldIndex i = 0; for (QMutableListIterator it(lookup_list); it.hasNext();) { KDbQueryColumnInfo* ci = it.next(); const QString key(lookupColumnKey(ci->foreignColumn()->field(), ci->field())); if (lookup_dict.contains(key)) { // this table.field is already fetched by this query it.remove(); delete ci; } else { lookup_dict.insert(key, i); i++; } } //create internal expanded list with lookup fields - if (d->internalFields) { - qDeleteAll(*d->internalFields); - d->internalFields->clear(); - d->internalFields->resize(lookup_list.count()); - } - delete d->fieldsExpandedWithInternal; //clear cache - delete d->fieldsExpandedWithInternalAndRecordId; //clear cache - d->fieldsExpandedWithInternal = nullptr; - d->fieldsExpandedWithInternalAndRecordId = nullptr; - if (!lookup_list.isEmpty() && !d->internalFields) {//create on demand - d->internalFields = new KDbQueryColumnInfo::Vector(lookup_list.count()); - } + cache->internalFields.resize(lookup_list.count()); i = -1; foreach(KDbQueryColumnInfo *ci, lookup_list) { i++; //add it to the internal list - (*d->internalFields)[i] = ci; - d->columnsOrderExpanded->insert(ci, list.count() + i); + cache->internalFields[i] = ci; + cache->columnsOrderExpanded.insert(ci, list.count() + i); } //update KDbQueryColumnInfo::indexForVisibleLookupValue() cache for columns numberOfColumnsWithMultipleVisibleFields = 0; - for (i = 0; i < d->fieldsExpanded->size(); i++) { - KDbQueryColumnInfo* ci = d->fieldsExpanded->at(i); + for (i = 0; i < cache->fieldsExpanded.size(); i++) { + KDbQueryColumnInfo* ci = cache->fieldsExpanded[i]; //! @todo KDbQuerySchema itself will also support lookup fields... KDbLookupFieldSchema *lookupFieldSchema = ci->field()->table() ? ci->field()->table()->lookupFieldSchema(*ci->field()) : nullptr; if (!lookupFieldSchema || lookupFieldSchema->boundColumn() < 0) continue; const KDbLookupFieldSchemaRecordSource recordSource = lookupFieldSchema->recordSource(); if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Table) { - KDbTableSchema *lookupTable = connection()->tableSchema(recordSource.name()); + KDbTableSchema *lookupTable = conn->tableSchema(recordSource.name()); KDbFieldList* visibleColumns = nullptr; if (lookupTable && lookupFieldSchema->boundColumn() < lookupTable->fieldCount() && (visibleColumns = lookupTable->subList(lookupFieldSchema->visibleColumns()))) { // for single visible column, just add it as-is if (visibleColumns->fieldCount() == 1) { KDbField *visibleColumn = visibleColumns->fields()->first(); const QString key(lookupColumnKey(ci->field(), visibleColumn)); int index = lookup_dict.value(key, -99); if (index != -99) - ci->setIndexForVisibleLookupValue(d->fieldsExpanded->size() + index); + ci->setIndexForVisibleLookupValue(cache->fieldsExpanded.size() + index); } else { const QString key(QString::fromLatin1("[multiple_visible_fields_%1]_%2.%3") .arg(++numberOfColumnsWithMultipleVisibleFields) .arg(ci->field()->table()->name(), ci->field()->name())); int index = lookup_dict.value(key, -99); if (index != -99) - ci->setIndexForVisibleLookupValue(d->fieldsExpanded->size() + index); + ci->setIndexForVisibleLookupValue(cache->fieldsExpanded.size() + index); } } delete visibleColumns; } else if (recordSource.type() == KDbLookupFieldSchemaRecordSource::Query) { - KDbQuerySchema *lookupQuery = connection()->querySchema(recordSource.name()); + KDbQuerySchema *lookupQuery = conn->querySchema(recordSource.name()); if (!lookupQuery) continue; - const KDbQueryColumnInfo::Vector lookupQueryFieldsExpanded(lookupQuery->fieldsExpanded()); + const KDbQueryColumnInfo::Vector lookupQueryFieldsExpanded( + lookupQuery->fieldsExpanded(conn)); if (lookupFieldSchema->boundColumn() >= lookupQueryFieldsExpanded.count()) continue; KDbQueryColumnInfo *boundColumnInfo = nullptr; if (!(boundColumnInfo = lookupQueryFieldsExpanded.value(lookupFieldSchema->boundColumn()))) continue; KDbField *boundField = boundColumnInfo->field(); if (!boundField) continue; const QList visibleColumns(lookupFieldSchema->visibleColumns()); // for single visible column, just add it as-is if (visibleColumns.count() == 1) { if (lookupQueryFieldsExpanded.count() > visibleColumns.first()) { // sanity check KDbField *visibleColumn = lookupQueryFieldsExpanded.at(visibleColumns.first())->field(); const QString key(lookupColumnKey(ci->field(), visibleColumn)); int index = lookup_dict.value(key, -99); if (index != -99) - ci->setIndexForVisibleLookupValue(d->fieldsExpanded->size() + index); + ci->setIndexForVisibleLookupValue(cache->fieldsExpanded.size() + index); } } else { const QString key(QString::fromLatin1("[multiple_visible_fields_%1]_%2.%3") .arg(++numberOfColumnsWithMultipleVisibleFields) .arg(ci->field()->table()->name(), ci->field()->name())); int index = lookup_dict.value(key, -99); if (index != -99) - ci->setIndexForVisibleLookupValue(d->fieldsExpanded->size() + index); + ci->setIndexForVisibleLookupValue(cache->fieldsExpanded.size() + index); } } else { kdbWarning() << "unsupported record source type" << recordSource.typeName(); } } + if (d->recentConnection != conn) { + if (d->recentConnection) { + // connection changed: remove old cache + d->recentConnection->d->insertFieldsExpanded(this, nullptr); + } + d->recentConnection = conn; + } + conn->d->insertFieldsExpanded(this, guard.take()); + return cache; } -QHash KDbQuerySchema::columnsOrder(ColumnsOrderOptions options) const +QHash KDbQuerySchema::columnsOrder(KDbConnection *conn, + ColumnsOrderMode mode) const { - if (!d->columnsOrder) - computeFieldsExpanded(); - if (options == UnexpandedList) - return *d->columnsOrder; - else if (options == UnexpandedListWithoutAsterisks) - return *d->columnsOrderWithoutAsterisks; - return *d->columnsOrderExpanded; + KDbQuerySchemaFieldsExpanded *cache = computeFieldsExpanded(conn); + if (mode == ColumnsOrderMode::UnexpandedList) { + return cache->columnsOrder; + } else if (mode == ColumnsOrderMode::UnexpandedListWithoutAsterisks) { + return cache->columnsOrderWithoutAsterisks; + } + return cache->columnsOrderExpanded; } -QVector KDbQuerySchema::pkeyFieldsOrder() const +QVector KDbQuerySchema::pkeyFieldsOrder(KDbConnection *conn) const { if (d->pkeyFieldsOrder) return *d->pkeyFieldsOrder; KDbTableSchema *tbl = masterTable(); if (!tbl || !tbl->primaryKey()) return QVector(); //get order of PKEY fields (e.g. for records updating or inserting ) KDbIndexSchema *pkey = tbl->primaryKey(); kdbDebug() << *pkey; d->pkeyFieldsOrder = new QVector(pkey->fieldCount(), -1); - const int fCount = fieldsExpanded().count(); d->pkeyFieldCount = 0; + const KDbQueryColumnInfo::Vector fieldsExpanded(this->fieldsExpanded(conn)); + const int fCount = fieldsExpanded.count(); for (int i = 0; i < fCount; i++) { - KDbQueryColumnInfo *fi = d->fieldsExpanded->at(i); + const KDbQueryColumnInfo *fi = fieldsExpanded[i]; const int fieldIndex = fi->field()->table() == tbl ? pkey->indexOf(*fi->field()) : -1; if (fieldIndex != -1/* field found in PK */ && d->pkeyFieldsOrder->at(fieldIndex) == -1 /* first time */) { kdbDebug() << "FIELD" << fi->field()->name() << "IS IN PKEY AT POSITION #" << fieldIndex; (*d->pkeyFieldsOrder)[fieldIndex] = i; d->pkeyFieldCount++; } } kdbDebug() << d->pkeyFieldCount << " OUT OF " << pkey->fieldCount() << " PKEY'S FIELDS FOUND IN QUERY " << name(); return *d->pkeyFieldsOrder; } -int KDbQuerySchema::pkeyFieldCount() +int KDbQuerySchema::pkeyFieldCount(KDbConnection *conn) { - (void)pkeyFieldsOrder(); /* rebuild information */ + (void)pkeyFieldsOrder(conn); /* rebuild information */ return d->pkeyFieldCount; } KDbRelationship* KDbQuerySchema::addRelationship(KDbField *field1, KDbField *field2) { //@todo: find existing global db relationships KDbRelationship *r = new KDbRelationship(this, field1, field2); if (r->isEmpty()) { delete r; return nullptr; } d->relations.append(r); return r; } -KDbQueryColumnInfo::List* KDbQuerySchema::autoIncrementFields() const +KDbQueryColumnInfo::List* KDbQuerySchema::autoIncrementFields(KDbConnection *conn) const { if (!d->autoincFields) { d->autoincFields = new KDbQueryColumnInfo::List(); } KDbTableSchema *mt = masterTable(); if (!mt) { kdbWarning() << "no master table!"; return d->autoincFields; } if (d->autoincFields->isEmpty()) {//no cache - KDbQueryColumnInfo::Vector fexp = fieldsExpanded(); - for (int i = 0; i < fexp.count(); i++) { - KDbQueryColumnInfo *ci = fexp[i]; + const KDbQueryColumnInfo::Vector fieldsExpanded(this->fieldsExpanded(conn)); + for (int i = 0; i < fieldsExpanded.count(); i++) { + KDbQueryColumnInfo *ci = fieldsExpanded[i]; if (ci->field()->table() == mt && ci->field()->isAutoIncrement()) { d->autoincFields->append(ci); } } } return d->autoincFields; } // static -KDbEscapedString KDbQuerySchema::sqlColumnsList(const KDbQueryColumnInfo::List& infolist, KDbConnection *conn, - KDb::IdentifierEscapingType escapingType) +KDbEscapedString KDbQuerySchema::sqlColumnsList(const KDbQueryColumnInfo::List &infolist, + KDbConnection *conn, + KDb::IdentifierEscapingType escapingType) { KDbEscapedString result; result.reserve(256); bool start = true; foreach(KDbQueryColumnInfo* ci, infolist) { if (!start) result += ","; else start = false; result += escapeIdentifier(ci->field()->name(), conn, escapingType); } return result; } KDbEscapedString KDbQuerySchema::autoIncrementSqlFieldsList(KDbConnection *conn) const { // QWeakPointer driverWeakPointer // = DriverManagerInternal::self()->driverWeakPointer(*conn->driver()); if ( /*d->lastUsedDriverForAutoIncrementSQLFieldsList != driverWeakPointer ||*/ d->autoIncrementSqlFieldsList.isEmpty()) { - d->autoIncrementSqlFieldsList = KDbQuerySchema::sqlColumnsList(*autoIncrementFields(), conn); + d->autoIncrementSqlFieldsList = KDbQuerySchema::sqlColumnsList(*autoIncrementFields(conn), conn); //d->lastUsedDriverForAutoIncrementSQLFieldsList = driverWeakPointer; } return d->autoIncrementSqlFieldsList; } static void setResult(const KDbParseInfoInternal &parseInfo, QString *errorMessage, QString *errorDescription) { if (errorMessage) { *errorMessage = parseInfo.errorMessage(); } if (errorDescription) { *errorDescription = parseInfo.errorDescription(); } } bool KDbQuerySchema::setWhereExpression(const KDbExpression &expr, QString *errorMessage, QString *errorDescription) { KDbExpression newWhereExpr = expr.clone(); KDbParseInfoInternal parseInfo(this); QString tempErrorMessage; QString tempErrorDescription; QString *errorMessagePointer = errorMessage ? errorMessage : &tempErrorMessage; QString *errorDescriptionPointer = errorDescription ? errorDescription : &tempErrorDescription; if (!newWhereExpr.validate(&parseInfo)) { setResult(parseInfo, errorMessagePointer, errorDescription); kdbWarning() << "message=" << *errorMessagePointer << "description=" << *errorDescriptionPointer; kdbWarning() << newWhereExpr; d->whereExpr = KDbExpression(); return false; } errorMessagePointer->clear(); errorDescriptionPointer->clear(); - Private::setWhereExpressionInternal(this, newWhereExpr); + KDbQuerySchemaPrivate::setWhereExpressionInternal(this, newWhereExpr); return true; } bool KDbQuerySchema::addToWhereExpression(KDbField *field, const QVariant &value, KDbToken relation, QString *errorMessage, QString *errorDescription) { KDbToken token; if (value.isNull()) { token = KDbToken::SQL_NULL; } else { const KDbField::Type type = field->type(); // cache: evaluating type of expressions can be expensive if (KDbField::isIntegerType(type)) { token = KDbToken::INTEGER_CONST; } else if (KDbField::isFPNumericType(type)) { token = KDbToken::REAL_CONST; } else { token = KDbToken::CHARACTER_STRING_LITERAL; } //! @todo date, time } KDbBinaryExpression newExpr( KDbConstExpression(token, value), relation, KDbVariableExpression((field->table() ? (field->table()->name() + QLatin1Char('.')) : QString()) + field->name()) ); const KDbExpression origWhereExpr = d->whereExpr; if (!d->whereExpr.isNull()) { newExpr = KDbBinaryExpression( d->whereExpr, KDbToken::AND, newExpr ); } const bool result = setWhereExpression(newExpr, errorMessage, errorDescription); if (!result) { // revert, setWhereExpression() cleared it d->whereExpr = origWhereExpr; } return result; } /* void KDbQuerySchema::addToWhereExpression(KDbField *field, const QVariant& value) switch (value.type()) { case Int: case UInt: case Bool: case LongLong: case ULongLong: token = INTEGER_CONST; break; case Double: token = REAL_CONST; break; default: token = CHARACTER_STRING_LITERAL; } //! @todo date, time */ KDbExpression KDbQuerySchema::whereExpression() const { return d->whereExpr; } void KDbQuerySchema::setOrderByColumnList(const KDbOrderByColumnList& list) { delete d->orderByColumnList; - d->orderByColumnList = new KDbOrderByColumnList(list, nullptr, nullptr); + d->orderByColumnList = new KDbOrderByColumnList(list, nullptr, nullptr, nullptr); // all field names should be found, exit otherwise ..........? } KDbOrderByColumnList* KDbQuerySchema::orderByColumnList() { return d->orderByColumnList; } const KDbOrderByColumnList* KDbQuerySchema::orderByColumnList() const { return d->orderByColumnList; } -QList KDbQuerySchema::parameters() const +QList KDbQuerySchema::parameters(KDbConnection *conn) const { QList params; - const KDbQueryColumnInfo::Vector fieldsExpanded(this->fieldsExpanded()); + const KDbQueryColumnInfo::Vector fieldsExpanded(this->fieldsExpanded(conn)); for (int i = 0; i < fieldsExpanded.count(); ++i) { KDbQueryColumnInfo *ci = fieldsExpanded[i]; if (!ci->field()->expression().isNull()) { ci->field()->expression().getQueryParameters(¶ms); } } KDbExpression where = whereExpression(); if (!where.isNull()) { where.getQueryParameters(¶ms); } return params; } bool KDbQuerySchema::validate(QString *errorMessage, QString *errorDescription) { KDbParseInfoInternal parseInfo(this); foreach(KDbField* f, *fields()) { if (f->isExpression()) { if (!f->expression().validate(&parseInfo)) { setResult(parseInfo, errorMessage, errorDescription); return false; } } } if (!whereExpression().validate(&parseInfo)) { setResult(parseInfo, errorMessage, errorDescription); return false; } return true; } diff --git a/src/KDbQuerySchema.h b/src/KDbQuerySchema.h index a135787f..4d112d69 100644 --- a/src/KDbQuerySchema.h +++ b/src/KDbQuerySchema.h @@ -1,744 +1,752 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 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_QUERYSCHEMA_H #define KDB_QUERYSCHEMA_H #include #include #include "KDbFieldList.h" #include "KDbObject.h" #include "KDbQueryColumnInfo.h" #include "KDbToken.h" class KDbConnection; -class KDbTableSchema; -class KDbRelationship; -class KDbQueryAsterisk; -class KDbQuerySchemaParameter; class KDbOrderByColumn; class KDbOrderByColumnList; +class KDbQueryAsterisk; +class KDbQuerySchemaFieldsExpanded; +class KDbQuerySchemaParameter; +class KDbQuerySchemaPrivate; +class KDbRelationship; +class KDbTableSchema; //! @short KDbQuerySchema provides information about database query /*! The query that can be executed using KDb-compatible SQL database engine or used as an introspection tool. KDb parser builds KDbQuerySchema objects by parsing SQL statements. */ class KDB_EXPORT KDbQuerySchema : public KDbFieldList, public KDbObject { public: /*! Creates empty query object (without columns). */ KDbQuerySchema(); /*! Creates query schema object that is equivalent to "SELECT * FROM table" sql command. Schema of @a table is used to contruct this query -- it is defined by just adding all the fields to the query in natural order. To avoid problems (e.g. with fields added outside of Kexi using ALTER TABLE) we do not use "all-tables query asterisk" (see KDbQueryAsterisk) item to achieve this effect. Properties such as the name and caption of the query are inherited from table schema. We consider that query schema based on @a table is not (a least yet) stored in a system table, so query connection is set to @c nullptr (even if @a tableSchema's connection is not @c nullptr). Id of the created query is set to 0. */ explicit KDbQuerySchema(KDbTableSchema *tableSchema); /*! Copy constructor. Creates deep copy of @a querySchema. KDbQueryAsterisk objects are deeply copied while only pointers to KDbField objects are copied. */ - KDbQuerySchema(const KDbQuerySchema& querySchema); + KDbQuerySchema(const KDbQuerySchema& querySchema, KDbConnection *conn); ~KDbQuerySchema() override; /*! Inserts @a field to the columns list at @a position. Inserted field will not be owned by this KDbQuerySchema object, but by the corresponding KDbTableSchema. KDbQueryAsterisk can be also passed as @a field. See the KDbQueryAsterisk class description. @note After inserting a field, corresponding table will be automatically added to query's tables list if it is not present there (see tables()). KDbField must have its table assigned. The inserted field will be visible. Use insertInvisibleField(position, field) to add an invisible field. The field is not bound to any particular table within the query. */ bool insertField(int position, KDbField *field) override; /** * @overload bool insertField(int position, KDbField *field) * Inserts @a field to the columns list at @a position. * @a bindToTable is a table index within the query for which the field should be bound. * If @a bindToTable is -1, no particular table will be bound. * @see tableBoundToColumn(int columnPosition) */ bool insertField(int position, KDbField *field, int bindToTable); /** * @overload bool insertField(int position, KDbField *field) * Inserts @a field to the columns list at @a position. * In addition sets field's visibility to @c false. It will not be bound to any table in this query. * @since 3.1 */ bool insertInvisibleField(int position, KDbField *field); /** * @overload bool insertInvisibleField(int position, KDbField *field) * Inserts @a field to the columns list at @a position. * In addition sets field's visibility to @c false. * @a bindToTable is a table index within the query for which the field should be bound. * If @a bindToTable is -1, no particular table will be bound. * @see tableBoundToColumn(int columnPosition) * @since 3.1 */ bool insertInvisibleField(int position, KDbField *field, int bindToTable); /** * Appends @a field to the columns list. * The field will be visible. Use addInvisibleField(field) to add an invisible field. * The field is not bound to any particular table within the query. * @see insertField() */ bool addField(KDbField* field); /*! Appends @a field to the columns list. Also binds to a table at @a bindToTable position. * Use bindToTable==-1 if no table should be bound. * The field will be visible. Use addInvisibleField(field, bindToTable) to add * an invisible field. * @see insertField() * @see tableBoundToColumn(int columnPosition) */ bool addField(KDbField* field, int bindToTable); /** * @overload bool addField(KDbField* field) * Appends @a field to the columns list. * The field is not bound to any particular table within the query. * In addition sets field's visibility to @c false. It will not be bound to any table in this query. * @since 3.1 */ bool addInvisibleField(KDbField* field); /** * @overload bool addField(KDbField* field, int bindToTable) * Appends @a field to the columns list. Also binds to a table at @a bindToTable position. * In addition sets field's visibility to @c false. * @see tableBoundToColumn(int columnPosition) * @since 3.1 */ bool addInvisibleField(KDbField* field, int bindToTable); /*! Removes field from the columns list. Use with care. */ bool removeField(KDbField *field) override; /** * Appends a column built on top of @a expr expression. * This creates a new KDbField object and adds it to the query schema using addField(). */ bool addExpression(const KDbExpression& expr); /** * @overload bool addExpression(const KDbExpression& expr) * Appends a column built on top of @a expr expression. * In addition sets column's visibility to @c false. * @since 3.1 */ bool addInvisibleExpression(const KDbExpression& expr); /*! @return visibility flag for column at @a position. By default column is visible. */ bool isColumnVisible(int position) const; //! Sets visibility flag for column at @a position to @a visible. void setColumnVisible(int position, bool visible); /*! Appends @a asterisk at the and of columns list. */ bool addAsterisk(KDbQueryAsterisk *asterisk); /** * @overload bool addAsterisk(KDbQueryAsterisk *asterisk) * Appends @a asterisk at the and of columns list. * Sets the asterisk as invisible. * @since 3.1 */ bool addInvisibleAsterisk(KDbQueryAsterisk *asterisk); /*! Removes all columns and their aliases from the columns list, removes all tables and their aliases from the tables list within this query. Sets master table information to @c nullptr. Does not destroy any objects though. Clears name and all other properties. @see KDbFieldList::clear() */ void clear() override; - /*! If query was created using a connection, - returns this connection object, otherwise @c nullptr. */ - KDbConnection* connection() const; - /*! @return table that is master to this query. All potentially-editable columns within this query belong just to this table. This method also can return @c nullptr if there are no tables at all, or if previously assigned master table schema has been removed with removeTable(). Every query that has at least one table defined, should have assigned a master table. If no master table is assigned explicitly, but only one table used in this query, a single table is returned here, even if there are table aliases, (e.g. "T" table is returned for "SELECT T1.A, T2.B FROM T T1, T T2" statement). */ KDbTableSchema* masterTable() const; /*! Sets master table of this query to @a table. This table should be also added to query's tables list using addTable(). If @a table equals @c nullptr, nothing is performed. @see masterTable() */ void setMasterTable(KDbTableSchema *table); /*! @return list of tables used in a query. This also includes master table. @see masterTable() */ QList* tables() const; /*! Appends @a table schema as one of tables used in a query. If @a alias is not empty, it will be assigned to this table using setTableAlias(position, alias). */ void addTable(KDbTableSchema *table, const QString& alias = QString()); /*! Removes @a table schema from this query. This does not destroy @a table object but only takes it out of the list. If this table was master for the query, master table information is also invalidated. */ void removeTable(KDbTableSchema *table); /*! @return table with name @a tableName or 0 if this query has no such table. */ KDbTableSchema* table(const QString& tableName) const; /*! @return @c true if the query uses @a table. */ bool contains(KDbTableSchema *table) const; /*! Convenience function. @return table field by searching through all tables in this query. The field does not need to be included on the list of query columns. Similarly, query aliases are not taken into account. @a tableOrTableAndFieldName string may contain table name and field name with '.' character between them, e.g. "mytable.myfield". This is recommended way to avoid ambiguity. 0 is returned if the query has no such table defined of the table has no such field defined. If you do not provide a table name, the first field found is returned. KDbQuerySchema::table("mytable")->field("myfield") could be alternative for findTableField("mytable.myfield") but it can crash if "mytable" is not defined in the query. @see KDb::splitToTableAndFieldParts() */ KDbField* findTableField(const QString &tableOrTableAndFieldName) const; /*! @return alias of a column at @a position or null string If there is no alias for this column or if there is no such column within the query defined. If the column is an expression and has no alias defined, a new unique alias will be generated automatically on this call. */ QString columnAlias(int position) const; /*! @return number of column aliases */ int columnAliasesCount() const; /*! Provided for convenience. @return @c true if a column at @a position has non empty alias defined within the query. If there is no alias for this column, or if there is no such column in the query defined, @c false is returned. */ bool hasColumnAlias(int position) const; /*! Sets @a alias for a column at @a position, within the query. Passing empty string to @a alias clears alias for a given column. */ void setColumnAlias(int position, const QString& alias); /*! @return a table position (within FROM section), that is bound to column at @a columnPosition (within SELECT section). This information can be used to find if there is alias defined for a table that is referenced by a given column. For example, for "SELECT t2.id FROM table1 t1, table2 t2" query statement, columnBoundToTable(0) returns 1, what means that table at position 1 (within FROM section) is bound to column at position 0, so we can now call tableAlias(1) to see if we have used alias for this column (t2.id) or just a table name (table2.id). These checks are performed e.g. by KDbConnection::selectStatement() to construct a statement string maximally identical to originally defined query statement. -1 is returned if: - @a columnPosition is out of range (i.e. < 0 or >= fieldCount()) - a column at @a columnPosition is not bound to any table (i.e. no database field is used for this column, e.g. "1" constant for "SELECT 1 from table" query statement) */ int tableBoundToColumn(int columnPosition) const; /*! @return number of table aliases */ int tableAliasesCount() const; /*! @return alias of a table at @a position (within FROM section) or null string if there is no alias for this table or if there is no such table within the query defined. */ QString tableAlias(int position) const; /*! @return alias of a table @a tableName (within FROM section) or empty value if there is no alias for this table or if there is no such table within the query defined. */ QString tableAlias(const QString& tableName) const; /*! @return alias of a table @a tableName (within FROM section). If there is no alias for this table, its name is returned. Empty value is returned if there is no such table within the query defined. */ QString tableAliasOrName(const QString& tableName) const; /*! @return table position (within FROM section) that has attached alias @a name. If there is no such alias, -1 is returned. Only first table's position attached for this alias is returned. It is not especially bad, since aliases rarely can be duplicated, what leads to ambiguity. Duplicated aliases are only allowed for trivial queries that have no database fields used within their columns, e.g. "SELECT 1 from table1 t, table2 t" is ok but "SELECT t.id from table1 t, table2 t" is not. */ int tablePositionForAlias(const QString& name) const; /*! @return position (within the FROM section) of table @a tableName. -1 is returned if there's no such table declared in the FROM section. @see tablePositions() */ int tablePosition(const QString& tableName) const; /*! @return a list of all occurrences of table @a tableName (within the FROM section). E.g. for "SELECT * FROM table t, table t2" tablePositions("table") returns {0, 1} list. Empty list is returned if there's no table @a tableName used in the FROM section at all. @see tablePosition() */ QList tablePositions(const QString& tableName) const; /*! Provided for convenience. @return @c true if a table at @a position (within FROM section of the query) has non empty alias defined. If there is no alias for this table, or if there is no such table in the query defined, @c false is returned. */ bool hasTableAlias(int position) const; /*! @return column position that has defined alias @a name. If there is no such alias, -1 is returned. */ int columnPositionForAlias(const QString& name) const; /*! Sets @a alias for a table at @a position (within FROM section of the query). Passing empty sting to @a alias clears alias for a given table (only for specified @a position). */ void setTableAlias(int position, const QString& alias); /*! @return a list of relationships defined for this query */ QList* relationships() const; /*! Appends a new relationship defined by @a field1 and @a field2. Both fields should belong to two different tables of this query. This is convenience function useful for a typical cases. It automatically creates KDbRelationship object for this query. If one of the fields are primary keys, it will be detected and appropriate master-detail relation will be established. This functiuon does nothing if the arguments are invalid. */ KDbRelationship* addRelationship(KDbField *field1, KDbField *field2); /*! @return list of KDbQueryAsterisk objects defined for this query */ KDbField::List* asterisks() const; + //! Mode for field() and columnInfo() + //! @since 3.1 + enum class ExpandMode { + Unexpanded, //!< All fields are returned even if duplicated + Expanded //!< Expanded list of the query fields is computed so queries with asterisks + //!< are processed well + }; + /*! @return field for @a identifier or @c nullptr if no field for this name was found within the query. fieldsExpanded() method is used to lookup expanded list of the query fields, so queries with asterisks are processed well. If a field has alias defined, name is not taken into account, but only its alias. If a field has no alias: - field's name is checked - field's table and field's name are checked in a form of "tablename.fieldname", so you can provide @a identifier in this form to avoid ambiguity. If there are more than one fields with the same name equal to @a identifier, first-found is returned (checking is performed from first to last query field). Structures needed to compute result of this method are cached, so only first usage costs o(n) - another usages cost o(1). Example: Let query be defined by "SELECT T.B AS X, T.* FROM T" statement and let T be table containing fields A, B, C. Expanded list of columns for the query is: T.B AS X, T.A, T.B, T.C. - Calling field("B") will return a pointer to third query column (not the first, because it is covered by "X" alias). Additionally, calling field("X") will return the same pointer. - Calling field("T.A") will return the same pointer as field("A"). This method is also a product of inheritance from KDbFieldList. */ - const KDbField* field(const QString& identifier) const override; + const KDbField *field(KDbConnection *conn, const QString &identifier, + ExpandMode mode = ExpandMode::Expanded) const; /** - * @overload const KDbField* field(const QString& identifier) const + * @overload */ - KDbField* field(const QString& identifier) override; - - /** - * An overloaded method KDbField* field(const QString& identifier) - * where unexpanded list of fields is used to find a field. - */ - const KDbField* unexpandedField(const QString& identifier) const; - - /** - * @overload const KDbField* unexpandedField(const QString& identifier) const - */ - KDbField* unexpandedField(const QString& identifier); + KDbField *field(KDbConnection *conn, const QString &identifier, + ExpandMode mode = ExpandMode::Expanded); /*! @return field id or @c nullptr if there is no such a field. */ KDbField* field(int id) override; + using KDbFieldList::field; + /*! @overload KDbField* field(int id) */ const KDbField* field(int id) const override; /*! Like KDbQuerySchema::field(const QString& name) but returns not only KDbField object for @a identifier but entire KDbQueryColumnInfo object. @a identifier can be: - a fieldname - an aliasname - a tablename.fieldname - a tablename.aliasname Note that if there are two occurrrences of the same name, only the first is accessible using this method. For instance, calling columnInfo("name") for "SELECT t1.name, t2.name FROM t1, t2" statement will only return the column related to t1.name and not t2.name, so you'll need to explicitly specify "t2.name" as the identifier to get the second column. */ - KDbQueryColumnInfo* columnInfo(const QString& identifier, bool expanded = true) const; + KDbQueryColumnInfo *columnInfo(KDbConnection *conn, const QString &identifier, + ExpandMode mode = ExpandMode::Expanded) const; - /*! Options used in fieldsExpanded() and visibleFieldsExpanded(). */ - enum FieldsExpandedOptions { + //! Mode for fieldsExpanded() and visibleFieldsExpanded() + //! @since 3.1 + enum class FieldsExpandedMode { Default, //!< All fields are returned even if duplicated Unique, //!< Unique list of fields is returned WithInternalFields, //!< Like Default but internal fields (for lookup) are appended WithInternalFieldsAndRecordId //!< Like WithInternalFields but record ID (big int type) field //!< is appended after internal fields }; /*! @return fully expanded list of fields. KDbQuerySchema::fields() returns vector of fields used for the query columns, but in a case when there are asterisks defined for the query, it does not expand KDbQueryAsterisk objects to field lists but return every asterisk as-is. This could be inconvenient when you need just a fully expanded list of fields, so this method does the work for you. If @a options is Unique, each field is returned in the vector only once (first found field is selected). Note however, that the same field can be returned more than once if it has attached a different alias. For example, let t be TABLE( a, b ) and let query be defined by "SELECT *, a AS alfa FROM t" statement. Both fieldsExpanded(Default) and fieldsExpanded(Unique) will return [ a, b, a (alfa) ] list. On the other hand, for query defined by "SELECT *, a FROM t" statement, fieldsExpanded(Default) will return [ a, b, a ] list while fieldsExpanded(Unique) will return [ a, b ] list. If @a options is WithInternalFields or WithInternalFieldsAndRecordID, additional internal fields are also appended to the vector. If @a options is WithInternalFieldsAndRecordId, one fake BigInteger column is appended to make space for Record ID column used by KDbCursor implementations. For example, let city_id in TABLE persons(surname, city_id) reference cities.id in TABLE cities(id, name) and let query q be defined by "SELECT * FROM persons" statement. We want to display persons' city names instead of city_id's. To do this, cities.name has to be retrieved as well, so the following statement should be used: "SELECT * FROM persons, cities.name LEFT OUTER JOIN cities ON persons.city_id=cities.id". Thus, calling fieldsExpanded(WithInternalFieldsAndRecordId) will return 4 elements instead of 2: persons.surname, persons.city_id, cities.name, {ROWID}. The {ROWID} item is the placeholder used for fetching ROWID by KDb cursors. By default, all fields are returned in the vector even if there are multiple occurrences of one or more (options == Default). Note: You should assign the resulted vector in your space - it will be shared and implicity copied on any modification. This method's result is cached by KDbQuerySchema object. @todo js: UPDATE CACHE! */ inline KDbQueryColumnInfo::Vector fieldsExpanded( - FieldsExpandedOptions options = Default) const + KDbConnection *conn, FieldsExpandedMode mode = FieldsExpandedMode::Default) const { - return fieldsExpandedInternal(options, false); + return fieldsExpandedInternal(conn, mode, false); } /*! Like fieldsExpanded() but returns only visible fields. */ inline KDbQueryColumnInfo::Vector visibleFieldsExpanded( - FieldsExpandedOptions options = Default) const + KDbConnection *conn, FieldsExpandedMode options = FieldsExpandedMode::Default) const { - return fieldsExpandedInternal(options, true); + return fieldsExpandedInternal(conn, options, true); } /*! @return list of internal fields used for lookup columns. */ - KDbQueryColumnInfo::Vector internalFields() const; + KDbQueryColumnInfo::Vector internalFields(KDbConnection *conn) const; /*! @return info for expanded of internal field at index @a index. The returned field can be either logical or internal (for lookup), the latter case is @c true if @a index >= fieldsExpanded().count(). Equivalent of KDbQuerySchema::fieldsExpanded(WithInternalFields).at(index). */ - KDbQueryColumnInfo* expandedOrInternalField(int index) const; + KDbQueryColumnInfo* expandedOrInternalField(KDbConnection *conn, int index) const; - /*! Options used in columnsOrder(). */ - enum ColumnsOrderOptions { + //! Mode for columnsOrder() + //! @since 3.1 + enum class ColumnsOrderMode { UnexpandedList, //!< A map for unexpanded list is created UnexpandedListWithoutAsterisks, //!< A map for unexpanded list is created, with asterisks skipped ExpandedList //!< A map for expanded list is created }; /*! @return a hash for fast lookup of query columns' order. - If @a options is UnexpandedList, each KDbQueryColumnInfo pointer is mapped to the index within (unexpanded) list of fields, i.e. "*" or "table.*" asterisks are considered to be single items. - If @a options is UnexpandedListWithoutAsterisks, each KDbQueryColumnInfo pointer is mapped to the index within (unexpanded) list of columns that come from asterisks like "*" or "table.*" are not included in the map at all. - If @a options is ExpandedList (the default) this method provides is exactly opposite information compared to vector returned by fieldsExpanded(). This method's result is cached by the KDbQuerySchema object. Note: indices of internal fields (see internalFields()) are also returned here - in this case the index is counted as a sum of size(e) + i (where "e" is the list of expanded fields and i is the column index within internal fields list). This feature is used eg. at the end of KDbConnection::updateRecord() where need indices of fields (including internal) to update all the values in memory. Example use: let t be table (int id, name text, surname text) and q be query defined by a statement "select * from t". - columnsOrder(ExpandedList) will return the following map: KDbQueryColumnInfo(id)->0, KDbQueryColumnInfo(name)->1, KDbQueryColumnInfo(surname)->2. - columnsOrder(UnexpandedList) will return the following map: KDbQueryColumnInfo(id)->0, KDbQueryColumnInfo(name)->0, KDbQueryColumnInfo(surname)->0 because the column list is not expanded. This way you can use the returned index to get KDbField* pointer using field(int) method of KDbFieldList superclass. - columnsOrder(UnexpandedListWithoutAsterisks) will return the following map: KDbQueryColumnInfo(id)->0, */ - QHash columnsOrder(ColumnsOrderOptions options = ExpandedList) const; + QHash columnsOrder(KDbConnection *conn, + ColumnsOrderMode mode = ColumnsOrderMode::ExpandedList) const; /*! @return table describing order of primary key (PKEY) fields within the query. Indexing is performed against vector returned by fieldsExpanded(). It is usable for e.g. Connection::updateRecord(), when we need to locate each primary key's field in a constant time. Returned vector is owned and cached by KDbQuerySchema object. When you assign it, it is implicity shared. Its size is equal to number of primary key fields defined for master table (masterTable()->primaryKey()->fieldCount()). Each element of the returned vector: - can belong to [0..fieldsExpanded().count()-1] if there is such primary key's field in the fieldsExpanded() list. - can be equal to -1 if there is no such primary key's field in the fieldsExpanded() list. If there are more than one primary key's field included in the query, only first-found column (oin the fieldsExpanded() list) for each pkey's field is included. Returns empty vector if there is no master table or no master table's pkey. @see example for pkeyFieldCount(). @todo js: UPDATE CACHE! */ - QVector pkeyFieldsOrder() const; + QVector pkeyFieldsOrder(KDbConnection *conn) const; /*! @return number of master table's primary key fields included in this query. This method is useful to quickly check whether the vector returned by pkeyFieldsOrder() if filled completely. User e.g. in KDbConnection::updateRecord() to check if entire primary key information is specified. Examples: let table T has (ID1 INTEGER, ID2 INTEGER, A INTEGER) fields, and let (ID1, ID2) is T's primary key. -# The query defined by "SELECT * FROM T" statement contains all T's primary key's fields as T is the master table, and thus pkeyFieldCount() will return 2 (both primary key's fields are in the fieldsExpanded() list), and pkeyFieldsOrder() will return vector {0, 1}. -# The query defined by "SELECT A, ID2 FROM T" statement, and thus pkeyFieldCount() will return 1 (only one primary key's field is in the fieldsExpanded() list), and pkeyFieldsOrder() will return vector {-1, 1}, as second primary key's field is at position #1 and first field is not specified at all within the query. */ - int pkeyFieldCount(); + int pkeyFieldCount(KDbConnection *conn); /*! @return a list of field infos for all auto-incremented fields from master table of this query. This result is cached for efficiency. fieldsExpanded() is used for that. */ - KDbQueryColumnInfo::List* autoIncrementFields() const; + KDbQueryColumnInfo::List* autoIncrementFields(KDbConnection *conn) const; /*! @return a preset statement (if any). */ KDbEscapedString statement() const; /*! Forces a raw SQL statement @a sql for the query. This means that no statement is composed * from KDbQuerySchema's content. */ void setStatement(const KDbEscapedString& sql); /*! @return a string that is a result of concatenating all column names for @a infolist, with "," between each one. This is usable e.g. as argument like "field1,field2" for "INSERT INTO (xxx) ..". The result of this method is effectively cached, and it is invalidated when set of fields changes (e.g. using clear() or addField()). This method is similar to KDbFieldList::sqlFieldsList() it just uses KDbQueryColumnInfo::List instead of KDbField::List. @a escapingType can be used to alter default escaping type. If @a conn is not provided for DriverEscaping, no escaping is performed. */ static KDbEscapedString sqlColumnsList(const KDbQueryColumnInfo::List &infolist, KDbConnection *conn = nullptr, KDb::IdentifierEscapingType escapingType = KDb::DriverEscaping); /*! @return cached list of autoincrement fields created using sqlColumnsList() on a list returned by autoIncrementFields(). The field names are escaped using driver escaping. */ KDbEscapedString autoIncrementSqlFieldsList(KDbConnection *conn) const; /** * @brief Sets a WHERE expression @a exp. * * Previously set WHERE expression will be removed. A null expression * (KDbExpression()) can be passed to remove existing WHERE expresssion. * @return @c false if @a expr is not a valid WHERE expression. validate() is called * to check this. On failure the WHERE expression for this query is cleared. In this * case a string pointed by @a errorMessage (if provided) is set to a general error * message and a string pointed by @a errorDescription (if provided) is set to a * detailed description of the error. */ bool setWhereExpression(const KDbExpression &expr, QString *errorMessage = nullptr, QString *errorDescription = nullptr); /*! @return WHERE expression or 0 if this query has no WHERE expression */ KDbExpression whereExpression() const; /** * @brief Appends a part to WHERE expression. * * Simplifies creating of WHERE expression if used instead of setWhereExpression(). * @return @c false if the newly constructed WHERE expression is not valid. * validate() is called to check this. On failure the WHERE expression for this query * is left unchanged. In this case a string pointed by @a errorMessage (if provided) * is set to a general error message and a string pointed by @a errorDescription * (if provided) is set to a detailed description of the error. */ bool addToWhereExpression(KDbField *field, const QVariant &value, KDbToken relation = '=', QString *errorMessage = nullptr, QString *errorDescription = nullptr); /*! Sets a list of columns for ORDER BY section of the query. Each name on the list must be a field or alias present within the query and must not be covered by aliases. If one or more names cannot be found within the query, the method will have no effect. Any previous ORDER BY settings will be removed. Note that this information is cleared whenever you call methods that modify list of columns (KDbQueryColumnInfo), i.e. insertField(), addField(), removeField(), addExpression(), etc. (because KDbOrderByColumn items can point to a KDbQueryColumnInfo that's removed by these methods), so you should use setOrderByColumnList() method after the query is completely built. */ void setOrderByColumnList(const KDbOrderByColumnList& list); /*! @return a list of columns listed in ORDER BY section of the query. Read notes for @ref setOrderByColumnList(). */ KDbOrderByColumnList* orderByColumnList(); /*! @see orderByColumnList() */ const KDbOrderByColumnList* orderByColumnList() const; /*! @return query schema parameters. These are taked from the WHERE section (a tree of expression items). */ - QList parameters() const; + QList parameters(KDbConnection *conn) const; //! @return @c true if this query is valid /*! Detailed validation is performed in the same way as parsing of query statements * by the KDbParser. * Example :Let the query be "SELECT FROM WHERE ". * First each field from (@see fields()) is validated using * KDbField::expression().validate(). Then the (@see * whereExpression()) * is validated using KDbExpression::validate(). * * On error a string pointed by @a errorMessage (if provided) is set to a general * error message and a string pointed by @a errorDescription (if provided) is set to a * detailed description of the error. */ //! @todo add tests bool validate(QString *errorMessage = nullptr, QString *errorDescription = nullptr); - class Private; // Protected not private because of the parser - protected: - //! @internal associates @a conn with this query so it's possible to find tables - explicit KDbQuerySchema(KDbConnection *conn); - - void computeFieldsExpanded() const; + KDbQuerySchemaFieldsExpanded *computeFieldsExpanded(KDbConnection *conn) const; - //! Used by fieldsExpanded(FieldsExpandedOptions) - //! and visibleFieldsExpanded(FieldsExpandedOptions options). - KDbQueryColumnInfo::Vector fieldsExpandedInternal(FieldsExpandedOptions options, + //! Used by fieldsExpanded(KDbConnection*, FieldsExpandedMode) + //! and visibleFieldsExpanded(KDbConnection*, FieldsExpandedMode). + KDbQueryColumnInfo::Vector fieldsExpandedInternal(KDbConnection *conn, + FieldsExpandedMode mode, bool onlyVisible) const; /** Internal method used by all insert*Field methods. * The new column can also be explicitly bound to a specific position on tables list. * @a bindToTable is a table index within the query for which the field should be bound. * If @a bindToTable is -1, no particular table will be bound. * @see tableBoundToColumn(int columnPosition) */ bool insertFieldInternal(int position, KDbField *field, int bindToTable, bool visible); /** * Internal method used by add*Asterisk() methods. * Appends @a asterisk at the and of columns list, sets visibility. */ bool addAsteriskInternal(KDbQueryAsterisk *asterisk, bool visible); /** Internal method used by all add*Expression methods. * Appends expression @a expr at the and of columns list, sets visibility. */ bool addExpressionInternal(const KDbExpression& expr, bool visible); /** Internal method used by a query parser. */ void setWhereExpressionInternal(const KDbExpression &expr); - Private * const d; + friend class KDbQuerySchemaPrivate; + + Q_DISABLE_COPY(KDbQuerySchema) + KDbQuerySchemaPrivate * const d; }; -//! Sends query schema information @a query to debug output @a dbg. -KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbQuerySchema& query); +//! A pair (connection, table-or-schema) for QDebug operator<< +//! @since 3.1 +typedef std::tuple KDbConnectionAndQuerySchema; + +//! Sends connection and query schema information @a connectionAndSchema to debug output @a dbg. +//! @since 3.1 +KDB_EXPORT QDebug operator<<(QDebug dbg, + const KDbConnectionAndQuerySchema &connectionAndSchema); #endif diff --git a/src/KDbQuerySchema_p.cpp b/src/KDbQuerySchema_p.cpp index c57b4a84..146c67b1 100644 --- a/src/KDbQuerySchema_p.cpp +++ b/src/KDbQuerySchema_p.cpp @@ -1,219 +1,148 @@ /* This file is part of the KDE project Copyright (C) 2003-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. */ #include "KDbQuerySchema_p.h" +#include "KDbConnection.h" +#include "KDbConnection_p.h" #include "KDbOrderByColumn.h" -KDbQuerySchema::Private::Private(KDbQuerySchema* q, Private* copy) +KDbQuerySchemaPrivate::KDbQuerySchemaPrivate(KDbQuerySchema* q, KDbQuerySchemaPrivate* copy) : query(q) , masterTable(nullptr) , fakeRecordIdField(nullptr) , fakeRecordIdCol(nullptr) - , conn(nullptr) , maxIndexWithAlias(-1) , visibility(64) - , fieldsExpanded(nullptr) - , visibleFieldsExpanded(nullptr) - , internalFields(nullptr) - , fieldsExpandedWithInternalAndRecordId(nullptr) - , visibleFieldsExpandedWithInternalAndRecordId(nullptr) - , fieldsExpandedWithInternal(nullptr) - , visibleFieldsExpandedWithInternal(nullptr) , orderByColumnList(nullptr) , autoincFields(nullptr) - , columnsOrder(nullptr) - , columnsOrderWithoutAsterisks(nullptr) - , columnsOrderExpanded(nullptr) , pkeyFieldsOrder(nullptr) , pkeyFieldCount(0) , tablesBoundToColumns(64, -1) // will be resized if needed - , ownedVisibleColumns(nullptr) , regenerateExprAliases(false) { visibility.fill(false); if (copy) { // deep copy *this = *copy; // - fieldsExpanded = nullptr; - visibleFieldsExpanded = nullptr; - internalFields = nullptr; - columnsOrder = nullptr; - columnsOrderWithoutAsterisks = nullptr; - columnsOrderExpanded = nullptr; orderByColumnList = nullptr; autoincFields = nullptr; autoIncrementSqlFieldsList.clear(); - columnInfosByNameExpanded.clear(); - columnInfosByName.clear(); - ownedVisibleColumns = nullptr; - fieldsExpandedWithInternalAndRecordId = nullptr; - visibleFieldsExpandedWithInternalAndRecordId = nullptr; - fieldsExpandedWithInternal = nullptr; - visibleFieldsExpandedWithInternal = nullptr; pkeyFieldsOrder = nullptr; fakeRecordIdCol = nullptr; fakeRecordIdField = nullptr; - conn = nullptr; - ownedVisibleColumns = nullptr; // if (!copy->whereExpr.isNull()) { whereExpr = copy->whereExpr.clone(); } // "*this = *copy" causes copying pointers; pull of them without destroying, // will be deep-copied in the KDbQuerySchema ctor. asterisks.setAutoDelete(false); asterisks.clear(); asterisks.setAutoDelete(true); } else { orderByColumnList = new KDbOrderByColumnList; } } -KDbQuerySchema::Private::~Private() +KDbQuerySchemaPrivate::~KDbQuerySchemaPrivate() { + if (recentConnection) { + recentConnection->d->insertFieldsExpanded(query, nullptr); + } delete orderByColumnList; delete autoincFields; - delete columnsOrder; - delete columnsOrderWithoutAsterisks; - delete columnsOrderExpanded; delete pkeyFieldsOrder; delete fakeRecordIdCol; delete fakeRecordIdField; - delete ownedVisibleColumns; - if (fieldsExpanded) { - qDeleteAll(*fieldsExpanded); - delete fieldsExpanded; - } - if (internalFields) { - qDeleteAll(*internalFields); - delete internalFields; - } - delete fieldsExpandedWithInternalAndRecordId; - delete visibleFieldsExpandedWithInternalAndRecordId; - delete fieldsExpandedWithInternal; - delete visibleFieldsExpandedWithInternal; -} - -//static -KDbQuerySchema* KDbQuerySchema::Private::createQuery(KDbConnection *conn) -{ - return new KDbQuerySchema(conn); } -void KDbQuerySchema::Private::clear() +void KDbQuerySchemaPrivate::clear() { columnAliases.clear(); tableAliases.clear(); asterisks.clear(); relations.clear(); masterTable = nullptr; tables.clear(); clearCachedData(); delete pkeyFieldsOrder; pkeyFieldsOrder = nullptr; visibility.fill(false); tablesBoundToColumns = QVector(64, -1); // will be resized if needed tablePositionsForAliases.clear(); columnPositionsForAliases.clear(); } -void KDbQuerySchema::Private::clearCachedData() +void KDbQuerySchemaPrivate::clearCachedData() { if (orderByColumnList) { orderByColumnList->clear(); } - if (fieldsExpanded) { - delete columnsOrder; - columnsOrder = nullptr; - delete columnsOrderWithoutAsterisks; - columnsOrderWithoutAsterisks = nullptr; - delete columnsOrderExpanded; - columnsOrderExpanded = nullptr; - delete autoincFields; - autoincFields = nullptr; - autoIncrementSqlFieldsList.clear(); - columnInfosByNameExpanded.clear(); - columnInfosByName.clear(); - delete ownedVisibleColumns; - ownedVisibleColumns = nullptr; - qDeleteAll(*fieldsExpanded); - delete fieldsExpanded; - fieldsExpanded = nullptr; - delete visibleFieldsExpanded; // NO qDeleteAll, items not owned - visibleFieldsExpanded = nullptr; - if (internalFields) { - qDeleteAll(*internalFields); - delete internalFields; - internalFields = nullptr; - } - delete fieldsExpandedWithInternalAndRecordId; - fieldsExpandedWithInternalAndRecordId = nullptr; - delete visibleFieldsExpandedWithInternalAndRecordId; - visibleFieldsExpandedWithInternalAndRecordId = nullptr; - delete fieldsExpandedWithInternal; - fieldsExpandedWithInternal = nullptr; - delete visibleFieldsExpandedWithInternal; - visibleFieldsExpandedWithInternal = nullptr; + if (recentConnection) { + recentConnection->d->insertFieldsExpanded(query, nullptr); } + delete autoincFields; + autoincFields = nullptr; + autoIncrementSqlFieldsList.clear(); } -void KDbQuerySchema::Private::setColumnAlias(int position, const QString& alias) +void KDbQuerySchemaPrivate::setColumnAlias(int position, const QString& alias) { if (alias.isEmpty()) { columnAliases.remove(position); maxIndexWithAlias = -1; } else { setColumnAliasInternal(position, alias); } } -void KDbQuerySchema::Private::tryRegenerateExprAliases() +void KDbQuerySchemaPrivate::tryRegenerateExprAliases() { if (!regenerateExprAliases) return; //regenerate missing aliases for experessions int colNum = 0; //used to generate a name QString columnAlias; int p = -1; foreach(KDbField* f, *query->fields()) { p++; if (f->isExpression() && columnAliases.value(p).isEmpty()) { //missing do { //find 1st unused colNum++; columnAlias = tr("expr%1", "short for 'expression' word, it will expand " "to 'expr1', 'expr2', etc. Please use ONLY latin " "letters and DON'T use '.'").arg(colNum); columnAlias = KDb::stringToIdentifier(columnAlias); // sanity fix, translators make mistakes! } while (-1 != tablePositionForAlias(columnAlias)); setColumnAliasInternal(p, columnAlias); } } regenerateExprAliases = false; } -void KDbQuerySchema::Private::setColumnAliasInternal(int position, const QString& alias) +void KDbQuerySchemaPrivate::setColumnAliasInternal(int position, const QString& alias) { columnAliases.insert(position, alias.toLower()); columnPositionsForAliases.insert(alias.toLower(), position); maxIndexWithAlias = qMax(maxIndexWithAlias, position); } diff --git a/src/KDbQuerySchema_p.h b/src/KDbQuerySchema_p.h index 8763ac54..bd642b51 100644 --- a/src/KDbQuerySchema_p.h +++ b/src/KDbQuerySchema_p.h @@ -1,225 +1,240 @@ /* This file is part of the KDE project Copyright (C) 2003-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_QUERYSCHEMA_P_H #define KDB_QUERYSCHEMA_P_H #include "KDbDriver.h" #include "KDbExpression.h" #include "KDbQuerySchema.h" #include #include class KDbConnection; //! @internal -class Q_DECL_HIDDEN KDbQuerySchema::Private +class KDbQuerySchemaPrivate { Q_DECLARE_TR_FUNCTIONS(KDbQuerySchema) public: - explicit Private(KDbQuerySchema* q, Private* copy = nullptr); + explicit KDbQuerySchemaPrivate(KDbQuerySchema* q, KDbQuerySchemaPrivate* copy = nullptr); - ~Private(); + ~KDbQuerySchemaPrivate(); //! @return a new query that's associated with @a conn. Used internally, e.g. by the parser. //! Uses an internal KDbQuerySchema(KDbConnection*) ctor. static KDbQuerySchema* createQuery(KDbConnection *conn); void clear(); void clearCachedData(); void setColumnAlias(int position, const QString& alias); inline void setTableAlias(int position, const QString& alias) { tableAliases.insert(position, alias.toLower()); tablePositionsForAliases.insert(alias.toLower(), position); } inline int columnAliasesCount() { tryRegenerateExprAliases(); return columnAliases.count(); } inline QString columnAlias(int position) { tryRegenerateExprAliases(); return columnAliases.value(position); } inline bool hasColumnAlias(int position) { tryRegenerateExprAliases(); return columnAliases.contains(position); } inline void removeTablePositionForAlias(const QString& alias) { tablePositionsForAliases.remove(alias.toLower()); } inline int tablePositionForAlias(const QString& alias) const { return tablePositionsForAliases.value(alias.toLower(), -1); } inline int columnPositionForAlias(const QString& alias) const { return columnPositionsForAliases.value(alias.toLower(), -1); } //! Accessor for buildSelectQuery() static void setWhereExpressionInternal(KDbQuerySchema *query, const KDbExpression &expr) { query->d->whereExpr = expr; } KDbQuerySchema *query; /*! Master table of the query. Can be @c nullptr. Any data modifications can be performed if we know master table. If null, query's records cannot be modified. */ KDbTableSchema *masterTable; /*! List of tables used in this query */ QList tables; KDbField *fakeRecordIdField; //! used to mark a place for record Id KDbQueryColumnInfo *fakeRecordIdCol; //! used to mark a place for record Id - //! Connection on which this query operates - //! @todo use equivalent of QPointer - KDbConnection* conn; - protected: void tryRegenerateExprAliases(); void setColumnAliasInternal(int position, const QString& alias); /*! Used to mapping columns to its aliases for this query */ QHash columnAliases; /*! Collects table positions for aliases: used in tablePositionForAlias(). */ QHash tablePositionsForAliases; /*! Collects column positions for aliases: used in columnPositionForAlias(). */ QHash columnPositionsForAliases; public: /*! Used to mapping tables to its aliases for this query */ QHash tableAliases; /*! Helper used with aliases */ int maxIndexWithAlias; /*! Used to store visibility flag for every field */ QBitArray visibility; /*! List of asterisks defined for this query */ KDbField::List asterisks; - /*! Temporary field vector for using in fieldsExpanded() */ - KDbQueryColumnInfo::Vector *fieldsExpanded; - - /*! Like fieldsExpanded but only visible column infos; infos are not owned. */ - KDbQueryColumnInfo::Vector *visibleFieldsExpanded; - - /*! Temporary field vector containing internal fields used for lookup columns. */ - KDbQueryColumnInfo::Vector *internalFields; - - /*! Temporary, used to cache sum of expanded fields and internal fields (+record Id) used for lookup columns. - Contains not auto-deleted items.*/ - KDbQueryColumnInfo::Vector *fieldsExpandedWithInternalAndRecordId; - - /*! Like fieldsExpandedWithInternalAndRecordId but only contains visible column infos; infos are not owned.*/ - KDbQueryColumnInfo::Vector *visibleFieldsExpandedWithInternalAndRecordId; - - /*! Temporary, used to cache sum of expanded fields and internal fields used for lookup columns. - Contains not auto-deleted items.*/ - KDbQueryColumnInfo::Vector *fieldsExpandedWithInternal; - - /*! Like fieldsExpandedWithInternal but only contains visible column infos; infos are not owned.*/ - KDbQueryColumnInfo::Vector *visibleFieldsExpandedWithInternal; - /*! A list of fields for ORDER BY section. @see KDbQuerySchema::orderByColumnList(). */ KDbOrderByColumnList* orderByColumnList; /*! A cache for autoIncrementFields(). */ KDbQueryColumnInfo::List *autoincFields; /*! A cache for autoIncrementSqlFieldsList(). */ KDbEscapedString autoIncrementSqlFieldsList; QWeakPointer lastUsedDriverForAutoIncrementSQLFieldsList; - /*! A hash for fast lookup of query columns' order (unexpanded version). */ - QHash *columnsOrder; - - /*! A hash for fast lookup of query columns' order (unexpanded version without asterisks). */ - QHash *columnsOrderWithoutAsterisks; - - /*! A hash for fast lookup of query columns' order. - This is exactly opposite information compared to vector returned - by fieldsExpanded() */ - QHash *columnsOrderExpanded; - /*! order of PKEY fields (e.g. for updateRecord() ) */ QVector *pkeyFieldsOrder; /*! number of PKEY fields within the query */ int pkeyFieldCount; /*! Forced (predefined) raw SQL statement */ KDbEscapedString sql; /*! Relationships defined for this query. */ QList relations; /*! Information about columns bound to tables. Used if table is used in FROM section more than once (using table aliases). This list is updated by insertField(int position, KDbField *field, int bindToTable, bool visible), using bindToTable parameter. Example: for this statement: SELECT t1.a, othertable.x, t2.b FROM table t1, table t2, othertable; tablesBoundToColumns list looks like this: [ 0, -1, 1 ] - first column is bound to table 0 "t1" - second coulmn is not specially bound (othertable.x isn't ambiguous) - third column is bound to table 1 "t2" */ QVector tablesBoundToColumns; /*! WHERE expression */ KDbExpression whereExpr; + /*! Set by insertField(): true, if aliases for expression columns should + be generated on next columnAlias() call. */ + bool regenerateExprAliases; + + //! Points to connection recently used for caching + //! @todo use equivalent of QPointer + KDbConnection *recentConnection = nullptr; +}; + +//! Information about expanded fields for a single query schema, used for caching +class KDbQuerySchemaFieldsExpanded +{ +public: + inline KDbQuerySchemaFieldsExpanded() + { + } + + inline ~KDbQuerySchemaFieldsExpanded() + { + qDeleteAll(fieldsExpanded); + qDeleteAll(internalFields); + } + + /*! Temporary field vector for using in fieldsExpanded() */ + KDbQueryColumnInfo::Vector fieldsExpanded; + + /*! Like fieldsExpanded but only visible column infos; infos are not owned. */ + KDbQueryColumnInfo::Vector visibleFieldsExpanded; + + /*! Temporary field vector containing internal fields used for lookup columns. */ + KDbQueryColumnInfo::Vector internalFields; + + /*! Temporary, used to cache sum of expanded fields and internal fields (+record Id) used for lookup columns. + Contains not auto-deleted items.*/ + KDbQueryColumnInfo::Vector fieldsExpandedWithInternalAndRecordId; + + /*! Like fieldsExpandedWithInternalAndRecordId but only contains visible column infos; infos are not owned.*/ + KDbQueryColumnInfo::Vector visibleFieldsExpandedWithInternalAndRecordId; + + /*! Temporary, used to cache sum of expanded fields and internal fields used for lookup columns. + Contains not auto-deleted items.*/ + KDbQueryColumnInfo::Vector fieldsExpandedWithInternal; + + /*! Like fieldsExpandedWithInternal but only contains visible column infos; infos are not owned.*/ + KDbQueryColumnInfo::Vector visibleFieldsExpandedWithInternal; + + /*! A hash for fast lookup of query columns' order (unexpanded version). */ + QHash columnsOrder; + + /*! A hash for fast lookup of query columns' order (unexpanded version without asterisks). */ + QHash columnsOrderWithoutAsterisks; + + /*! A hash for fast lookup of query columns' order. + This is exactly opposite information compared to vector returned + by fieldsExpanded() */ + QHash columnsOrderExpanded; + QHash columnInfosByNameExpanded; QHash columnInfosByName; //!< Same as columnInfosByNameExpanded but asterisks are skipped //! field schemas created for multiple joined columns like a||' '||b||' '||c - KDbField::List *ownedVisibleColumns; - - /*! Set by insertField(): true, if aliases for expression columns should - be generated on next columnAlias() call. */ - bool regenerateExprAliases; + KDbField::List ownedVisibleColumns; }; //! @return identifier string @a name escaped using @a conn connection and type @a escapingType QString escapeIdentifier(const QString& name, KDbConnection *conn, KDb::IdentifierEscapingType escapingType); #endif diff --git a/src/KDbTableOrQuerySchema.cpp b/src/KDbTableOrQuerySchema.cpp index 7207c6f4..152f240d 100644 --- a/src/KDbTableOrQuerySchema.cpp +++ b/src/KDbTableOrQuerySchema.cpp @@ -1,199 +1,196 @@ /* This file is part of the KDE project Copyright (C) 2004-2015 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 "KDbTableOrQuerySchema.h" #include "KDbConnection.h" #include "KDbQuerySchema.h" #include "kdb_debug.h" class Q_DECL_HIDDEN KDbTableOrQuerySchema::Private { public: Private() {} //! The name is kept here because m_table and m_table can be 0 //! and we still want name() and acptionOrName() work. QByteArray name; KDbTableSchema* table; KDbQuerySchema* query; private: Q_DISABLE_COPY(Private) }; KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbConnection *conn, const QByteArray& name) : d(new Private) { d->name = name; d->table = conn->tableSchema(QLatin1String(name)); d->query = d->table ? nullptr : conn->querySchema(QLatin1String(name)); if (!d->table && !d->query) { kdbWarning() << "tableOrQuery is neither table nor query!"; } } KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbConnection *conn, const QByteArray& name, Type type) : d(new Private) { d->name = name; d->table = type == Type::Table ? conn->tableSchema(QLatin1String(name)) : nullptr; d->query = type == Type::Query ? conn->querySchema(QLatin1String(name)) : nullptr; if (type == Type::Table && !d->table) { kdbWarning() << "no table specified!"; } if (type == Type::Query && !d->query) { kdbWarning() << "no query specified!"; } } KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbFieldList *tableOrQuery) : d(new Private) { d->table = dynamic_cast(tableOrQuery); d->query = dynamic_cast(tableOrQuery); if (!d->table && !d->query) { kdbWarning() << "tableOrQuery is neither table nor query!"; } } KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbConnection *conn, int id) : d(new Private) { d->table = conn->tableSchema(id); d->query = d->table ? nullptr : conn->querySchema(id); if (!d->table && !d->query) { kdbWarning() << "no table or query found for id==" << id; } } KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbTableSchema* table) : d(new Private) { d->table = table; d->query = nullptr; if (!d->table) { kdbWarning() << "no table specified!"; } } KDbTableOrQuerySchema::KDbTableOrQuerySchema(KDbQuerySchema* query) : d(new Private) { d->table = nullptr; d->query = query; if (!d->query) { kdbWarning() << "no query specified!"; } } KDbTableOrQuerySchema::~KDbTableOrQuerySchema() { delete d; } -int KDbTableOrQuerySchema::fieldCount() const +int KDbTableOrQuerySchema::fieldCount(KDbConnection *conn) const { if (d->table) return d->table->fieldCount(); - if (d->query) - return d->query->fieldsExpanded().size(); - return 0; + if (d->query && conn) + return d->query->fieldsExpanded(conn).size(); + return -1; } -const KDbQueryColumnInfo::Vector KDbTableOrQuerySchema::columns(bool unique) +const KDbQueryColumnInfo::Vector KDbTableOrQuerySchema::columns(KDbConnection * conn, ColumnsMode mode) { - if (d->table) - return d->table->query()->fieldsExpanded(unique ? KDbQuerySchema::Unique : KDbQuerySchema::Default); - - if (d->query) - return d->query->fieldsExpanded(unique ? KDbQuerySchema::Unique : KDbQuerySchema::Default); - + if (d->table) { + return d->table->query()->fieldsExpanded(conn, mode == ColumnsMode::Unique + ? KDbQuerySchema::FieldsExpandedMode::Unique + : KDbQuerySchema::FieldsExpandedMode::Default); + } + if (d->query) { + return d->query->fieldsExpanded(conn, mode == ColumnsMode::Unique + ? KDbQuerySchema::FieldsExpandedMode::Unique + : KDbQuerySchema::FieldsExpandedMode::Default); + } kdbWarning() << "no query or table specified!"; return KDbQueryColumnInfo::Vector(); } QByteArray KDbTableOrQuerySchema::name() const { if (d->table) return d->table->name().toLatin1(); if (d->query) return d->query->name().toLatin1(); return d->name; } QString KDbTableOrQuerySchema::captionOrName() const { KDbObject *object = d->table ? static_cast(d->table) : static_cast(d->query); if (!object) return QLatin1String(d->name); return object->caption().isEmpty() ? object->name() : object->caption(); } KDbField* KDbTableOrQuerySchema::field(const QString& name) { if (d->table) return d->table->field(name); if (d->query) return d->query->field(name); return nullptr; } -KDbQueryColumnInfo* KDbTableOrQuerySchema::columnInfo(const QString& name) +KDbQueryColumnInfo* KDbTableOrQuerySchema::columnInfo(KDbConnection *conn, const QString& name) { if (d->table) - return d->table->query()->columnInfo(name); + return d->table->query()->columnInfo(conn, name); if (d->query) - return d->query->columnInfo(name); + return d->query->columnInfo(conn, name); return nullptr; } //! Sends information about table or query schema @a schema to debug output @a dbg. -QDebug operator<<(QDebug dbg, const KDbTableOrQuerySchema& schema) +QDebug operator<<(QDebug dbg, const KDbConnectionAndSchema &connectionAndSchema) { - if (schema.table()) - dbg.nospace() << *schema.table(); - else if (schema.query()) - dbg.nospace() << *schema.query(); + if (std::get<1>(connectionAndSchema).table()) { + dbg.nospace() << *std::get<1>(connectionAndSchema).table(); + } else if (std::get<1>(connectionAndSchema).query()) { + dbg.nospace() << KDbConnectionAndQuerySchema(std::get<0>(connectionAndSchema), + *std::get<1>(connectionAndSchema).query()); + } return dbg.space(); } -KDbConnection* KDbTableOrQuerySchema::connection() const -{ - if (d->table) - return d->table->connection(); - else if (d->query) - return d->query->connection(); - return nullptr; -} - KDbQuerySchema* KDbTableOrQuerySchema::query() const { return d->query; } KDbTableSchema* KDbTableOrQuerySchema::table() const { return d->table; } diff --git a/src/KDbTableOrQuerySchema.h b/src/KDbTableOrQuerySchema.h index e29cc26a..2906ea56 100644 --- a/src/KDbTableOrQuerySchema.h +++ b/src/KDbTableOrQuerySchema.h @@ -1,117 +1,130 @@ /* This file is part of the KDE project Copyright (C) 2004-2015 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 KDBTABLEORQUERYSCHEMA_H #define KDBTABLEORQUERYSCHEMA_H #include #include "KDbQueryColumnInfo.h" class KDbConnection; class KDbFieldList; class KDbTableSchema; class KDbQuerySchema; /*! Variant class providing a pointer to table or query. */ class KDB_EXPORT KDbTableOrQuerySchema { public: //! Type of object: table or query //! @since 3.1 enum class Type { Table, Query }; /*! Creates a new KDbTableOrQuerySchema variant object, retrieving table or query schema using @a conn connection and @a name. If both table and query exists for @a name, table has priority over query. Check whether a query or table has been found by testing (query() || table()) expression. */ KDbTableOrQuerySchema(KDbConnection *conn, const QByteArray& name); /*! Creates a new KDbTableOrQuerySchema variant object, retrieving table or query schema using @a conn connection and @a name. If @a type is Table, @a name is assumed to be a table name, otherwise @a name is assumed to be a query name. Check whether a query or table has been found by testing (query() || table()) expression. @since 3.1 */ KDbTableOrQuerySchema(KDbConnection *conn, const QByteArray &name, Type type); /*! Creates a new KDbTableOrQuerySchema variant object. @a tableOrQuery should be of class KDbTableSchema or KDbQuerySchema. Check whether a query or table has been found by testing (query() || table()) expression. */ explicit KDbTableOrQuerySchema(KDbFieldList *tableOrQuery); /*! Creates a new KDbTableOrQuerySchema variant object, retrieving table or query schema using @a conn connection and @a id. Check whether a query or table has been found by testing (query() || table()) expression. */ KDbTableOrQuerySchema(KDbConnection *conn, int id); /*! Creates a new KDbTableOrQuerySchema variant object, keeping a pointer to @a table object. */ explicit KDbTableOrQuerySchema(KDbTableSchema* table); /*! Creates a new KDbTableOrQuerySchema variant object, keeping a pointer to @a query object. */ explicit KDbTableOrQuerySchema(KDbQuerySchema* query); ~KDbTableOrQuerySchema(); //! @return a pointer to the query if it's provided KDbQuerySchema* query() const; //! @return a pointer to the table if it's provided KDbTableSchema* table() const; //! @return name of a query or table QByteArray name() const; //! @return caption (if present) or name of the table/query QString captionOrName() const; - //! @return number of fields - int fieldCount() const; + /** + * @brief Returns number of columns within record set returned from specified table or query + * + * In case of query expanded fields list is counted. + * For tables @a conn is not required. + * Returns -1 if the object has neither table or query assigned. + * Returns -1 if the object has query assigned but @a conn is @c nullptr. + */ + int fieldCount(KDbConnection *conn) const; + + /*! Mode for columns(). */ + enum class ColumnsMode { + NonUnique, //!< Non-unique columns are returned + Unique //!< Unique columns are returned + }; //! @return all columns for the table or the query - const KDbQueryColumnInfo::Vector columns(bool unique = false); + const KDbQueryColumnInfo::Vector columns(KDbConnection *conn, ColumnsMode mode = ColumnsMode::NonUnique); /*! @return a field of the table or the query schema for name @a name or 0 if there is no such field. */ KDbField* field(const QString& name); /*! Like KDbField* field(const QString& name); but returns all information associated with field/column @a name. */ - KDbQueryColumnInfo* columnInfo(const QString& name); - - /*! @return connection object, for table or query or 0 if there's no table or query defined. */ - KDbConnection* connection() const; + KDbQueryColumnInfo* columnInfo(KDbConnection *conn, const QString& name); private: class Private; Private * const d; Q_DISABLE_COPY(KDbTableOrQuerySchema) }; -namespace KDb { -//! Sends information about table or query schema @a schema to debug output @a dbg. -KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbTableOrQuerySchema& schema); -} +//! A pair (connection, table-or-schema) for QDebug operator<< +//! @since 3.1 +typedef std::tuple KDbConnectionAndSchema; + +//! Sends information about table or query schema and connection @a connectionAndSchema to debug output @a dbg. +//! @since 3.1 +KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbConnectionAndSchema &connectionAndSchema); #endif diff --git a/src/KDbTableSchema.h b/src/KDbTableSchema.h index 37155999..49cbc844 100644 --- a/src/KDbTableSchema.h +++ b/src/KDbTableSchema.h @@ -1,226 +1,228 @@ /* This file is part of the KDE project Copyright (C) 2003 Joseph Wenninger Copyright (C) 2003-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_TABLESCHEMA_H #define KDB_TABLESCHEMA_H #include #include #include "KDbFieldList.h" #include "KDbIndexSchema.h" class KDbConnection; class KDbLookupFieldSchema; +class KDbFieldPrivate; /*! Provides information about native database table that can be stored using KDb database engine. */ class KDB_EXPORT KDbTableSchema : public KDbFieldList, public KDbObject { public: explicit KDbTableSchema(const QString& name); explicit KDbTableSchema(const KDbObject& object); KDbTableSchema(); /*! Copy constructor. If @a copyId is true, it's copied as well, otherwise the table id becomes -1, what is usable when we want to store the copy as an independent table. */ explicit KDbTableSchema(const KDbTableSchema& ts, bool copyId); /*! Copy constructor like @ref KDbTableSchema(const KDbTableSchema&, bool). @a id is set as the table identifier. This is rarely usable, e.g. in project and data migration routines when we need to need deal with unique identifiers; @see KexiMigrate::performImport(). */ KDbTableSchema(const KDbTableSchema& ts, int id); ~KDbTableSchema() override; /*! Inserts @a field into a specified position (@a index). 'order' property of @a field is set automatically. @c false is returned if @a field is @c nullptr or @a index is invalid. */ bool insertField(int index, KDbField *field) override; /*! Reimplemented for internal reasons. */ bool removeField(KDbField *field) override; /*! @return list of fields that are primary key of this table. This method never returns @c nullptr value, if there is no primary key, empty KDbIndexSchema object is returned. KDbIndexSchema object is owned by the table schema. */ KDbIndexSchema* primaryKey(); //! @overload KDbIndexSchema* primaryKey() const KDbIndexSchema* primaryKey() const; /*! Sets table's primary key index to @a pkey. Pass pkey as @c nullptr to unassign existing primary key. In this case "primary" property of previous primary key KDbIndexSchema object that will be cleared, making it an ordinary index. If this table already has primary key assigned, it is unassigned using setPrimaryKey(nullptr). Before assigning as primary key, you should add the index to indices list with addIndex() (this is not done automatically!). */ void setPrimaryKey(KDbIndexSchema *pkey); const QList::ConstIterator indicesIterator() const; const QList* indices() const; //! Adds index @a index to this table schema //! Ownership of the index is transferred to the table schema. //! @return true on success //! @since 3.1 bool addIndex(KDbIndexSchema *index); //! Removes index @a index from this table schema //! Ownership of the index is transferred to the table schema. //! @return true on success //! @since 3.1 bool removeIndex(KDbIndexSchema *index); /*! Creates a copy of index @a index with references moved to fields of this table. The new index is added to this table schema. Table fields are taken by name from this table. This way it's possible to copy index owned by other table and add it to another table, e.g. a copied one. To copy an index from another table, call: @code KDbIndexSchema *originalIndex = anotherTable->indices()->at(...); KDbIndexSchema *newIndex = table->copyIndex(*originalIndex); // newIndex is now created and is added to the table 'table' @endcode To copy an index within the same table, call: @code KDbIndexSchema *originalIndex = table->indices()->at(...); KDbIndexSchema *newIndex = table->copyIndex(*originalIndex); // newIndex is now created and is added to the table @endcode @since 3.1 @todo All relationships should be also copied */ KDbIndexSchema* copyIndexFrom(const KDbIndexSchema& index); /*! Removes all fields from the list, clears name and all other properties. @see KDbFieldList::clear() */ void clear() override; /*! Sends information about fields of this table schema to debug output @a dbg. */ QDebug debugFields(QDebug dbg) const; - /*! @return connection object if table was created/retrieved using a connection, - otherwise 0. */ - KDbConnection* connection() const; - /*! @return true if this is internal KDb's table. Internal tables are hidden in applications (if desired) but are available for schema export/import functionality. Any internal KDb system table's schema (kexi__*) has cleared its KDbObject part, e.g. id=-1 for such table, and no description, caption and so on. This is because it represents a native database table rather that extended Kexi table. KDbTableSchema object has this property set to false, KDbInternalTableSchema has it set to true. */ bool isInternal() const; /*! @return query schema object that is defined by "select * from " This query schema object is owned by the table schema object. It is convenient way to get such a query when it is not available otherwise. Always returns non-0. */ KDbQuerySchema* query(); /*! @return any field not being a part of primary key of this table. If there is no such field, returns @c nullptr. */ KDbField* anyNonPKField(); /*! Sets lookup field schema @a lookupFieldSchema for @a fieldName. Passing @c nullptr @a lookupFieldSchema will remove the previously set lookup field. @return true if @a lookupFieldSchema has been added, or false if there is no such field @a fieldName. */ bool setLookupFieldSchema(const QString& fieldName, KDbLookupFieldSchema *lookupFieldSchema); /*! @return lookup field schema for @a field. 0 is returned if there is no such field in the table or this field has no lookup schema. Note that even id non-zero is returned here, you may want to check whether lookup field's recordSource().name() is empty (if so, the field should behave as there was no lookup field defined at all). */ KDbLookupFieldSchema *lookupFieldSchema(const KDbField& field); //! @overload const KDbLookupFieldSchema *lookupFieldSchema(const KDbField& field) const; /*! @overload KDbLookupFieldSchema *KDbTableSchema::lookupFieldSchema( KDbField& field ) const */ KDbLookupFieldSchema *lookupFieldSchema(const QString& fieldName); /*! @return list of lookup field schemas for this table. The order is the same as the order of fields within the table. */ QVector lookupFields() const; protected: /*! Automatically retrieves table schema via connection. */ explicit KDbTableSchema(KDbConnection *conn, const QString & name = QString()); + /*! @return connection object if table was created/retrieved using a connection, + otherwise @c nullptr. */ + KDbConnection* connection() const; + /*! For KDbConnection. */ void setConnection(KDbConnection* conn); private: //! Used by some ctors. void init(KDbConnection* conn); //! Used by some ctors. void init(const KDbTableSchema& ts, bool copyId); class Private; Private * const d; friend class KDbConnection; friend class KDbNativeStatementBuilder; + friend class KDbFieldPrivate; Q_DISABLE_COPY(KDbTableSchema) }; /*! Internal table with a name @a name. Rarely used. Use KDbConnection::createTable() to create a table using this schema. The table will not be visible as user table. For example, 'kexi__blobs' table is created this way by Kexi application. */ class KDB_EXPORT KDbInternalTableSchema : public KDbTableSchema { public: explicit KDbInternalTableSchema(const QString& name); explicit KDbInternalTableSchema(const KDbTableSchema& ts); KDbInternalTableSchema(const KDbInternalTableSchema& ts); ~KDbInternalTableSchema() override; private: class Private; Private * const d; }; //! Sends information about table schema @a table to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbTableSchema& table); //! Sends information about internal table schema @a table to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbInternalTableSchema& table); #endif diff --git a/src/KDbTransaction.cpp b/src/KDbTransaction.cpp index f8442118..e0ae9e8c 100644 --- a/src/KDbTransaction.cpp +++ b/src/KDbTransaction.cpp @@ -1,254 +1,264 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbTransaction.h" #include "KDbConnection.h" #include "KDbTransactionData.h" #include "KDbTransactionGuard.h" #include "kdb_debug.h" #ifdef KDB_TRANSACTIONS_DEBUG //helper for debugging int KDbTransaction_globalcount = 0; KDB_EXPORT int KDbTransaction::globalCount() { return KDbTransaction_globalcount; } int KDbTransactionData_globalcount = 0; KDB_EXPORT int KDbTransactionData::globalCount() { return KDbTransactionData_globalcount; } #endif class Q_DECL_HIDDEN KDbTransactionData::Private { public: Private(KDbConnection *c) : connection(c) { Q_ASSERT(connection); } KDbConnection *connection; bool active = true; int refcount = 1; }; KDbTransactionData::KDbTransactionData(KDbConnection *connection) : d(new Private(connection)) { #ifdef KDB_TRANSACTIONS_DEBUG KDbTransaction_globalcount++; // because of refcount is initialized to 1 KDbTransactionData_globalcount++; transactionsDebug() << "-- globalcount ==" << KDbTransactionData_globalcount; #endif } KDbTransactionData::~KDbTransactionData() { #ifdef KDB_TRANSACTIONS_DEBUG KDbTransactionData_globalcount--; transactionsDebug() << "-- globalcount ==" << KDbTransactionData_globalcount; #endif delete d; } void KDbTransactionData::ref() { d->refcount++; } void KDbTransactionData::deref() { d->refcount--; } int KDbTransactionData::refcount() const { return d->refcount; } bool KDbTransactionData::isActive() const { return d->active; } void KDbTransactionData::setActive(bool set) { d->active = set; } KDbConnection *KDbTransactionData::connection() { return d->connection; } +const KDbConnection *KDbTransactionData::connection() const +{ + return d->connection; +} + //--------------------------------------------------- KDbTransaction::KDbTransaction() : m_data(nullptr) { } KDbTransaction::KDbTransaction(const KDbTransaction& trans) : m_data(trans.m_data) { if (m_data) { m_data->ref(); #ifdef KDB_TRANSACTIONS_DEBUG KDbTransaction_globalcount++; #endif } } KDbTransaction::~KDbTransaction() { if (m_data) { m_data->deref(); #ifdef KDB_TRANSACTIONS_DEBUG KDbTransaction_globalcount--; #endif transactionsDebug() << "m_data->refcount==" << m_data->refcount(); if (m_data->refcount() == 0) delete m_data; } else { transactionsDebug() << "null"; } #ifdef KDB_TRANSACTIONS_DEBUG transactionsDebug() << "-- globalcount == " << KDbTransaction_globalcount; #endif } KDbTransaction& KDbTransaction::operator=(const KDbTransaction & trans) { if (this != &trans) { if (m_data) { m_data->deref(); #ifdef KDB_TRANSACTIONS_DEBUG KDbTransaction_globalcount--; #endif transactionsDebug() << "m_data->refcount==" << m_data->refcount(); if (m_data->refcount() == 0) delete m_data; } m_data = trans.m_data; if (m_data) { m_data->ref(); #ifdef KDB_TRANSACTIONS_DEBUG KDbTransaction_globalcount++; #endif } } return *this; } bool KDbTransaction::operator==(const KDbTransaction& other) const { return m_data == other.m_data; } -KDbConnection* KDbTransaction::connection() const +KDbConnection* KDbTransaction::connection() { return m_data ? m_data->connection() : nullptr; } +const KDbConnection* KDbTransaction::connection() const +{ + return const_cast(this)->connection(); +} + bool KDbTransaction::isActive() const { return m_data && m_data->isActive(); } bool KDbTransaction::isNull() const { return m_data == nullptr; } //--------------------------------------------------- class Q_DECL_HIDDEN KDbTransactionGuard::Private { public: Private() {} KDbTransaction transaction; bool doNothing = false; }; KDbTransactionGuard::KDbTransactionGuard(KDbConnection *connection) : KDbTransactionGuard() { if (connection) { d->transaction = connection->beginTransaction(); } } KDbTransactionGuard::KDbTransactionGuard(const KDbTransaction &transaction) : KDbTransactionGuard() { d->transaction = transaction; } KDbTransactionGuard::KDbTransactionGuard() : d(new Private) { } KDbTransactionGuard::~KDbTransactionGuard() { if (!d->doNothing && d->transaction.isActive()) { const bool result = rollback(); #ifdef KDB_TRANSACTIONS_DEBUG transactionsDebug() << "~KDbTransactionGuard is rolling back transaction:" << result; #else Q_UNUSED(result) #endif } delete d; } void KDbTransactionGuard::setTransaction(const KDbTransaction& transaction) { d->transaction = transaction; } bool KDbTransactionGuard::commit(KDbTransaction::CommitOptions options) { if (d->transaction.connection()) { return d->transaction.connection()->commitTransaction(d->transaction, options); } return false; } bool KDbTransactionGuard::rollback(KDbTransaction::CommitOptions options) { if (d->transaction.connection()) { return d->transaction.connection()->rollbackTransaction(d->transaction, options); } return false; } void KDbTransactionGuard::doNothing() { d->doNothing = true; } const KDbTransaction KDbTransactionGuard::transaction() const { return d->transaction; } diff --git a/src/KDbTransaction.h b/src/KDbTransaction.h index ed9959fb..26a199e9 100644 --- a/src/KDbTransaction.h +++ b/src/KDbTransaction.h @@ -1,121 +1,125 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_TRANSACTION_H #define KDB_TRANSACTION_H #include "config-kdb.h" #include "kdb_export.h" #include class KDbConnection; class KDbTransactionData; /** * @brief This class encapsulates a single database transaction * * The KDbTransaction handle abstracts a database transaction for given database connection. * Transaction objects are value-based, implicitly shared. * * Lifetime of the transaction object is closely related to a KDbConnection object. * Deleting the either instance does not commit or rollback the actual transaction. * Use KDbTransactionGuard for automatic commits or rolls back. * * @see KDbConnection::beginTransaction() */ class KDB_EXPORT KDbTransaction { public: /** * @brief Constructs a null transaction. * * @note It can be initialized only by KDbConnection. */ KDbTransaction(); /** * @brief Copy constructor */ KDbTransaction(const KDbTransaction& trans); ~KDbTransaction(); //! Options for commiting and rolling back transactions //! @see KDbConnection::beginTransaction() KDbConnection::rollbackTransaction() //! @see KDbTransactionGuard::commit() KDbTransactionGuard::rollback() enum class CommitOption { None = 0, IgnoreInactive = 1 //!< Do not return error for inactive or null transactions when //!< requesting commit or rollback }; Q_DECLARE_FLAGS(CommitOptions, CommitOption) KDbTransaction& operator=(const KDbTransaction& trans); /** * @brief Returns @c true if this transaction is equal to @a other; otherwise returns @c false * * Two transactions are equal if they encapsulate the same physical transaction, * i.e. copy constructor or assignment operator was used. * Two null transaction objects are equal. */ bool operator==(const KDbTransaction& other) const; //! @return @c true if this transaction is not equal to @a other; otherwise returns @c false. //! @since 3.1 inline bool operator!=(const KDbTransaction &other) const { return !operator==(other); } /** * @brief Returns database connection for which the transaction belongs. * * @c nullptr is returned for null transactions. */ - KDbConnection* connection() const; + KDbConnection* connection(); + + //! @overload + //! @since 3.1 + const KDbConnection* connection() const; /** * @brief Returns @c true if transaction is active (i.e. started) * * @return @c false also if transaction is uninitialised (null) or not started. * @see KDbConnection::beginTransaction() * @since 3.1 */ bool isActive() const; /** * @brief Returns @c true if this transaction is null. * * Null implies !isActive(). */ bool isNull() const; #ifdef KDB_TRANSACTIONS_DEBUG //! Helper for debugging, returns value of global transaction data reference counter static int globalCount(); #endif protected: KDbTransactionData *m_data; friend class KDbConnection; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KDbTransaction::CommitOptions) #endif diff --git a/src/KDbTransactionData.h b/src/KDbTransactionData.h index 1f3b6688..a82be0a0 100644 --- a/src/KDbTransactionData.h +++ b/src/KDbTransactionData.h @@ -1,71 +1,75 @@ /* This file is part of the KDE project Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_TRANSACTIONDATA_H #define KDB_TRANSACTIONDATA_H #include "config-kdb.h" #include "kdb_export.h" #include class KDbConnection; /** * @brief Internal prototype for storing transaction handle for KDbTransaction object * * Only for driver developers. Teimplement this class for database driver that supports transactions. */ class KDB_EXPORT KDbTransactionData { public: explicit KDbTransactionData(KDbConnection *connection); ~KDbTransactionData(); //! Increments the value of reference counter for this data. void ref(); //! Decrements the value of reference counter for this data. void deref(); //! @return value of reference counter for this data. int refcount() const; //! @return "active" flag of this data bool isActive() const; //! Sets "active" flag of this data void setActive(bool set); //! @return connection for this data KDbConnection *connection(); + //! @overload + //! @since 3.1 + const KDbConnection *connection() const; + #ifdef KDB_TRANSACTIONS_DEBUG //! Helper for debugging, returns value of global transaction data reference counter static int globalCount(); #endif private: Q_DISABLE_COPY(KDbTransactionData) class Private; Private * const d; }; #endif diff --git a/src/parser/KDbParser.cpp b/src/parser/KDbParser.cpp index 7856def6..e9f9b50e 100644 --- a/src/parser/KDbParser.cpp +++ b/src/parser/KDbParser.cpp @@ -1,216 +1,231 @@ /* This file is part of the KDE project Copyright (C) 2003 Lucijan Busch Copyright (C) 2004-2017 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbParser.h" #include "KDbParser_p.h" #include "generated/sqlparser.h" #include "KDbConnection.h" #include "KDbTableSchema.h" #include -bool parseData(KDbParser *p, const KDbEscapedString &sql); +bool parseData(); //! Cache class ParserStatic { public: ParserStatic() : statementTypeStrings({ QLatin1String("None"), QLatin1String("Select"), QLatin1String("CreateTable"), QLatin1String("AlterTable"), QLatin1String("Insert"), QLatin1String("Update"), QLatin1String("Delete")}) { } const std::vector statementTypeStrings; private: Q_DISABLE_COPY(ParserStatic) }; Q_GLOBAL_STATIC(ParserStatic, KDb_parserStatic) KDbParser::KDbParser(KDbConnection *connection) : d(new KDbParserPrivate) { d->connection = connection; } KDbParser::~KDbParser() { delete d; } KDbParser::StatementType KDbParser::statementType() const { return d->statementType; } QString KDbParser::statementTypeString() const { Q_ASSERT(size_t(d->statementType) < sizeof(KDb_parserStatic->statementTypeStrings)); return KDb_parserStatic->statementTypeStrings[d->statementType]; } KDbTableSchema *KDbParser::table() { KDbTableSchema *t = d->table; d->table = nullptr; return t; } +const KDbTableSchema *KDbParser::table() const +{ + return const_cast(this)->table(); +} + KDbQuerySchema *KDbParser::query() { KDbQuerySchema *s = d->query; d->query = nullptr; return s; } -KDbConnection *KDbParser::connection() const +KDbConnection *KDbParser::connection() +{ + return d->connection; +} + +const KDbConnection *KDbParser::connection() const { return d->connection; } KDbParserError KDbParser::error() const { return d->error; } KDbEscapedString KDbParser::statement() const { return d->sql; } void KDbParser::init() { if (d->initialized) return; // nothing to do d->initialized = true; } bool KDbParser::parse(const KDbEscapedString &sql, KDbQuerySchema *query) { init(); reset(); d->sql = sql; d->query = query; KDbParser *oldParser = globalParser; KDbField *oldField = globalField; - bool res = parseData(this, sql); + globalParser = this; + globalField = nullptr; + bool res = parseData(); globalParser = oldParser; globalField = oldField; + if (query) { // if existing query was supplied to parse() nullptr should be returned by query() + d->query = nullptr; + } return res; } void KDbParser::reset() { d->reset(); } //------------------------------------- class Q_DECL_HIDDEN KDbParserError::Private { public: Private() {} Private(const Private &other) { copy(other); } #define KDbParserErrorPrivateArgs(o) std::tie(o.type, o.message, o.token, o.position) void copy(const Private &other) { KDbParserErrorPrivateArgs((*this)) = KDbParserErrorPrivateArgs(other); } bool operator==(const Private &other) const { return KDbParserErrorPrivateArgs((*this)) == KDbParserErrorPrivateArgs(other); } QString type; QString message; QByteArray token; int position = -1; }; KDbParserError::KDbParserError() : d(new Private) { } KDbParserError::KDbParserError(const QString &type, const QString &message, const QByteArray &token, int position) : d(new Private) { d->type = type; d->message = message; d->token = token; d->position = position; } KDbParserError::KDbParserError(const KDbParserError &other) : d(new Private(*other.d)) { *d = *other.d; } KDbParserError::~KDbParserError() { delete d; } KDbParserError& KDbParserError::operator=(const KDbParserError &other) { if (this != &other) { d->copy(*other.d); } return *this; } bool KDbParserError::operator==(const KDbParserError &other) const { return *d == *other.d; } QString KDbParserError::type() const { return d->type; } QString KDbParserError::message() const { return d->message; } int KDbParserError::position() const { return d->position; } QDebug operator<<(QDebug dbg, const KDbParserError& error) { if (error.type().isEmpty() && error.message().isEmpty()) { return dbg.space() << "KDb:KDbParserError: None"; } return dbg.space() << "KDb:KDbParserError: type=" << error.type() << "message=" << error.message() << "pos=" << error.position() << ")"; } diff --git a/src/parser/KDbParser.h b/src/parser/KDbParser.h index ee240b71..dba9063e 100644 --- a/src/parser/KDbParser.h +++ b/src/parser/KDbParser.h @@ -1,200 +1,209 @@ /* This file is part of the KDE project Copyright (C) 2003 Lucijan Busch Copyright (C) 2004-2017 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef KDB_PARSER_H #define KDB_PARSER_H #include "kdb_export.h" #include #include class KDbConnection; class KDbQuerySchema; class KDbTableSchema; class KDbEscapedString; /** * Provides detailed error description about KDbParser. * * @todo Make it explicitly shared using SDC * @todo change type to enum */ class KDB_EXPORT KDbParserError { public: /** * Empty constructor. */ KDbParserError(); /** * Constructor. * * @param type The error type. * @param message A description of the error. * @param token Token where the Error happend. * @param position The position where the error happened. */ KDbParserError(const QString &type, const QString &message, const QByteArray &token, int position); /** * Copy constructor. */ KDbParserError(const KDbParserError &other); ~KDbParserError(); KDbParserError& operator=(const KDbParserError &other); bool operator==(const KDbParserError &other) const; inline bool operator!=(const KDbParserError &other) const { return !operator==(other); } /** * @return the error type. */ QString type() const; /** * @return translated error message. */ QString message() const; /** * @return (character) position where the error happened. */ int position() const; private: class Private; Private * const d; }; class KDbParserPrivate; //!< @internal /** * A parser tool for SQL statements. * * The KDbParser class offers functionality of a SQL parser for database-backend-independent * KDbSQL dialect. Schema objects such as KDbQuerySchema that are created after successful parsing * can be then used for running the queries on actual data or used for further modification. * * @todo Add examples * @todo Support more types than the SELECT */ class KDB_EXPORT KDbParser { Q_DECLARE_TR_FUNCTIONS(KDbParser) public: /** * The type of the statement. */ enum StatementType { NoType, //!< No statement type specified or detected Select, //!< Query-statement CreateTable, //!< Create a new table AlterTable, //!< Alter schema of an existing table Insert, //!< Insert new records Update, //!< Update existing records Delete //!< Delete existing records }; /** * Constructs an new parser object. * @a connection is used to obtain context, for example wildcards "T.*" resolution * is possible only if information about table T is available. */ explicit KDbParser(KDbConnection *connection); ~KDbParser(); /** * @brief Clears the parser's status and runs the parsing for a raw SQL statement * * If parsing of @a sql results in a proper query and @a query is present, it will be set to * representation of the parsed query. * @since 3.1 */ bool parse(const KDbEscapedString &sql, KDbQuerySchema *query = nullptr); /** * Reset the parser's status (table, query, error, statement, statement type). */ void reset(); /** * @return the resulting statement type * NoType is returned if parsing failed or it has not been yet performed or reset() was called. */ StatementType statementType() const; /** * @return the resulting statement type as string. It is not translated. */ QString statementTypeString() const; /** * @return a pointer to a query schema if 'CREATE TABLE ...' statement was parsed * or @c nullptr for any other statements or on error. * @note A proper table schema is returned only once for each successful parse() call, * and the object is owned by the caller. In all other cases @c nullptr is returned. * * @todo Implement this */ KDbTableSchema *table(); + //! @overload + //! @since 3.1 + const KDbTableSchema *table() const; + /** - * @return a pointer to a query schema if 'SELECT ...' statement was parsed + * @return a pointer to a new query schema created by parsing 'SELECT ...' statement * or @c nullptr for any other statements or on error. + * If existing query was supplied to parse() @c nullptr is returned. * @note A proper query schema is returned only once for each successful parse() call, * and the object is owned by the caller. In all other cases nullptr is returned. */ KDbQuerySchema *query(); /** * @return a pointer to the used database connection or @c nullptr if it was not set. */ - KDbConnection *connection() const; + KDbConnection *connection(); + + //! @overload + //! @since 3.1 + const KDbConnection *connection() const; /** * @return detailed information about last error. * If no error occurred KDbParserError::type() is empty. */ KDbParserError error() const; /** * @return the statement passed on the most recent call of parse(). */ KDbEscapedString statement() const; private: void init(); friend class KDbParserPrivate; KDbParserPrivate * const d; //!< @internal d-pointer class. Q_DISABLE_COPY(KDbParser) }; //! Sends information about parser error @a error to debug output @a dbg. KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbParserError& error); #endif diff --git a/src/parser/KDbParser_p.cpp b/src/parser/KDbParser_p.cpp index 806b7f30..02c0105f 100644 --- a/src/parser/KDbParser_p.cpp +++ b/src/parser/KDbParser_p.cpp @@ -1,533 +1,534 @@ /* This file is part of the KDE project Copyright (C) 2004-2017 Jarosław Staniek This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "KDbParser_p.h" #include "KDb.h" #include "KDbConnection.h" #include "KDbTableSchema.h" #include "KDbQueryAsterisk.h" #include "KDbQuerySchema.h" #include "KDbQuerySchema_p.h" #include "KDbOrderByColumn.h" #include "kdb_debug.h" #include "generated/sqlparser.h" #include KDbParser *globalParser = nullptr; KDbField *globalField = nullptr; QList fieldList; int globalCurrentPos = 0; QByteArray globalToken; extern int yylex_destroy(void); //------------------------------------- KDbParserPrivate::KDbParserPrivate() : table(nullptr), query(nullptr), connection(nullptr), initialized(false) { reset(); } KDbParserPrivate::~KDbParserPrivate() { reset(); } void KDbParserPrivate::reset() { statementType = KDbParser::NoType; sql.clear(); error = KDbParserError(); delete table; table = nullptr; delete query; query = nullptr; } void KDbParserPrivate::setStatementType(KDbParser::StatementType type) { statementType = type; } void KDbParserPrivate::setError(const KDbParserError &err) { error = err; } void KDbParserPrivate::setTableSchema(KDbTableSchema *table) { delete this->table; this->table = table; } void KDbParserPrivate::setQuerySchema(KDbQuerySchema *query) { - delete this->query; + if (this->query != query) { + delete this->query; + } this->query = query; } KDbQuerySchema* KDbParserPrivate::createQuery() { - return query ? query : KDbQuerySchema::Private::createQuery(connection); + return query ? query : new KDbQuerySchema; } //------------------------------------- KDbParseInfo::KDbParseInfo(KDbQuerySchema *query) : d(new Private) { d->querySchema = query; } KDbParseInfo::~KDbParseInfo() { delete d; } QList KDbParseInfo::tablesAndAliasesForName(const QString &tableOrAliasName) const { QList result; const QList *list = d->repeatedTablesAndAliases.value(tableOrAliasName); if (list) { result = *list; } if (result.isEmpty()) { int position = d->querySchema->tablePositionForAlias(tableOrAliasName); if (position == -1) { position = d->querySchema->tablePosition(tableOrAliasName); if (position != -1) { result.append(position); } } else { result.append(position); } } return result; } KDbQuerySchema* KDbParseInfo::querySchema() const { return d->querySchema; } QString KDbParseInfo::errorMessage() const { return d->errorMessage; } QString KDbParseInfo::errorDescription() const { return d->errorDescription; } void KDbParseInfo::setErrorMessage(const QString &message) { d->errorMessage = message; } void KDbParseInfo::setErrorDescription(const QString &description) { d->errorDescription = description; } //------------------------------------- KDbParseInfoInternal::KDbParseInfoInternal(KDbQuerySchema *query) : KDbParseInfo(query) { } KDbParseInfoInternal::~KDbParseInfoInternal() { } void KDbParseInfoInternal::appendPositionForTableOrAliasName(const QString &tableOrAliasName, int pos) { QList *list = d->repeatedTablesAndAliases.value(tableOrAliasName); if (!list) { list = new QList(); d->repeatedTablesAndAliases.insert(tableOrAliasName, list); } list->append(pos); } //------------------------------------- extern int yyparse(); extern void tokenize(const char *data); void yyerror(const char *str) { kdbDebug() << "error: " << str; kdbDebug() << "at character " << globalCurrentPos << " near tooken " << globalToken; KDbParserPrivate::get(globalParser)->setStatementType(KDbParser::NoType); const bool otherError = (qstrnicmp(str, "other error", 11) == 0); const bool syntaxError = qstrnicmp(str, "syntax error", 12) == 0; if ((globalParser->error().type().isEmpty() && (str == nullptr || strlen(str) == 0 || syntaxError)) || otherError) { kdbDebug() << globalParser->statement(); QString ptrline(globalCurrentPos, QLatin1Char(' ')); ptrline += QLatin1String("^"); kdbDebug() << ptrline; #if 0 //lexer may add error messages QString lexerErr = globalParser->error().message(); QString errtypestr = QLatin1String(str); if (lexerErr.isEmpty()) { if (errtypestr.startsWith(QString::fromLatin1("parse error, expecting `IDENTIFIER'"))) { lexerErr = KDbParser::tr("identifier was expected"); } } #endif //! @todo exact invalid expression can be selected in the editor, based on KDbParseInfo data if (!otherError) { const bool isKDbSqlKeyword = KDb::isKDbSqlKeyword(globalToken); if (isKDbSqlKeyword || syntaxError) { if (isKDbSqlKeyword) { KDbParserPrivate::get(globalParser)->setError(KDbParserError(KDbParser::tr("Syntax Error"), KDbParser::tr("\"%1\" is a reserved keyword.").arg(QLatin1String(globalToken)), globalToken, globalCurrentPos)); } else { KDbParserPrivate::get(globalParser)->setError(KDbParserError(KDbParser::tr("Syntax Error"), KDbParser::tr("Syntax error."), globalToken, globalCurrentPos)); } } else { KDbParserPrivate::get(globalParser)->setError(KDbParserError(KDbParser::tr("Error"), KDbParser::tr("Error near \"%1\".").arg(QLatin1String(globalToken)), globalToken, globalCurrentPos)); } } } } void setError(const QString& errName, const QString& errDesc) { KDbParserPrivate::get(globalParser)->setError(KDbParserError(errName, errDesc, globalToken, globalCurrentPos)); yyerror(qPrintable(errName)); } void setError(const QString& errDesc) { setError(KDbParser::tr("Other error"), errDesc); } /* this is better than assert() */ #define IMPL_ERROR(errmsg) setError(KDbParser::tr("Implementation error"), QLatin1String(errmsg)) //! @internal Parses @a data for parser @a p //! @todo Make it REENTRANT -bool parseData(KDbParser *p, const KDbEscapedString &sql) +bool parseData() { - globalParser = p; - globalParser->reset(); - globalField = nullptr; fieldList.clear(); + const KDbEscapedString sql(globalParser->statement()); if (sql.isEmpty()) { KDbParserError err(KDbParser::tr("Error"), KDbParser::tr("No query statement specified."), globalToken, globalCurrentPos); KDbParserPrivate::get(globalParser)->setError(err); yyerror(""); - globalParser = nullptr; return false; } const char *data = sql.constData(); tokenize(data); if (!globalParser->error().type().isEmpty()) { - globalParser = nullptr; return false; } bool ok = yyparse() == 0; if (ok && globalCurrentPos < sql.length()) { kdbDebug() << "Parse error: tokens left" << "globalCurrentPos:" << globalCurrentPos << "sql.length():" << sql.length() << "globalToken:" << QString::fromUtf8(globalToken); KDbParserError err(KDbParser::tr("Error"), KDbParser::tr("Unexpected character."), globalToken, globalCurrentPos); KDbParserPrivate::get(globalParser)->setError(err); yyerror(""); ok = false; } if (ok && globalParser->statementType() == KDbParser::Select) { kdbDebug() << "parseData(): ok"; // kdbDebug() << "parseData(): " << tableDict.count() << " loaded tables"; /* KDbTableSchema *ts; for(QDictIterator it(tableDict); KDbTableSchema *s = tableList.first(); s; s = tableList.next()) { kdbDebug() << " " << s->name(); }*/ } else { ok = false; } yylex_destroy(); - globalParser = nullptr; return ok; } /*! Adds @a columnExpr to @a parseInfo The column can be in a form table.field, tableAlias.field or field. @return true on success. On error message in globalParser object is updated. */ bool addColumn(KDbParseInfo *parseInfo, const KDbExpression &columnExpr) { if (!KDbExpression(columnExpr).validate(parseInfo)) { // (KDbExpression(columnExpr) used to avoid constness problem) setError(parseInfo->errorMessage(), parseInfo->errorDescription()); return false; } const KDbVariableExpression v_e(columnExpr.toVariable()); if (columnExpr.expressionClass() == KDb::VariableExpression && !v_e.isNull()) { //it's a variable: if (v_e.name() == QLatin1String("*")) {//all tables asterisk if (parseInfo->querySchema()->tables()->isEmpty()) { setError(KDbParser::tr("\"*\" could not be used if no tables are specified.")); return false; } KDbQueryAsterisk *a = new KDbQueryAsterisk(parseInfo->querySchema()); if (!parseInfo->querySchema()->addAsterisk(a)) { delete a; setError(KDbParser::tr("\"*\" could not be added.")); return false; } } else if (v_e.tableForQueryAsterisk()) {//one-table asterisk KDbQueryAsterisk *a = new KDbQueryAsterisk(parseInfo->querySchema(), *v_e.tableForQueryAsterisk()); if (!parseInfo->querySchema()->addAsterisk(a)) { delete a; setError(KDbParser::tr("\".*\" could not be added.")); return false; } } else if (v_e.field()) {//"table.field" or "field" (bound to a table or not) if (!parseInfo->querySchema()->addField(v_e.field(), v_e.tablePositionForField())) { setError(KDbParser::tr("Could not add binding to a field.")); return false; } } else { IMPL_ERROR("addColumn(): unknown case!"); return false; } return true; } //it's complex expression return parseInfo->querySchema()->addExpression(columnExpr); } KDbQuerySchema* buildSelectQuery( KDbQuerySchema* querySchema, KDbNArgExpression* _colViews, KDbNArgExpression* _tablesList, SelectOptionsInternal* options) { KDbParseInfoInternal parseInfo(querySchema); // remove from heap (using heap was requered because parser uses union) KDbNArgExpression colViews; if (_colViews) { colViews = *_colViews; delete _colViews; } KDbNArgExpression tablesList; if (_tablesList) { tablesList = *_tablesList; delete _tablesList; } QScopedPointer optionsPtr(options); QScopedPointer querySchemaPtr(querySchema); // destroy query on any error //-------tables list int columnNum = 0; /*! @todo use this later if there are columns that use database fields, e.g. "SELECT 1 from table1 t, table2 t") is ok however. */ //used to collect information about first repeated table name or alias: if (!tablesList.isEmpty()) { for (int i = 0; i < tablesList.argCount(); i++, columnNum++) { KDbExpression e(tablesList.arg(i)); KDbVariableExpression t_e; QString aliasString; if (e.expressionClass() == KDb::SpecialBinaryExpression) { KDbBinaryExpression t_with_alias = e.toBinary(); Q_ASSERT(e.isBinary()); Q_ASSERT(t_with_alias.left().expressionClass() == KDb::VariableExpression); Q_ASSERT(t_with_alias.right().expressionClass() == KDb::VariableExpression && (t_with_alias.token() == KDbToken::AS || t_with_alias.token() == KDbToken::AS_EMPTY)); t_e = t_with_alias.left().toVariable(); aliasString = t_with_alias.right().toVariable().name(); } else { t_e = e.toVariable(); } Q_ASSERT(t_e.isVariable()); QString tname = t_e.name(); KDbTableSchema *s = globalParser->connection()->tableSchema(tname); if (!s) { setError(KDbParser::tr("Table \"%1\" does not exist.").arg(tname)); return nullptr; } QString tableOrAliasName = KDb::iifNotEmpty(aliasString, tname); if (!aliasString.isEmpty()) { // kdbDebug() << "- add alias for table: " << aliasString; } // 1. collect information about first repeated table name or alias // (potential ambiguity) parseInfo.appendPositionForTableOrAliasName(tableOrAliasName, i); // kdbDebug() << "addTable: " << tname; querySchema->addTable(s, aliasString); } } /* set parent table if there's only one */ if (querySchema->tables()->count() == 1) querySchema->setMasterTable(querySchema->tables()->first()); //-------add fields if (!colViews.isEmpty()) { columnNum = 0; bool containsAsteriskColumn = false; // used to check duplicated asterisks (disallowed) for (int i = 0; i < colViews.argCount(); i++, columnNum++) { const KDbExpression e(colViews.arg(i)); KDbExpression columnExpr(e); KDbVariableExpression aliasVariable; if (e.expressionClass() == KDb::SpecialBinaryExpression && e.isBinary() && (e.token() == KDbToken::AS || e.token() == KDbToken::AS_EMPTY)) { //KDb::SpecialBinaryExpression: with alias columnExpr = e.toBinary().left(); aliasVariable = e.toBinary().right().toVariable(); if (aliasVariable.isNull()) { setError(KDbParser::tr("Invalid alias definition for column \"%1\".") .arg(columnExpr.toString(nullptr).toString())); //ok? break; } } const KDb::ExpressionClass c = columnExpr.expressionClass(); const bool isExpressionField = c == KDb::ConstExpression || c == KDb::UnaryExpression || c == KDb::ArithmeticExpression || c == KDb::LogicalExpression || c == KDb::RelationalExpression || c == KDb::FunctionExpression || c == KDb::AggregationExpression || c == KDb::QueryParameterExpression; if (c == KDb::VariableExpression) { if (columnExpr.toVariable().name() == QLatin1String("*")) { if (containsAsteriskColumn) { setError(KDbParser::tr("More than one asterisk \"*\" is not allowed.")); return nullptr; } else { containsAsteriskColumn = true; } } // addColumn() will handle this } else if (isExpressionField) { //expression object will be reused, take, will be owned, do not destroy // kdbDebug() << colViews->list.count() << " " << it.current()->debugString(); //! @todo IMPORTANT: it.remove(); } else if (aliasVariable.isNull()) { setError(KDbParser::tr("Invalid \"%1\" column definition.") .arg(e.toString(nullptr).toString())); //ok? break; } else { //take first (left) argument of the special binary expr, will be owned, do not destroy e.toBinary().setLeft(KDbExpression()); } if (!addColumn(&parseInfo, columnExpr)) { break; } if (!aliasVariable.isNull()) { // kdbDebug() << "ALIAS \"" << aliasVariable->name << "\" set for column " // << columnNum; querySchema->setColumnAlias(columnNum, aliasVariable.name()); } } // for if (!globalParser->error().message().isEmpty()) { // we could not return earlier (inside the loop) // because we want run CLEANUP what could crash QMutableListIterator. return nullptr; } } //----- SELECT options if (options) { //----- WHERE expr. if (!options->whereExpr.isNull()) { if (!options->whereExpr.validate(&parseInfo)) { setError(parseInfo.errorMessage(), parseInfo.errorDescription()); return nullptr; } - KDbQuerySchema::Private::setWhereExpressionInternal(querySchema, options->whereExpr); + KDbQuerySchemaPrivate::setWhereExpressionInternal(querySchema, options->whereExpr); } //----- ORDER BY if (options->orderByColumns) { KDbOrderByColumnList *orderByColumnList = querySchema->orderByColumnList(); int count = options->orderByColumns->count(); QList::ConstIterator it(options->orderByColumns->constEnd()); --it; for (;count > 0; --it, --count) /*opposite direction due to parser specifics*/ { - //first, try to find a column name or alias (outside of asterisks) - KDbQueryColumnInfo *columnInfo = querySchema->columnInfo((*it).aliasOrName, false/*outside of asterisks*/); + // first, try to find a column name or alias (outside of asterisks) + KDbQueryColumnInfo *columnInfo = querySchema->columnInfo( + globalParser->connection(), (*it).aliasOrName, + KDbQuerySchema::ExpandMode::Unexpanded /*outside of asterisks*/); if (columnInfo) { orderByColumnList->appendColumn(columnInfo, (*it).order); } else { //failed, try to find a field name within all the tables if ((*it).columnNumber != -1) { - if (!orderByColumnList->appendColumn(querySchema, - (*it).order, (*it).columnNumber - 1)) { + if (!orderByColumnList->appendColumn(globalParser->connection(), + querySchema, (*it).order, + (*it).columnNumber - 1)) + { setError(KDbParser::tr("Could not define sorting. Column at " "position %1 does not exist.") .arg((*it).columnNumber)); return nullptr; } } else { KDbField * f = querySchema->findTableField((*it).aliasOrName); if (!f) { setError(KDbParser::tr("Could not define sorting. " "Column name or alias \"%1\" does not exist.") .arg((*it).aliasOrName)); return nullptr; } orderByColumnList->appendField(f, (*it).order); } } } } } // kdbDebug() << "Select ColViews=" << (colViews ? colViews->debugString() : QString()) // << " Tables=" << (tablesList ? tablesList->debugString() : QString()s); return querySchemaPtr.take(); } diff --git a/src/views/KDbTableViewColumn.cpp b/src/views/KDbTableViewColumn.cpp index 98086b26..e998b52c 100644 --- a/src/views/KDbTableViewColumn.cpp +++ b/src/views/KDbTableViewColumn.cpp @@ -1,423 +1,422 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Daniel Molkentin Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. Original Author: Till Busch Original Project: buX (www.bux.at) */ #include "KDbTableViewColumn.h" #include "KDbConnection.h" #include "KDbConnectionOptions.h" #include "KDbCursor.h" #include "KDb.h" #include "KDbQuerySchema.h" #include "KDbRecordEditBuffer.h" #include "KDbTableViewData.h" #include "KDbValidator.h" #include class Q_DECL_HIDDEN KDbTableViewColumn::Private { public: Private() : data(nullptr) , validator(nullptr) , relatedData(nullptr) , field(nullptr) , columnInfo(nullptr) , visibleLookupColumnInfo(nullptr) , width(0) , readOnly(false) , visible(true) , relatedDataEditable(false) , headerTextVisible(true) { } //! Data that this column is assigned to. Set by KDbTableViewColumn::setData() KDbTableViewData* data; QString captionAliasOrName; QIcon icon; KDbValidator* validator; KDbTableViewData* relatedData; int relatedDataPKeyID; KDbField* field; //! @see columnInfo() KDbQueryColumnInfo* columnInfo; //! @see visibleLookupColumnInfo() KDbQueryColumnInfo* visibleLookupColumnInfo; int width; bool isDBAware; //!< true if data is stored in DB, not only in memeory bool readOnly; bool fieldOwned; bool visible; bool relatedDataEditable; bool headerTextVisible; }; //------------------------ KDbTableViewColumn::KDbTableViewColumn(KDbField *f, FieldIsOwned isOwned) : d(new Private) { d->field = f; d->isDBAware = false; d->fieldOwned = isOwned == FieldIsOwned::Yes; d->captionAliasOrName = d->field->captionOrName(); } KDbTableViewColumn::KDbTableViewColumn(const QString &name, KDbField::Type ctype, KDbField::Constraints cconst, KDbField::Options options, int maxLength, int precision, QVariant defaultValue, const QString &caption, const QString &description) : d(new Private) { d->field = new KDbField( name, ctype, cconst, options, maxLength, precision, defaultValue, caption, description); d->isDBAware = false; d->fieldOwned = true; d->captionAliasOrName = d->field->captionOrName(); } KDbTableViewColumn::KDbTableViewColumn(const QString &name, KDbField::Type ctype, const QString &caption, const QString &description) : d(new Private) { d->field = new KDbField( name, ctype, KDbField::NoConstraints, KDbField::NoOptions, 0, 0, QVariant(), caption, description); d->isDBAware = false; d->fieldOwned = true; d->captionAliasOrName = d->field->captionOrName(); } // db-aware KDbTableViewColumn::KDbTableViewColumn( const KDbQuerySchema &query, KDbQueryColumnInfo *aColumnInfo, KDbQueryColumnInfo *aVisibleLookupColumnInfo) : d(new Private) { Q_ASSERT(aColumnInfo); d->field = aColumnInfo->field(); d->columnInfo = aColumnInfo; d->visibleLookupColumnInfo = aVisibleLookupColumnInfo; d->isDBAware = true; d->fieldOwned = false; //setup column's caption: if (!d->columnInfo->field()->caption().isEmpty()) { d->captionAliasOrName = d->columnInfo->field()->caption(); } else { //reuse alias if available: d->captionAliasOrName = d->columnInfo->alias(); //last hance: use field name if (d->captionAliasOrName.isEmpty()) d->captionAliasOrName = d->columnInfo->field()->name(); //! @todo compute other auto-name? } //setup column's readonly flag: true, if // - it's not from parent table's field, or // - if the query itself is coming from read-only connection, or // - if the query itself is stored (i.e. has connection) and lookup column is defined const bool columnFromMasterTable = query.masterTable() == d->columnInfo->field()->table(); - d->readOnly = !columnFromMasterTable - || (query.connection() && query.connection()->options()->isReadOnly()); + d->readOnly = !columnFromMasterTable; //! @todo remove this when queries become editable ^^^^^^^^^^^^^^ // kdbDebug() << "KDbTableViewColumn: query.masterTable()==" // << (query.masterTable() ? query.masterTable()->name() : "notable") << ", columnInfo->field->table()==" // << (columnInfo->field->table() ? columnInfo->field->table()->name() : "notable"); } KDbTableViewColumn::KDbTableViewColumn(bool) : d(new Private) { d->isDBAware = false; } KDbTableViewColumn::~KDbTableViewColumn() { if (d->fieldOwned) delete d->field; setValidator(nullptr); delete d->relatedData; delete d; } void KDbTableViewColumn::setValidator(KDbValidator *v) { if (d->validator) {//remove old one if (!d->validator->parent()) //destroy if has no parent delete d->validator; } d->validator = v; } void KDbTableViewColumn::setData(KDbTableViewData *data) { d->data = data; } void KDbTableViewColumn::setRelatedData(KDbTableViewData *data) { if (d->isDBAware) return; if (d->relatedData) delete d->relatedData; d->relatedData = nullptr; if (!data) return; //find a primary key const QList *columns = data->columns(); int id = -1; foreach(KDbTableViewColumn* col, *columns) { id++; if (col->field()->isPrimaryKey()) { //found, remember d->relatedDataPKeyID = id; d->relatedData = data; return; } } } bool KDbTableViewColumn::isReadOnly() const { return d->readOnly || (d->data && d->data->isReadOnly()); } void KDbTableViewColumn::setReadOnly(bool ro) { d->readOnly = ro; } bool KDbTableViewColumn::isVisible() const { return d->columnInfo ? d->columnInfo->isVisible() : d->visible; } void KDbTableViewColumn::setVisible(bool v) { bool changed = d->visible != v; if (d->columnInfo && d->columnInfo->isVisible() != v) { d->columnInfo->setVisible(v); changed = true; } d->visible = v; if (changed && d->data) { d->data->columnVisibilityChanged(*this); } } void KDbTableViewColumn::setIcon(const QIcon& icon) { d->icon = icon; } QIcon KDbTableViewColumn::icon() const { return d->icon; } void KDbTableViewColumn::setHeaderTextVisible(bool visible) { d->headerTextVisible = visible; } bool KDbTableViewColumn::isHeaderTextVisible() const { return d->headerTextVisible; } QString KDbTableViewColumn::captionAliasOrName() const { return d->captionAliasOrName; } KDbValidator* KDbTableViewColumn::validator() const { return d->validator; } KDbTableViewData *KDbTableViewColumn::relatedData() { return d->relatedData; } const KDbTableViewData *KDbTableViewColumn::relatedData() const { return d->relatedData; } KDbField* KDbTableViewColumn::field() { return d->field; } const KDbField* KDbTableViewColumn::field() const { return d->field; } void KDbTableViewColumn::setRelatedDataEditable(bool set) { d->relatedDataEditable = set; } bool KDbTableViewColumn::isRelatedDataEditable() const { return d->relatedDataEditable; } KDbQueryColumnInfo* KDbTableViewColumn::columnInfo() { return d->columnInfo; } const KDbQueryColumnInfo* KDbTableViewColumn::columnInfo() const { return d->columnInfo; } KDbQueryColumnInfo* KDbTableViewColumn::visibleLookupColumnInfo() { return d->visibleLookupColumnInfo; } const KDbQueryColumnInfo* KDbTableViewColumn::visibleLookupColumnInfo() const { return d->visibleLookupColumnInfo; } bool KDbTableViewColumn::isDBAware() const { return d->isDBAware; } bool KDbTableViewColumn::acceptsFirstChar(const QChar &ch) const { // the field we're looking at can be related to "visible lookup column" // if lookup column is present KDbField *visibleField = d->visibleLookupColumnInfo ? d->visibleLookupColumnInfo->field() : d->field; const KDbField::Type type = visibleField->type(); // cache: evaluating type of expressions can be expensive if (KDbField::isNumericType(type)) { if (ch == QLatin1Char('.') || ch == QLatin1Char(',')) return KDbField::isFPNumericType(type); if (ch == QLatin1Char('-')) return !visibleField->isUnsigned(); if (ch == QLatin1Char('+') || (ch >= QLatin1Char('0') && ch <= QLatin1Char('9'))) return true; return false; } switch (type) { case KDbField::Boolean: return false; case KDbField::Date: case KDbField::DateTime: case KDbField::Time: return ch >= QLatin1Char('0') && ch <= QLatin1Char('9'); default:; } return true; } void KDbTableViewColumn::setWidth(int w) { d->width = w; } int KDbTableViewColumn::width() const { return d->width; } QDebug operator<<(QDebug dbg, const KDbTableViewColumn &column) { dbg.nospace() << "TableViewColumn("; dbg.space() << "columnInfo:"; if (column.columnInfo()) { dbg.space() << *column.columnInfo(); } else { dbg.space() << ""; } dbg.space() << "captionAliasOrName:" << column.captionAliasOrName(); dbg.space() << "visibleLookupColumnInfo:"; if (column.visibleLookupColumnInfo()) { dbg.space() << *column.visibleLookupColumnInfo(); } else { dbg.space() << ""; } dbg.space() << "data: KDbTableViewData("; const KDbTableViewData *data = column.d->data; if (data) { dbg.space() << "count:" << data->count() << ")"; } else { dbg.space() << ")"; } dbg.space() << "relatedData: KDbTableViewData("; const KDbTableViewData *relatedData = column.d->relatedData; if (relatedData) { dbg.space() << "count:" << relatedData->count() << ")"; } else { dbg.space() << ")"; } const KDbField *field = column.d->field; if (data) { dbg.space() << "field:" << *field; } else { dbg.space() << ""; } dbg.space() << "fieldOwned:" << column.d->fieldOwned; dbg.space() << "validator:"; if (column.validator()) { dbg.space() << ""; } else { dbg.space() << ""; } dbg.space() << "icon:" << column.icon().name(); dbg.space() << "fieldOwned:" << column.d->fieldOwned; dbg.space() << "width:" << column.width(); dbg.space() << "isDBAware:" << column.isDBAware(); dbg.space() << "readOnly:" << column.isReadOnly(); dbg.space() << "visible:" << column.isVisible(); dbg.space() << "relatedDataEditable:" << column.isRelatedDataEditable(); dbg.space() << "headerTextVisible:" << column.isHeaderTextVisible(); return dbg.space(); } diff --git a/src/views/KDbTableViewColumn.h b/src/views/KDbTableViewColumn.h index b3e687ba..4066316d 100644 --- a/src/views/KDbTableViewColumn.h +++ b/src/views/KDbTableViewColumn.h @@ -1,205 +1,205 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Daniel Molkentin Copyright (C) 2003-2017 Jarosław Staniek This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. Original Author: Till Busch Original Project: buX (www.bux.at) */ #ifndef KDB_TABLEVIEWCOLUMN_H #define KDB_TABLEVIEWCOLUMN_H #include "kdb_export.h" #include "KDbField.h" class KDbQueryColumnInfo; class KDbQuerySchema; class KDbTableViewColumn; class KDbTableViewData; class KDbValidator; //! Definition of a single column for table view. /*! @todo improve API */ class KDB_EXPORT KDbTableViewColumn { public: /*! Specifies if the associated KDbField object is owned by the column so it will be automatically destroyed when needed by this column. */ enum class FieldIsOwned { Yes, No }; /*! Not db-aware ctor. if @a isOwned is Yes, the field @a will be owned by this column so it will be automatically destroyed when needed by this column. */ explicit KDbTableViewColumn(KDbField *f, FieldIsOwned isOwned = FieldIsOwned::No); /*! Not db-aware, convenience ctor, like above. The field is created using specified parameters that are equal to these accepted by KDbField ctor. The column will be the owner of this automatically generated field. */ KDbTableViewColumn(const QString &name, KDbField::Type ctype, KDbField::Constraints cconst = KDbField::NoConstraints, KDbField::Options options = KDbField::NoOptions, int maxLength = 0, int precision = 0, QVariant defaultValue = QVariant(), const QString &caption = QString(), const QString &description = QString()); /*! Not db-aware, convenience ctor, simplified version of the above. */ KDbTableViewColumn(const QString &name, KDbField::Type ctype, const QString &caption, const QString &description = QString()); //! Db-aware version. KDbTableViewColumn(const KDbQuerySchema &query, KDbQueryColumnInfo *aColumnInfo, KDbQueryColumnInfo *aVisibleLookupColumnInfo = nullptr); virtual ~KDbTableViewColumn(); virtual bool acceptsFirstChar(const QChar &ch) const; /*! @return true if the column is read-only For db-aware column this can depend on whether the column is in parent table of this query. @see setReadOnly() */ bool isReadOnly() const; //! forces readOnly flag to be set to @a ro //! @todo synchronize this with table view: void setReadOnly(bool ro); //! Column visibility. By default column is visible. bool isVisible() const; //! Changes column visibility. //! KDbTableViewData is informed about this change. //! @todo react on changes of KDbQueryColumnInfo::visible too void setVisible(bool v); /*! Sets icon for displaying in the caption area (header). */ void setIcon(const QIcon &icon); /*! @return bame of icon displayed in the caption area (header). */ QIcon icon() const; /*! If @a visible is true, caption has to be displayed in the column's header, (or field's name if caption is empty. True by default. */ void setHeaderTextVisible(bool visible); /*! @return true if caption has to be displayed in the column's header, (or field's name if caption is empty. */ bool isHeaderTextVisible() const; /*! @return whatever is available: - field's caption - or field's alias (from query) - or finally - field's name */ QString captionAliasOrName() const; /*! Assigns validator @a v for this column. If the validator has no parent object, it will be owned by the column, so you don't need to care about destroying it. */ void setValidator(KDbValidator *v); //! @return validator assigned for this column of 0 if there is no validator assigned. KDbValidator* validator() const; /*! For not-db-aware data only: Sets related data @a data for this column, what defines simple one-field, one-to-many relationship between this column and the primary key in @a data. The relationship will be used to generate a popup editor instead of just regular editor. This assignment has no result if @a data has no primary key defined. @a data is owned, so is will be destroyed when needed. It is also destroyed when another data (or @c nullptr) is set for the same column. */ void setRelatedData(KDbTableViewData *data); /*! For not-db-aware data only: Related data @a data for this column, what defines simple one-field. @c nullptr by default. @see setRelatedData() */ KDbTableViewData *relatedData(); //! @overload const KDbTableViewData *relatedData() const; /*! @return field for this column. For db-aware information is taken from columnInfo(). */ KDbField* field(); //! @overload const KDbField* field() const; /*! Only usable if related data is set (ie. this is for combo boxes). Sets 'editable' flag for this column, what means a new value can be entered by hand. This is similar to QComboBox::setEditable(). */ void setRelatedDataEditable(bool set); /*! Only usable if related data is set (ie. this is for combo boxes). @return 'editable' flag for this column. False by default. @see setRelatedDataEditable(bool). */ bool isRelatedDataEditable() const; /*! A rich field information for db-aware data. For not-db-aware data it is always 0 (use field() instead). */ KDbQueryColumnInfo* columnInfo(); //! @overload const KDbQueryColumnInfo* columnInfo() const; /*! A rich field information for db-aware data. Specifies information for a column that should be visible instead of columnInfo. For example case see - @ref KDbQueryColumnInfo::Vector KDbQuerySchema::fieldsExpanded(KDbQuerySchema::FieldsExpandedOptions options = Default) + @ref KDbQueryColumnInfo::Vector KDbQuerySchema::fieldsExpanded(KDbQuerySchema::FieldsExpandedMode mode = Default) - For not-db-aware data it is always 0. */ + For not-db-aware data it is always @c nullptr. */ KDbQueryColumnInfo* visibleLookupColumnInfo(); //! @overload const KDbQueryColumnInfo* visibleLookupColumnInfo() const; //! @return true if data is stored in DB, not only in memeory. bool isDBAware() const; /*! Sets visible width for this column to @a w (usually in pixels or points). 0 means there is no hint for the width. */ void setWidth(int w); /*! @return width of this field (usually in pixels or points). 0 (the default) means there is no hint for the width. */ int width() const; protected: //! special ctor that does not allocate d member; explicit KDbTableViewColumn(bool); //! used by KDbTableViewData::addColumn() void setData(KDbTableViewData *data); private: class Private; Private * const d; friend class KDbTableViewData; friend KDB_EXPORT QDebug operator<<(QDebug, const KDbTableViewColumn&); Q_DISABLE_COPY(KDbTableViewColumn) }; //! Sends information about column @a column to debug output @a dbg. //! @since 3.1 KDB_EXPORT QDebug operator<<(QDebug dbg, const KDbTableViewColumn &column); #endif diff --git a/src/views/KDbTableViewData.cpp b/src/views/KDbTableViewData.cpp index a99d42f1..56f74852 100644 --- a/src/views/KDbTableViewData.cpp +++ b/src/views/KDbTableViewData.cpp @@ -1,954 +1,957 @@ /* This file is part of the KDE project Copyright (C) 2002 Lucijan Busch Copyright (C) 2003 Daniel Molkentin Copyright (C) 2003-2017 Jarosław Staniek Copyright (C) 2014 Michał Poteralski 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. Original Author: Till Busch Original Project: buX (www.bux.at) */ #include "KDbTableViewData.h" #include "KDbConnection.h" #include "KDbConnectionOptions.h" #include "KDbCursor.h" #include "KDbError.h" #include "KDb.h" #include "KDbOrderByColumn.h" #include "KDbQuerySchema.h" #include "KDbRecordEditBuffer.h" #include "KDbTableViewColumn.h" #include "kdb_debug.h" #include #include // #define TABLEVIEW_NO_PROCESS_EVENTS static unsigned short charTable[] = { #include "chartable.txt" }; //------------------------------- //! @internal Unicode-aware collator for comparing strings class CollatorInstance { public: CollatorInstance() { UErrorCode status = U_ZERO_ERROR; m_collator = icu::Collator::createInstance(status); if (U_FAILURE(status)) { kdbWarning() << "Could not create instance of collator:" << status; m_collator = nullptr; } else { // enable normalization by default m_collator->setAttribute(UCOL_NORMALIZATION_MODE, UCOL_ON, status); if (U_FAILURE(status)) { kdbWarning() << "Could not set collator attribute:" << status; } } } icu::Collator* getCollator() { return m_collator; } ~CollatorInstance() { delete m_collator; } private: icu::Collator *m_collator; }; Q_GLOBAL_STATIC(CollatorInstance, KDb_collator) //! @internal A functor used in qSort() in order to sort by a given column class LessThanFunctor { private: KDbOrderByColumn::SortOrder m_order; QVariant m_leftTmp, m_rightTmp; int m_sortColumn; bool (*m_lessThanFunction)(const QVariant&, const QVariant&); #define CAST_AND_COMPARE(casting) \ return left.casting() < right.casting() static bool cmpInt(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toInt); } static bool cmpUInt(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toUInt); } static bool cmpLongLong(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toLongLong); } static bool cmpULongLong(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toULongLong); } static bool cmpDouble(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toDouble); } static bool cmpDate(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toDate); } static bool cmpDateTime(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toDateTime); } static bool cmpTime(const QVariant& left, const QVariant& right) { CAST_AND_COMPARE(toDate); } static bool cmpString(const QVariant& left, const QVariant& right) { const QString &as = left.toString(); const QString &bs = right.toString(); const QChar *a = as.isEmpty() ? nullptr : as.unicode(); const QChar *b = bs.isEmpty() ? nullptr : bs.unicode(); if (a == nullptr) { return b != nullptr; } if (a == b || b == nullptr) { return false; } int len = qMin(as.length(), bs.length()); forever { unsigned short au = a->unicode(); unsigned short bu = b->unicode(); au = (au <= 0x17e ? charTable[au] : 0xffff); bu = (bu <= 0x17e ? charTable[bu] : 0xffff); if (len <= 0) return false; len--; if (au != bu) return au < bu; a++; b++; } return false; } static bool cmpStringWithCollator(const QVariant& left, const QVariant& right) { const QString &as = left.toString(); const QString &bs = right.toString(); return icu::Collator::LESS == KDb_collator->getCollator()->compare( (const UChar *)as.constData(), as.size(), (const UChar *)bs.constData(), bs.size()); } //! Compare function for BLOB data (QByteArray). Uses size as the weight. static bool cmpBLOB(const QVariant& left, const QVariant& right) { return left.toByteArray().size() < right.toByteArray().size(); } public: LessThanFunctor() : m_order(KDbOrderByColumn::SortOrder::Ascending) , m_sortColumn(-1) , m_lessThanFunction(nullptr) { } void setColumnType(const KDbField& field) { const KDbField::Type t = field.type(); if (field.isTextType()) m_lessThanFunction = &cmpString; if (KDbField::isFPNumericType(t)) m_lessThanFunction = &cmpDouble; else if (t == KDbField::Integer && field.isUnsigned()) m_lessThanFunction = &cmpUInt; else if (t == KDbField::Boolean || KDbField::isNumericType(t)) m_lessThanFunction = &cmpInt; //other integers else if (t == KDbField::BigInteger) { if (field.isUnsigned()) m_lessThanFunction = &cmpULongLong; else m_lessThanFunction = &cmpLongLong; } else if (t == KDbField::Date) m_lessThanFunction = &cmpDate; else if (t == KDbField::Time) m_lessThanFunction = &cmpTime; else if (t == KDbField::DateTime) m_lessThanFunction = &cmpDateTime; else if (t == KDbField::BLOB) //! @todo allow users to define BLOB sorting function? m_lessThanFunction = &cmpBLOB; else { // anything else // check if CollatorInstance is not destroyed and has valid collator if (!KDb_collator.isDestroyed() && KDb_collator->getCollator()) { m_lessThanFunction = &cmpStringWithCollator; } else { m_lessThanFunction = &cmpString; } } } void setSortOrder(KDbOrderByColumn::SortOrder order) { m_order = order; } void setSortColumn(int column) { m_sortColumn = column; } #define _IIF(a,b) ((a) ? (b) : !(b)) //! Main comparison operator that takes column number, type and order into account bool operator()(KDbRecordData* record1, KDbRecordData* record2) { // compare NULLs : NULL is smaller than everything if ((m_leftTmp = record1->at(m_sortColumn)).isNull()) return _IIF(m_order == KDbOrderByColumn::SortOrder::Ascending, !record2->at(m_sortColumn).isNull()); if ((m_rightTmp = record2->at(m_sortColumn)).isNull()) return m_order == KDbOrderByColumn::SortOrder::Descending; return _IIF(m_order == KDbOrderByColumn::SortOrder::Ascending, m_lessThanFunction(m_leftTmp, m_rightTmp)); } }; #undef _IIF #undef CAST_AND_COMPARE //! @internal class Q_DECL_HIDDEN KDbTableViewData::Private { public: Private() : sortColumn(0) , realSortColumn(0) , sortOrder(KDbOrderByColumn::SortOrder::Ascending) , type(1) , pRecordEditBuffer(nullptr) , readOnly(false) , insertingEnabled(true) , containsRecordIdInfo(false) , autoIncrementedColumn(-2) { } ~Private() { delete pRecordEditBuffer; } //! Number of physical columns int realColumnCount; /*! Columns information */ QList columns; /*! Visible columns information */ QList visibleColumns; //! (Logical) sorted column number, set by setSorting(). //! Can differ from realSortColumn if there's lookup column used. int sortColumn; //! Real sorted column number, set by setSorting(), used by cmp*() methods int realSortColumn; //! Specifies sorting order KDbOrderByColumn::SortOrder sortOrder; LessThanFunctor lessThanFunctor; short type; KDbRecordEditBuffer *pRecordEditBuffer; KDbCursor *cursor; KDbResultInfo result; QList visibleColumnIDs; QList globalColumnIDs; bool readOnly; bool insertingEnabled; //! @see KDbTableViewData::containsRecordIdInfo() bool containsRecordIdInfo; mutable int autoIncrementedColumn; }; //------------------------------- KDbTableViewData::KDbTableViewData() : QObject() , KDbTableViewDataBase() , d(new Private) { d->realColumnCount = 0; d->cursor = nullptr; } // db-aware ctor KDbTableViewData::KDbTableViewData(KDbCursor *c) : QObject() , KDbTableViewDataBase() , d(new Private) { d->cursor = c; d->containsRecordIdInfo = d->cursor->containsRecordIdInfo(); if (d->cursor && d->cursor->query()) { - const KDbQuerySchema::FieldsExpandedOptions fieldsExpandedOptions - = d->containsRecordIdInfo ? KDbQuerySchema::WithInternalFieldsAndRecordId - : KDbQuerySchema::WithInternalFields; - d->realColumnCount = d->cursor->query()->fieldsExpanded(fieldsExpandedOptions).count(); + const KDbQuerySchema::FieldsExpandedMode fieldsExpandedMode + = d->containsRecordIdInfo ? KDbQuerySchema::FieldsExpandedMode::WithInternalFieldsAndRecordId + : KDbQuerySchema::FieldsExpandedMode::WithInternalFields; + d->realColumnCount = d->cursor->query()->fieldsExpanded( + d->cursor->connection(), fieldsExpandedMode).count(); } else { d->realColumnCount = d->columns.count() + (d->containsRecordIdInfo ? 1 : 0); } // Allocate KDbTableViewColumn objects for each visible query column - const KDbQueryColumnInfo::Vector fields = d->cursor->query()->fieldsExpanded(); + const KDbQueryColumnInfo::Vector fields + = d->cursor->query()->fieldsExpanded(d->cursor->connection()); const int fieldCount = fields.count(); for (int i = 0;i < fieldCount;i++) { KDbQueryColumnInfo *ci = fields[i]; if (ci->isVisible()) { KDbQueryColumnInfo *visibleLookupColumnInfo = nullptr; if (ci->indexForVisibleLookupValue() != -1) { - //Lookup field is defined - visibleLookupColumnInfo = d->cursor->query()->expandedOrInternalField(ci->indexForVisibleLookupValue()); + // Lookup field is defined + visibleLookupColumnInfo = d->cursor->query()->expandedOrInternalField( + d->cursor->connection(), ci->indexForVisibleLookupValue()); } KDbTableViewColumn* col = new KDbTableViewColumn(*d->cursor->query(), ci, visibleLookupColumnInfo); addColumn(col); } } } KDbTableViewData::KDbTableViewData(const QList &keys, const QList &values, KDbField::Type keyType, KDbField::Type valueType) : KDbTableViewData() { KDbField *keyField = new KDbField(QLatin1String("key"), keyType); keyField->setPrimaryKey(true); KDbTableViewColumn *keyColumn = new KDbTableViewColumn(keyField, KDbTableViewColumn::FieldIsOwned::Yes); keyColumn->setVisible(false); addColumn(keyColumn); KDbField *valueField = new KDbField(QLatin1String("value"), valueType); KDbTableViewColumn *valueColumn = new KDbTableViewColumn(valueField, KDbTableViewColumn::FieldIsOwned::Yes); addColumn(valueColumn); int cnt = qMin(keys.count(), values.count()); QList::ConstIterator it_keys = keys.constBegin(); QList::ConstIterator it_values = values.constBegin(); for (;cnt > 0;++it_keys, ++it_values, cnt--) { KDbRecordData *record = new KDbRecordData(2); (*record)[0] = (*it_keys); (*record)[1] = (*it_values); append(record); } } KDbTableViewData::KDbTableViewData(KDbField::Type keyType, KDbField::Type valueType) : KDbTableViewData(QList(), QList(), keyType, valueType) { } KDbTableViewData::~KDbTableViewData() { emit destroying(); clearInternal(false /* !processEvents */); qDeleteAll(d->columns); delete d; } void KDbTableViewData::deleteLater() { d->cursor = nullptr; QObject::deleteLater(); } void KDbTableViewData::addColumn(KDbTableViewColumn* col) { d->columns.append(col); col->setData(this); if (col->isVisible()) { d->visibleColumns.append(col); d->visibleColumnIDs.append(d->visibleColumns.count() - 1); d->globalColumnIDs.append(d->columns.count() - 1); } else { d->visibleColumnIDs.append(-1); } d->autoIncrementedColumn = -2; //clear cache; if (!d->cursor || !d->cursor->query()) { d->realColumnCount = d->columns.count() + (d->containsRecordIdInfo ? 1 : 0); } } void KDbTableViewData::columnVisibilityChanged(const KDbTableViewColumn &column) { if (column.isVisible()) { // column made visible int indexInGlobal = d->columns.indexOf(const_cast(&column)); // find previous column that is visible int prevIndexInGlobal = indexInGlobal - 1; while (prevIndexInGlobal >= 0 && d->visibleColumnIDs[prevIndexInGlobal] == -1) { prevIndexInGlobal--; } int indexInVisible = prevIndexInGlobal + 1; // update d->visibleColumns.insert(indexInVisible, const_cast(&column)); d->visibleColumnIDs[indexInGlobal] = indexInVisible; d->globalColumnIDs.insert(indexInVisible, indexInGlobal); for (int i = indexInGlobal + 1; i < d->columns.count(); i++) { // increment ids of the rest if (d->visibleColumnIDs[i] >= 0) { d->visibleColumnIDs[i]++; } } } else { // column made invisible int indexInVisible = d->visibleColumns.indexOf(const_cast(&column)); d->visibleColumns.removeAt(indexInVisible); int indexInGlobal = globalIndexOfVisibleColumn(indexInVisible); d->visibleColumnIDs[indexInGlobal] = -1; d->globalColumnIDs.removeAt(indexInVisible); } } int KDbTableViewData::globalIndexOfVisibleColumn(int visibleIndex) const { return d->globalColumnIDs.value(visibleIndex, -1); } int KDbTableViewData::visibleColumnIndex(int globalIndex) const { return d->visibleColumnIDs.value(globalIndex, -1); } int KDbTableViewData::columnCount() const { return d->columns.count(); } int KDbTableViewData::visibleColumnCount() const { return d->visibleColumns.count(); } QList* KDbTableViewData::columns() { return &d->columns; } QList* KDbTableViewData::visibleColumns() { return &d->visibleColumns; } KDbTableViewColumn* KDbTableViewData::column(int index) { return d->columns.value(index); } KDbTableViewColumn* KDbTableViewData::visibleColumn(int index) { return d->visibleColumns.value(index); } bool KDbTableViewData::isDBAware() const { return d->cursor != nullptr; } KDbCursor* KDbTableViewData::cursor() const { return d->cursor; } bool KDbTableViewData::isInsertingEnabled() const { return d->insertingEnabled; } KDbRecordEditBuffer* KDbTableViewData::recordEditBuffer() const { return d->pRecordEditBuffer; } const KDbResultInfo& KDbTableViewData::result() const { return d->result; } bool KDbTableViewData::containsRecordIdInfo() const { return d->containsRecordIdInfo; } KDbRecordData* KDbTableViewData::createItem() const { return new KDbRecordData(d->realColumnCount); } QString KDbTableViewData::dbTableName() const { if (d->cursor && d->cursor->query() && d->cursor->query()->masterTable()) return d->cursor->query()->masterTable()->name(); return QString(); } void KDbTableViewData::setSorting(int column, KDbOrderByColumn::SortOrder order) { d->sortOrder = order; if (column < 0 || column >= d->columns.count()) { d->sortColumn = -1; d->realSortColumn = -1; return; } // find proper column information for sorting (lookup column points to alternate column with visible data) const KDbTableViewColumn *tvcol = d->columns.at(column); const KDbQueryColumnInfo* visibleLookupColumnInfo = tvcol->visibleLookupColumnInfo(); const KDbField *field = visibleLookupColumnInfo ? visibleLookupColumnInfo->field() : tvcol->field(); d->sortColumn = column; d->realSortColumn = tvcol->columnInfo()->indexForVisibleLookupValue() != -1 ? tvcol->columnInfo()->indexForVisibleLookupValue() : d->sortColumn; // setup compare functor d->lessThanFunctor.setColumnType(*field); d->lessThanFunctor.setSortOrder(d->sortOrder); d->lessThanFunctor.setSortColumn(column); } int KDbTableViewData::sortColumn() const { return d->sortColumn; } KDbOrderByColumn::SortOrder KDbTableViewData::sortOrder() const { return d->sortOrder; } void KDbTableViewData::sort() { if (d->sortColumn < 0 || d->sortColumn >= d->columns.count()) { return; } qSort(begin(), end(), d->lessThanFunctor); } void KDbTableViewData::setReadOnly(bool set) { if (d->readOnly == set) return; d->readOnly = set; if (d->readOnly) setInsertingEnabled(false); } void KDbTableViewData::setInsertingEnabled(bool set) { if (d->insertingEnabled == set) return; d->insertingEnabled = set; if (d->insertingEnabled) setReadOnly(false); } void KDbTableViewData::clearRecordEditBuffer() { //init record edit buffer if (!d->pRecordEditBuffer) d->pRecordEditBuffer = new KDbRecordEditBuffer(isDBAware()); else d->pRecordEditBuffer->clear(); } bool KDbTableViewData::updateRecordEditBufferRef(KDbRecordData *record, int colnum, KDbTableViewColumn* col, QVariant* newval, bool allowSignals, QVariant *visibleValueForLookupField) { if (!record || !newval) { return false; } d->result.clear(); if (allowSignals) emit aboutToChangeCell(record, colnum, newval, &d->result); if (!d->result.success) return false; //kdbDebug() << "column #" << colnum << " = " << newval.toString(); if (!col) { kdbWarning() << "column #" << colnum << "not found! col==0"; return false; } if (!d->pRecordEditBuffer) d->pRecordEditBuffer = new KDbRecordEditBuffer(isDBAware()); if (d->pRecordEditBuffer->isDBAware()) { if (!(col->columnInfo())) { kdbWarning() << "column #" << colnum << " not found!"; return false; } d->pRecordEditBuffer->insert(col->columnInfo(), *newval); if (col->visibleLookupColumnInfo() && visibleValueForLookupField) { //this is value for lookup table: update visible value as well d->pRecordEditBuffer->insert(col->visibleLookupColumnInfo(), *visibleValueForLookupField); } return true; } if (!(col->field())) { kdbWarning() << "column #" << colnum << "not found!"; return false; } //not db-aware: const QString colname = col->field()->name(); if (colname.isEmpty()) { kdbWarning() << "column #" << colnum << "not found!"; return false; } d->pRecordEditBuffer->insert(colname, *newval); return true; } bool KDbTableViewData::updateRecordEditBuffer(KDbRecordData *record, int colnum, KDbTableViewColumn* col, const QVariant &newval, bool allowSignals) { QVariant newv(newval); return updateRecordEditBufferRef(record, colnum, col, &newv, allowSignals); } bool KDbTableViewData::updateRecordEditBuffer(KDbRecordData *record, int colnum, const QVariant &newval, bool allowSignals) { KDbTableViewColumn* col = d->columns.value(colnum); QVariant newv(newval); return col ? updateRecordEditBufferRef(record, colnum, col, &newv, allowSignals) : false; } //! Get a new value (if present in the buffer), or the old one (taken here for optimization) static inline void saveRecordGetValue(const QVariant **pval, KDbCursor *cursor, KDbRecordEditBuffer *pRecordEditBuffer, QList::ConstIterator* it_f, KDbRecordData *record, KDbField *f, QVariant* val, int col) { if (!*pval) { *pval = cursor ? pRecordEditBuffer->at( (**it_f)->columnInfo(), record->at(col).isNull() /* useDefaultValueIfPossible */ ) : pRecordEditBuffer->at( *f ); *val = *pval ? **pval : record->at(col); /* get old value */ //kdbDebug() << col << *(**it_f)->columnInfo() << "val:" << *val; } } //! @todo if there're multiple views for this data, we need multiple buffers! bool KDbTableViewData::saveRecord(KDbRecordData *record, bool insert, bool repaint) { Q_UNUSED(record); if (!d->pRecordEditBuffer) return true; //nothing to do //check constraints: //-check if every NOT NULL and NOT EMPTY field is filled QList::ConstIterator it_f(d->columns.constBegin()); int col = 0; const QVariant *pval = nullptr; QVariant val; for (;it_f != d->columns.constEnd() && col < record->count();++it_f, ++col) { KDbField *f = (*it_f)->field(); if (f->isNotNull()) { saveRecordGetValue(&pval, d->cursor, d->pRecordEditBuffer, &it_f, record, f, &val, col); //check it if (val.isNull() && !f->isAutoIncrement()) { //NOT NULL violated d->result.message = tr("\"%1\" column requires a value to be entered.").arg(f->captionOrName()) + QLatin1String("\n\n") + KDbTableViewData::messageYouCanImproveData(); d->result.description = tr("The column's constraint is declared as NOT NULL."); d->result.column = col; return false; } } if (f->isNotEmpty()) { saveRecordGetValue(&pval, d->cursor, d->pRecordEditBuffer, &it_f, record, f, &val, col); if (!f->isAutoIncrement() && (val.isNull() || KDb::isEmptyValue(f->type(), val))) { //NOT EMPTY violated d->result.message = tr("\"%1\" column requires a value to be entered.").arg(f->captionOrName()) + QLatin1String("\n\n") + KDbTableViewData::messageYouCanImproveData(); d->result.description = tr("The column's constraint is declared as NOT EMPTY."); d->result.column = col; return false; } } } if (d->cursor) {//db-aware if (insert) { if (!d->cursor->insertRecord(record, d->pRecordEditBuffer, d->containsRecordIdInfo /*also retrieve ROWID*/)) { d->result.message = tr("Record inserting failed.") + QLatin1String("\n\n") + KDbTableViewData::messageYouCanImproveData(); KDb::getHTMLErrorMesage(*d->cursor, &d->result); /* if (desc) *desc = */ /*! @todo use KexiMainWindow::showErrorMessage(const QString &title, KDbObject *obj) after it will be moved somewhere to KDb (this will require moving other showErrorMessage() methods from KexiMainWindow to libkexiutils....) then: just call: *desc = KDb::errorMessage(d->cursor); */ return false; } } else { // record updating if (!d->cursor->updateRecord(static_cast(record), d->pRecordEditBuffer, d->containsRecordIdInfo /*use ROWID*/)) { d->result.message = tr("Record changing failed.") + QLatin1String("\n\n") + KDbTableViewData::messageYouCanImproveData(); //! @todo set d->result.column if possible KDb::getHTMLErrorMesage(*d->cursor, &d->result.description); return false; } } } else {//not db-aware version KDbRecordEditBuffer::SimpleMap b = d->pRecordEditBuffer->simpleBuffer(); for (KDbRecordEditBuffer::SimpleMap::ConstIterator it = b.constBegin();it != b.constEnd();++it) { int i = -1; foreach(KDbTableViewColumn *col, d->columns) { i++; if (col->field()->name() == it.key()) { kdbDebug() << col->field()->name() << ": " << record->at(i).toString() << " -> " << it.value().toString(); (*record)[i] = it.value(); } } } } d->pRecordEditBuffer->clear(); if (repaint) emit recordRepaintRequested(record); return true; } bool KDbTableViewData::saveRecordChanges(KDbRecordData *record, bool repaint) { Q_UNUSED(record); d->result.clear(); emit aboutToUpdateRecord(record, d->pRecordEditBuffer, &d->result); if (!d->result.success) return false; if (saveRecord(record, false /*update*/, repaint)) { emit recordUpdated(record); return true; } return false; } bool KDbTableViewData::saveNewRecord(KDbRecordData *record, bool repaint) { Q_UNUSED(record); d->result.clear(); emit aboutToInsertRecord(record, &d->result, repaint); if (!d->result.success) return false; if (saveRecord(record, true /*insert*/, repaint)) { emit recordInserted(record, repaint); return true; } return false; } bool KDbTableViewData::deleteRecord(KDbRecordData *record, bool repaint) { Q_UNUSED(record); d->result.clear(); emit aboutToDeleteRecord(record, &d->result, repaint); if (!d->result.success) return false; if (d->cursor) {//db-aware d->result.success = false; if (!d->cursor->deleteRecord(static_cast(record), d->containsRecordIdInfo /*use ROWID*/)) { d->result.message = tr("Record deleting failed."); //! @todo use KDberrorMessage() for description as in KDbTableViewData::saveRecord() */ KDb::getHTMLErrorMesage(*d->cursor, &d->result); d->result.success = false; return false; } } int index = indexOf(record); if (index == -1) { //aah - this shouldn't be! kdbWarning() << "!removeRef() - IMPL. ERROR?"; d->result.success = false; return false; } removeAt(index); emit recordDeleted(); return true; } void KDbTableViewData::deleteRecords(const QList &recordsToDelete, bool repaint) { Q_UNUSED(repaint); if (recordsToDelete.isEmpty()) return; int last_r = 0; KDbTableViewDataIterator it(begin()); for (QList::ConstIterator r_it = recordsToDelete.constBegin(); r_it != recordsToDelete.constEnd(); ++r_it) { for (; last_r < (*r_it); last_r++) ++it; it = erase(it); /* this will delete *it */ last_r++; } //DON'T CLEAR BECAUSE KexiTableViewPropertyBuffer will clear BUFFERS! //--> emit reloadRequested(); //! \todo more effective? emit recordsDeleted(recordsToDelete); } void KDbTableViewData::insertRecord(KDbRecordData *record, int index, bool repaint) { Q_UNUSED(record); insert(index = qMin(index, count()), record); emit recordInserted(record, index, repaint); } void KDbTableViewData::clearInternal(bool processEvents) { clearRecordEditBuffer(); //! @todo this is time consuming: find better data model const int c = count(); #ifndef TABLEVIEW_NO_PROCESS_EVENTS const bool _processEvents = processEvents && !qApp->closingDown(); #endif for (int i = 0; i < c; i++) { removeLast(); #ifndef TABLEVIEW_NO_PROCESS_EVENTS if (_processEvents && i % 1000 == 0) qApp->processEvents(QEventLoop::AllEvents, 1); #endif } } bool KDbTableViewData::deleteAllRecords(bool repaint) { clearInternal(); bool res = true; if (d->cursor) { //db-aware res = d->cursor->deleteAllRecords(); } if (repaint) emit reloadRequested(); return res; } int KDbTableViewData::autoIncrementedColumn() const { if (d->autoIncrementedColumn == -2) { //find such a column d->autoIncrementedColumn = -1; foreach(KDbTableViewColumn *col, d->columns) { d->autoIncrementedColumn++; if (col->field()->isAutoIncrement()) break; } } return d->autoIncrementedColumn; } bool KDbTableViewData::preloadAllRecords() { if (!d->cursor) return false; if (!d->cursor->moveFirst() && d->cursor->result().isError()) return false; #ifndef TABLEVIEW_NO_PROCESS_EVENTS const bool processEvents = !qApp->closingDown(); #endif for (int i = 0;!d->cursor->eof();i++) { KDbRecordData *record = d->cursor->storeCurrentRecord(); if (!record) { clear(); return false; } // record->debug(); append(record); if (!d->cursor->moveNext() && d->cursor->result().isError()) { clear(); return false; } #ifndef TABLEVIEW_NO_PROCESS_EVENTS if (processEvents && (i % 1000) == 0) qApp->processEvents(QEventLoop::AllEvents, 1); #endif } return true; } bool KDbTableViewData::isReadOnly() const { return d->readOnly || (d->cursor && d->cursor->connection()->options()->isReadOnly()); } // static QString KDbTableViewData::messageYouCanImproveData() { return tr("Please correct data in this record or use the \"Cancel record changes\" function."); } QDebug operator<<(QDebug dbg, const KDbTableViewData &data) { dbg.nospace() << "TableViewData("; dbg.space() << "sortColumn:" << data.sortColumn() << "sortOrder:" << (data.sortOrder() == KDbOrderByColumn::SortOrder::Ascending ? "asc" : "desc") << "isDBAware:" << data.isDBAware() << "dbTableName:" << data.dbTableName() << "cursor:" << (data.cursor() ? "yes" : "no") << "columnCount:" << data.columnCount() << "count:" << data.count() << "autoIncrementedColumn:" << data.autoIncrementedColumn() << "visibleColumnCount:" << data.visibleColumnCount() << "isReadOnly:" << data.isReadOnly() << "isInsertingEnabled:" << data.isInsertingEnabled() << "containsRecordIdInfo:" << data.containsRecordIdInfo() << "result:" << data.result(); dbg.nospace() << ")"; return dbg.space(); } diff --git a/tests/features/parser_test.h b/tests/features/parser_test.h index 1a38107f..985bb67c 100644 --- a/tests/features/parser_test.h +++ b/tests/features/parser_test.h @@ -1,70 +1,70 @@ /* This file is part of the KDE project Copyright (C) 2003-2004 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 PARSER_TEST_H #define PARSER_TEST_H #include #include #include int parserTest(const KDbEscapedString &st, const QStringList ¶ms) { int r = 0; if (!conn->useDatabase()) { qDebug() << conn->result(); return 1; } KDbParser parser(conn); const bool ok = parser.parse(st); KDbQuerySchema *q = parser.query(); QList variantParams; for(const QString ¶m : params) { variantParams.append(param.toLocal8Bit()); } if (ok && q) { - cout << qPrintable(KDbUtils::debugString(*q)) << '\n'; + cout << qPrintable(KDbUtils::debugString(KDbConnectionAndQuerySchema(conn, *q))) << '\n'; KDbNativeStatementBuilder builder(conn); KDbEscapedString sql; if (builder.generateSelectStatement(&sql, q, variantParams)) { cout << "-STATEMENT:\n" << sql.toByteArray().constData() << '\n'; } else { cout << "-CANNOT GENERATE STATEMENT\n"; } } else { qDebug() << parser.error(); r = 1; } delete q; q = nullptr; if (!conn->closeDatabase()) { qDebug() << conn->result(); return 1; } return r; } #endif