Warning, file /libraries/kdb/src/KDb.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).
0001 /* This file is part of the KDE project 0002 Copyright (C) 2004-2018 Jarosław Staniek <staniek@kde.org> 0003 0004 This library is free software; you can redistribute it and/or 0005 modify it under the terms of the GNU Library General Public 0006 License as published by the Free Software Foundation; either 0007 version 2 of the License, or (at your option) any later version. 0008 0009 This library is distributed in the hope that it will be useful, 0010 but WITHOUT ANY WARRANTY; without even the implied warranty of 0011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 0012 Library General Public License for more details. 0013 0014 You should have received a copy of the GNU Library General Public License 0015 along with this library; see the file COPYING.LIB. If not, write to 0016 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 0017 * Boston, MA 02110-1301, USA. 0018 */ 0019 0020 #ifndef KDB_H 0021 #define KDB_H 0022 0023 #include "KDbField.h" 0024 #include "KDbGlobal.h" 0025 #include "KDbSqlResult.h" 0026 #include "KDbTableSchema.h" 0027 0028 class QDomNode; 0029 class QDomElement; 0030 class QDomDocument; 0031 0032 class KDbConnection; 0033 class KDbConnectionData; 0034 class KDbDriver; 0035 class KDbEscapedString; 0036 class KDbLookupFieldSchema; 0037 class KDbMessageHandler; 0038 class KDbResultable; 0039 class KDbResultInfo; 0040 class KDbTableOrQuerySchema; 0041 class KDbVersionInfo; 0042 class tristate; 0043 0044 namespace KDb 0045 { 0046 0047 //! @return runtime information about version of the KDb library. 0048 //! @see KDbConnection::databaseVersion() KDbConnection::serverVersion() KDbDriverMetaData::version() 0049 KDB_EXPORT KDbVersionInfo version(); 0050 0051 /** 0052 * @brief Deletes records using one generic criteria. 0053 * 0054 * @return @c true on success and @c false on failure and if @a conn is @c nullptr 0055 */ 0056 KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, 0057 const QString &keyname, KDbField::Type keytype, const QVariant &keyval); 0058 0059 //! @overload 0060 inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, 0061 const QString &keyname, KDbField::Type keytype, const QVariant &keyval) 0062 { 0063 return deleteRecords(conn, table.name(), keyname, keytype, keyval); 0064 } 0065 0066 //! @overload 0067 inline bool deleteRecords(KDbConnection* conn, const QString &tableName, 0068 const QString &keyname, const QString &keyval) 0069 { 0070 return deleteRecords(conn, tableName, keyname, KDbField::Text, keyval); 0071 } 0072 0073 //! @overload 0074 inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, 0075 const QString &keyname, const QString &keyval) 0076 { 0077 return deleteRecords(conn, table.name(), keyname, keyval); 0078 } 0079 0080 //! @overload 0081 inline bool deleteRecords(KDbConnection* conn, const KDbTableSchema &table, 0082 const QString& keyname, int keyval) 0083 { 0084 return deleteRecords(conn, table, keyname, KDbField::Integer, keyval); 0085 } 0086 0087 //! @overload 0088 inline bool deleteRecords(KDbConnection* conn, const QString &tableName, 0089 const QString& keyname, int keyval) 0090 { 0091 return deleteRecords(conn, tableName, keyname, KDbField::Integer, keyval); 0092 } 0093 0094 //! Deletes records with two generic criterias. 0095 KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, 0096 const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, 0097 const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2); 0098 0099 //! Deletes records with three generic criterias. 0100 KDB_EXPORT bool deleteRecords(KDbConnection* conn, const QString &tableName, 0101 const QString &keyname1, KDbField::Type keytype1, const QVariant& keyval1, 0102 const QString &keyname2, KDbField::Type keytype2, const QVariant& keyval2, 0103 const QString &keyname3, KDbField::Type keytype3, const QVariant& keyval3); 0104 0105 //! Deletes all records from table @a tableName. 0106 KDB_EXPORT bool deleteAllRecords(KDbConnection* conn, const QString &tableName); 0107 0108 //! @overload bool deleteAllRecords(KDbConnection*, const QString&); 0109 inline bool deleteAllRecords(KDbConnection* conn, const KDbTableSchema &table) 0110 { 0111 return KDb::deleteAllRecords(conn, table.name()); 0112 } 0113 0114 /** 0115 * Returns value of last inserted record for an autoincrement field 0116 * 0117 * This method internally fetches values of the last inserted record for which @a result was 0118 * returned and returns selected field's value. The field belong to @a tableName table. 0119 * The field must be of integer type, there must be a record inserted using query for which the @a 0120 * result is returned. 0121 * std::numeric_limits<quint64>::max() is returned on error or if @a result is null. 0122 * The last inserted record is identified by a magical record identifier, usually called ROWID 0123 * (PostgreSQL has it as well as SQLite; 0124 * see KDbDriverBehavior::ROW_ID_FIELD_RETURNS_LAST_AUTOINCREMENTED_VALUE). 0125 * ROWID's value will be assigned back to @a recordId if this pointer is not @c nullptr. 0126 */ 0127 KDB_EXPORT quint64 lastInsertedAutoIncValue(QSharedPointer<KDbSqlResult> result, 0128 const QString &autoIncrementFieldName, 0129 const QString &tableName, quint64 *recordId = nullptr); 0130 0131 /** 0132 * @overload 0133 * 0134 * Accepts @a recordId that can be obtained from KDbPreparedStatement::lastInsertRecordId() 0135 * or KDbSqlResult::lastInsertRecordId(). 0136 */ 0137 KDB_EXPORT quint64 lastInsertedAutoIncValue(KDbConnection *conn, const quint64 recordId, 0138 const QString &autoIncrementFieldName, 0139 const QString &tableName); 0140 0141 /** 0142 @overload 0143 */ 0144 inline quint64 lastInsertedAutoIncValue(QSharedPointer<KDbSqlResult> result, 0145 const QString &autoIncrementFieldName, 0146 const KDbTableSchema &table, quint64 *recordId = nullptr) 0147 { 0148 return lastInsertedAutoIncValue(result, autoIncrementFieldName, table.name(), recordId); 0149 } 0150 0151 /*! @return list of field types for field type group @a typeGroup. */ 0152 KDB_EXPORT const QList<KDbField::Type> fieldTypesForGroup(KDbField::TypeGroup typeGroup); 0153 0154 /*! @return list of translated field type names for field type group @a typeGroup. */ 0155 KDB_EXPORT QStringList fieldTypeNamesForGroup(KDbField::TypeGroup typeGroup); 0156 0157 /*! @return list of (nontranslated) field type names for field type group @a typeGroup. */ 0158 KDB_EXPORT QStringList fieldTypeStringsForGroup(KDbField::TypeGroup typeGroup); 0159 0160 /*! @return default field type for field type group @a typeGroup, 0161 for example, KDbField::Integer for KDbField::IntegerGroup. 0162 It is used e.g. in KexiAlterTableDialog, to properly fill 0163 'type' property when user selects type group for a field. */ 0164 KDB_EXPORT KDbField::Type defaultFieldTypeForGroup(KDbField::TypeGroup typeGroup); 0165 0166 /*! @return a slightly simplified field type name type @a type. 0167 For KDbField::BLOB type it returns a translated "Image" string or other, depending on the mime type. 0168 For numbers (either floating-point or integer) it returns a translated "Number" string. 0169 For other types KDbField::typeGroupName() is returned. */ 0170 //! @todo support names of other BLOB subtypes 0171 KDB_EXPORT QString simplifiedFieldTypeName(KDbField::Type type); 0172 0173 /*! @return true if value @a value represents an empty (but not null) value. 0174 - Case 1: If field type @a type is of any text type (KDbField::isTextType(type) == true) 0175 then the function returns true if @a value casted to a QString value is empty and not null. 0176 - Case 2: If field type @a type is KDbField::BLOB then the function returns if @a value casted 0177 to a QByteArray value is empty and not null. 0178 - Case 3: If field type @a type is of any other type then the function returns true if value.isNull(). 0179 @see KDbField::hasEmptyProperty() */ 0180 KDB_EXPORT bool isEmptyValue(KDbField::Type type, const QVariant &value); 0181 0182 /** 0183 * @brief Sets HTML-formatted error message with extra details obtained from result object 0184 * 0185 * Sets string pointed by @a msg to an error message retrieved from @a resultable, 0186 * and string pointed by @a details to details of this error (server message and result number). 0187 * Does nothing if there is no error (resultable.result().isError() == false) or if @a msg or 0188 * @a details is @c nullptr. 0189 * In this case strings pointer by @a msg and @a details strings are not changed. 0190 * If the string pointed by @a msg is not empty, it is not modified and message obtained from 0191 * @a resultable is appended to the string pointed by @a details instead. 0192 */ 0193 KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg, QString *details); 0194 0195 /** 0196 * @overload 0197 * 0198 * This methods works similarly but appends both a message and a description to string pointed by 0199 * @a msg. 0200 */ 0201 KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, QString *msg); 0202 0203 /** 0204 * @overload 0205 * 0206 * This methods similarly but outputs message to @a info instead. 0207 */ 0208 KDB_EXPORT void getHTMLErrorMesage(const KDbResultable& resultable, KDbResultInfo *info); 0209 0210 /*! Function useful for building WHERE parts of SQL statements. 0211 Constructs an SQL string like "fielname = value" for specific @a drv driver, 0212 field type @a t, @a fieldName and @a value. If @a value is null, "fieldname IS NULL" 0213 string is returned. */ 0214 KDB_EXPORT KDbEscapedString sqlWhere(KDbDriver *drv, KDbField::Type t, 0215 const QString& fieldName, const QVariant& value); 0216 0217 /** 0218 * @brief Finds an identifier for object @a objName of type @a objType 0219 * 0220 * On success true is returned and *id is set to the value of the identifier. 0221 * On failure or if @a conn is @c nullptr, @c false is returned. 0222 * If there is no object with specified name and type, @c cancelled value is returned. 0223 */ 0224 KDB_EXPORT tristate idForObjectName(KDbConnection* conn, int *id, const QString& objName, 0225 int objType); 0226 0227 /** 0228 * @brief Shows connection test dialog 0229 * 0230 * Shows connection test dialog with a progress bar indicating connection testing 0231 * (within a separate thread). @a data is used to perform a (temporary) test connection. 0232 * @a msgHandler can be used for error handling. @a parent is used as dialog's parent widget. 0233 * 0234 * The dialog is modal so the call is blocking. 0235 * 0236 * On successful connecting, a successfull message of type KDbMessageHandler::Information is passed 0237 * to @a msgHandler. After testing, temporary connection is closed. 0238 * 0239 * @return @c true for successfull connecting, @c for failed connecting and @c cancelled if the test 0240 * has been cancelled. 0241 */ 0242 KDB_EXPORT tristate showConnectionTestDialog(QWidget* parent, const KDbConnectionData& data, 0243 KDbMessageHandler* msgHandler); 0244 0245 //! Used in splitToTableAndFieldParts(). 0246 enum SplitToTableAndFieldPartsOptions { 0247 FailIfNoTableOrFieldName = 0, //!< default value for splitToTableAndFieldParts() 0248 SetFieldNameIfNoTableName = 1 //!< see splitToTableAndFieldParts() 0249 }; 0250 0251 /*! Splits @a string like "table.field" into "table" and "field" parts. 0252 On success, a table name is passed to @a tableName and a field name is passed to @a fieldName. 0253 The function fails if either: 0254 - @a string is empty, or 0255 - @a string does not contain '.' character and @a option is FailIfNoTableOrFieldName 0256 (the default), or 0257 - '.' character is the first of last character of @a string (in this case table name 0258 or field name could become empty what is not allowed). 0259 - @a tableName or @a fieldName is @c nullptr 0260 0261 If @a option is SetFieldNameIfNoTableName and @a string does not contain '.', 0262 @a string is passed to @a fieldName and @a tableName is set to QString() 0263 without failure. 0264 0265 If function fails, @a tableName and @a fieldName remain unchanged. 0266 @return true on success. */ 0267 KDB_EXPORT bool splitToTableAndFieldParts(const QString& string, 0268 QString *tableName, QString *fieldName, 0269 SplitToTableAndFieldPartsOptions option = FailIfNoTableOrFieldName); 0270 0271 /*! @return true if @a type supports "visibleDecimalPlaces" property. */ 0272 KDB_EXPORT bool supportsVisibleDecimalPlacesProperty(KDbField::Type type); 0273 0274 /*! @return string constructed by converting @a value. 0275 * If @a decimalPlaces is < 0, all meaningful fractional digits are returned (up to 10). 0276 * If @a automatically is 0, just integer part is returned. 0277 * If @a automatically is > 0, fractional part should take exactly 0278 N digits: if the fractional part is shorter than N, additional zeros are appended. 0279 Examples: 0280 * numberToString(12.345, 6) == "12.345000" 0281 * numberToString(12.345, 0) == "12" 0282 * numberToString(12.345, -1) == "12.345" 0283 * numberToString(12.0, -1) == "12" 0284 * numberToString(0.0, -1) == "0" 0285 0286 @note No rounding is performed 0287 @note No thousands group separator is used. Decimal symbol is '.'. 0288 0289 @see KDb::numberToLocaleString() KDbField::visibleDecimalPlaces() */ 0290 KDB_EXPORT QString numberToString(double value, int decimalPlaces); 0291 0292 /** 0293 * @brief Returns number converted to string using default locale 0294 * 0295 * This method is similar to KDb::numberToString() but the string is formatted using QLocale::toString(). 0296 * 0297 * @see KDb::numberToString() KDbField::visibleDecimalPlaces() 0298 */ 0299 KDB_EXPORT QString numberToLocaleString(double value, int decimalPlaces); 0300 0301 /** 0302 * @overload 0303 * 0304 * Returns number converted to string using specified locale. 0305 */ 0306 KDB_EXPORT QString numberToLocaleString(double value, int decimalPlaces, const QLocale &locale); 0307 0308 //! @return true if @a propertyName is a builtin field property. 0309 KDB_EXPORT bool isBuiltinTableFieldProperty(const QByteArray& propertyName); 0310 0311 //! @return true if @a propertyName is an extended field property. 0312 KDB_EXPORT bool isExtendedTableFieldProperty(const QByteArray& propertyName); 0313 0314 //! @return true if @a propertyName is belongs to lookup field's schema. 0315 KDB_EXPORT bool isLookupFieldSchemaProperty(const QByteArray& propertyName); 0316 0317 /*! @return type of field for integer value @a type. 0318 If @a type cannot be casted to KDbField::Type or is not normal type, 0319 i.e. @a type > KDbField::LastType (e.g. KDbField::Null), KDbField::InvalidType is returned. 0320 This can be used when type information is deserialized from a string or QVariant. 0321 @see KDbField::typesCount() KDbField::specialTypesCount() */ 0322 KDB_EXPORT KDbField::Type intToFieldType(int type); 0323 0324 /*! @return type group of field for integer value @a typeGroup. 0325 If @a typeGroup cannot be casted to KDbField::TypeGroup, KDbField::InvalidGroup is returned. 0326 This can be used when type information is deserialized from a string or QVariant. 0327 @see KDbField::typeGroupsCount() */ 0328 KDB_EXPORT KDbField::TypeGroup intToFieldTypeGroup(int typeGroup); 0329 0330 /*! Gets property values for the lookup schema @a lookup. 0331 @a values is not cleared before filling. This function is used e.g. for altering table design. 0332 Nothing is performed if @a values is @c nullptr. 0333 If @a lookup is @c nullptr, all returned values are null. 0334 */ 0335 KDB_EXPORT void getProperties(const KDbLookupFieldSchema *lookup, QMap<QByteArray, QVariant> *values); 0336 0337 /*! Gets property values for @a field. 0338 Properties from extended schema are included. @a values is cleared before filling. 0339 The same number of properties in the same order is returned. 0340 This function is used e.g. for altering table design. 0341 Nothing is performed if @a values is @c nullptr. 0342 */ 0343 KDB_EXPORT void getFieldProperties(const KDbField &field, QMap<QByteArray, QVariant> *values); 0344 0345 /*! Sets property values for @a field. @return true if all the values are valid and allowed. 0346 On failure contents of @a field is undefined. 0347 Properties from extended schema are also supported. 0348 This function is used e.g. by KDbAlterTableHandler when property information comes in form of text. 0349 If @a field is @c nullptr nothing is performed and @c false is returned. 0350 */ 0351 KDB_EXPORT bool setFieldProperties(KDbField *field, const QMap<QByteArray, QVariant>& values); 0352 0353 /*! Sets value of a single property for @a field. @return true if the property has been found and 0354 the value is valid for this property. On failure contents of @a field is not modified. 0355 Properties from extended schema are also supported as well as custom properties 0356 (using KDbField::setCustomProperty()). 0357 0358 This function is used e.g. by KDbAlterTableHandler when property information comes in form of text. 0359 If @a field is @c nullptr nothing is performed and @c false is returned. 0360 */ 0361 KDB_EXPORT bool setFieldProperty(KDbField *field, const QByteArray &propertyName, 0362 const QVariant &value); 0363 0364 /*! @return property value loaded from a DOM @a node, written in a QtDesigner-like 0365 notation: <number>int</number> or <bool>bool</bool>, etc. Supported types are 0366 "string", "cstring", "bool", "number". For invalid values null QVariant is returned. 0367 Validity of the returned value can be checked using the @a ok parameter and QVariant::type(). */ 0368 KDB_EXPORT QVariant loadPropertyValueFromDom(const QDomNode& node, bool *ok); 0369 0370 /*! Convenience version of loadPropertyValueFromDom(). @return int value. */ 0371 KDB_EXPORT int loadIntPropertyValueFromDom(const QDomNode& node, bool* ok); 0372 0373 /*! Convenience version of loadPropertyValueFromDom(). @return QString value. */ 0374 KDB_EXPORT QString loadStringPropertyValueFromDom(const QDomNode& node, bool* ok); 0375 0376 /*! Creates a new DOM element named @a elementName with numeric value @a value in @a doc document 0377 within parent element @a parentEl. The value will be enclosed in "number" element and 0378 "elementName" element. 0379 Example: saveNumberElementToDom(doc, parentEl, "height", 15) creates: 0380 @code 0381 <height><number>15</number></height> 0382 @endcode 0383 @return the reference to element created with tag elementName. 0384 Null element is returned if @a doc or @a parentEl is @c nullptr or if @a elementName is empty. 0385 */ 0386 KDB_EXPORT QDomElement saveNumberElementToDom(QDomDocument *doc, QDomElement *parentEl, 0387 const QString& elementName, int value); 0388 0389 /*! Creates a new DOM element named @a elementName with boolean value @a value in @a doc document 0390 within parent element @a parentEl. 0391 This method is like saveNumberElementToDom() but creates "bool" tags. True/false values will be 0392 saved as "true"/"false" strings. 0393 Example: saveBooleanElementToDom(doc, parentEl, "visible", true) creates: 0394 @code 0395 <visible><bool>true</bool></visible> 0396 @endcode 0397 @return the reference to element created with tag elementName. 0398 Null element is returned if @a doc or @a parentEl is @c nullptr or if @a elementName is empty. 0399 */ 0400 KDB_EXPORT QDomElement saveBooleanElementToDom(QDomDocument *doc, QDomElement *parentEl, 0401 const QString& elementName, bool value); 0402 0403 //! @return equivalent of empty (default) value that can be set for a database field of type @a type 0404 /*! In particular returns: 0405 - empty string for text types, 0406 - 0 for integer and floating-point types, 0407 - false for boolean types, 0408 - a null byte array for BLOB type, 0409 - current date, time, date+time is returned (measured at client side) for date, time and 0410 date/time types respectively, 0411 - a null QVariant for unsupported values such as KDbField::InvalidType. */ 0412 KDB_EXPORT QVariant emptyValueForFieldType(KDbField::Type type); 0413 0414 //! @return a value that can be set for a database field of type @a type having "notEmpty" property set. 0415 /*! It works in a similar way as @ref QVariant KDb::emptyValueForFieldType(KDbField::Type type) 0416 with the following differences: 0417 - " " string (a single space) is returned for Text and LongText types 0418 - a byte array with saved "filenew" PNG image (icon) for BLOB type 0419 Returns null QVariant for unsupported values like KDbField::InvalidType. */ 0420 KDB_EXPORT QVariant notEmptyValueForFieldType(KDbField::Type type); 0421 0422 /*! @return true if the @a word is an reserved KDBSQL keyword 0423 See generated/sqlkeywords.cpp. 0424 @todo add function returning list of keywords. */ 0425 KDB_EXPORT bool isKDbSqlKeyword(const QByteArray& word); 0426 0427 //! @return @a string string with applied KDBSQL identifier escaping 0428 /*! This escaping can be used for field, table, database names, etc. 0429 Use it for user-visible backend-independent statements. 0430 @see KDb::escapeIdentifierAndAddQuotes() */ 0431 KDB_EXPORT QString escapeIdentifier(const QString& string); 0432 0433 //! @overload QString escapeIdentifier(const QString&) 0434 KDB_EXPORT QByteArray escapeIdentifier(const QByteArray& string); 0435 0436 //! @return @a string string with applied KDBSQL identifier escaping and enclosed in " quotes 0437 /*! This escaping can be used for field, table, database names, etc. 0438 Use it for user-visible backend-independent statements. 0439 @see KDb::escapeIdentifier */ 0440 KDB_EXPORT QString escapeIdentifierAndAddQuotes(const QString& string); 0441 0442 //! @overload QString escapeIdentifierAndAddQuotes(const QString&) 0443 KDB_EXPORT QByteArray escapeIdentifierAndAddQuotes(const QByteArray& string); 0444 0445 /*! @return escaped string @a string for the KDBSQL dialect, 0446 i.e. doubles single quotes ("'") and inserts the string into single quotes. 0447 Quotes "'" are prepended and appended. 0448 Also escapes \\n, \\r, \\t, \\\\, \\0. 0449 Use it for user-visible backend-independent statements. 0450 @see unescapeString() */ 0451 KDB_EXPORT QString escapeString(const QString& string); 0452 0453 /** 0454 * @brief Returns escaped string @a string 0455 * 0456 * If @a drv driver is present, it is used to perform escaping, otherwise escapeString() is used 0457 * so the KDBSQL dialect-escaping is performed. 0458 * 0459 * @since 3.1.0 0460 */ 0461 KDB_EXPORT KDbEscapedString escapeString(KDbDriver *drv, const QString& string); 0462 0463 /** 0464 * @brief Returns escaped string @a string 0465 * 0466 * If @a conn is present, its driver is used to perform escaping, otherwise escapeString() is used 0467 * so the KDBSQL dialect-escaping is performed. 0468 * 0469 * @since 3.1.0 0470 */ 0471 KDB_EXPORT KDbEscapedString escapeString(KDbConnection *conn, const QString& string); 0472 0473 //! Unescapes characters in string @a string for the KDBSQL dialect. 0474 /** The operation depends on @a quote character, which can be be ' or ". 0475 * @a string is assumed to be properly constructed. This is assured by the lexer's grammar. 0476 * Used by lexer to recognize the CHARACTER_STRING_LITERAL token. 0477 * @return unescaped string and sets value pointed by @a errorPosition (if any) to -1 on success; 0478 * and to index of problematic character on failure. 0479 * The function fails when unsupported @a quote character is passed or for unsupported sequences. 0480 * 0481 * Example sequences for ' character quote: 0482 * - \' -> ' (escaping) 0483 * - \" -> " (escaping) 0484 * - '' -> ' (repeated quote escapes too) 0485 * - "" -> "" (repeated but this is not the quote) 0486 * - ' -> (disallowed, escaping needed) 0487 * - " -> " 0488 * Example sequences for " character quote: 0489 * - \' -> ' (escaping) 0490 * - \" -> " (escaping) 0491 * - " -> " (disallowed, escaping needed) 0492 * - "" -> " (repeated quote escapes too) 0493 * - '' -> '' (repeated but this is not the quote) 0494 * - ' -> ' 0495 * 0496 * Following sequences are always unescaped (selection based on a mix of MySQL and C/JavaScript): 0497 * - \0 -> NULL (QChar()) 0498 * - \b -> backspace 0x8 0499 * - \f -> form feed 0xc 0500 * - \n -> new line 0xa 0501 * - \r -> carriage return 0xd 0502 * - \t -> horizontal tab 0x9 0503 * - \v -> vertical tab 0xb 0504 * - \\ -> backslash 0505 * - \? -> ? (useful when '?' placeholders are used) 0506 * - \% -> (useful when '%' wildcards are used e.g. for the LIKE operator) 0507 * - \_ -> (useful when '_' pattern is used e.g. for the LIKE operator) 0508 * - \xhh -> a character for which hh (exactly 2 digits) is interpreted as an hexadecimal 0509 * number, 00 <= hh <= FF. Widely supported by programming languages. 0510 * Can be also 00 <= hh <= ff. 0511 * Example: \xA9 translates to "©". 0512 * - \uxxxx -> 16-bit unicode character, exactly 4 digits, each x is a hexadecimal digit, 0513 * case insensitive; known from JavaScript, Java, C/C++. 0000 <= xxxxxx <= FFFF 0514 * Example: \u2665 translates to "♥". 0515 * - \u{xxxxxx} -> 24-bit unicode "code point" character, each x is a hexadecimal digit, 0516 * case insensitive; known from JavaScript (ECMAScript 6). 0 <= xxxxxx <= 10FFFF 0517 * Example: \u{1D306} translates to "𝌆" 0518 * 0519 * @note Characters without special meaning can be escaped, but then the "\" character 0520 * is skipped, e.g. "\a" == "a". 0521 * @note Trailing "\" character in @a string is ignored. 0522 * @note \nnn octal notation is not supported, it may be confusing and conflicting 0523 * when combined with other characters (\0012 is not the same as \012). 0524 * The industry is moving away from it and EcmaScript 5 deprecates it. 0525 * 0526 * See also: 0527 * - https://dev.mysql.com/doc/refman/5.7/en/string-literals.html 0528 * - https://en.wikipedia.org/wiki/Escape_sequences_in_C#Table_of_escape_sequences 0529 * - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Using_special_characters_in_strings 0530 * - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals 0531 */ 0532 KDB_EXPORT QString unescapeString(const QString& string, char quote, int *errorPosition = nullptr); 0533 0534 //! Escaping types for BLOBS. Used in escapeBLOB(). 0535 enum class BLOBEscapingType { 0536 XHex = 1, //!< Escaping like X'1FAD', used by sqlite (hex numbers) 0537 ZeroXHex, //!< Escaping like 0x1FAD, used by mysql (hex numbers) 0538 Hex, //!< Escaping like 1FAD without quotes or prefixes 0539 Octal, //!< Escaping like 'zk\\000$x', used by PostgreSQL 0540 //!< (only non-printable characters are escaped using octal numbers); 0541 //!< see https://www.postgresql.org/docs/9.5/interactive/datatype-binary.html 0542 ByteaHex //!< "bytea hex" escaping, e.g. E'\xDEADBEEF'::bytea used by PostgreSQL 0543 //!< (only non-printable characters are escaped using octal numbers); 0544 //!< see https://www.postgresql.org/docs/9.5/interactive/datatype-binary.html 0545 }; 0546 0547 /*! @return a string containing escaped, printable representation of @a array. 0548 Escaping is controlled by @a type. For empty array, QString() is returned, 0549 so if you want to use this function in an SQL statement, empty arrays should be 0550 detected and "NULL" string should be put instead. 0551 This is helper, used in KDbDriver::escapeBLOB() and KDb::variantToString(). */ 0552 KDB_EXPORT QString escapeBLOB(const QByteArray& array, BLOBEscapingType type); 0553 0554 /*! @return byte array converted from @a data of length @a length. 0555 If @a length is negative, the data is assumed to point to a null-terminated string 0556 and its length is determined dynamically. 0557 @a data is escaped in format used by PostgreSQL's bytea datatype 0558 described at https://www.postgresql.org/docs/8.1/interactive/datatype-binary.html 0559 This function is used by PostgreSQL KDb and migration drivers. */ 0560 KDB_EXPORT QByteArray pgsqlByteaToByteArray(const char* data, int length = -1); 0561 0562 /*! @return byte array converted from @a data of length @a length. 0563 If @a length is negative, the data is assumed to point to a null-terminated string 0564 and its length is determined dynamically. 0565 @a data is escaped in format X'*', where * is one or more hexadecimal digits. 0566 Both A-F and a-f letters are supported. Even and odd number of digits are supported. 0567 If @a ok is not 0, *ok is set to result of the conversion. 0568 See BLOBEscapingType::XHex. */ 0569 KDB_EXPORT QByteArray xHexToByteArray(const char* data, int length = -1, bool *ok = nullptr); 0570 0571 /*! @return byte array converted from @a data of length @a length. 0572 If @a length is negative, the data is assumed to point to a null-terminated string 0573 and its length is determined dynamically. 0574 @a data is escaped in format 0x*, where * is one or more hexadecimal digits. 0575 Both A-F and a-f letters are supported. Even and odd number of digits are supported. 0576 If @a ok is not 0, *ok is set to result of the conversion. 0577 See BLOBEscapingType::ZeroXHex. */ 0578 KDB_EXPORT QByteArray zeroXHexToByteArray(const char* data, int length = -1, bool *ok = nullptr); 0579 0580 /*! @return int list converted from string list. 0581 If @a ok is not 0, *ok is set to result of the conversion. */ 0582 KDB_EXPORT QList<int> stringListToIntList(const QStringList &list, bool *ok = nullptr); 0583 0584 /*! @return string converted from list @a list. 0585 Separators are ',' characters, "," and "\\" are escaped. 0586 @see KDb::deserializeList() */ 0587 KDB_EXPORT QString serializeList(const QStringList &list); 0588 0589 /*! @return string list converted from @a data which was built using serializeList(). 0590 Separators are ',' characters, escaping is assumed as "\\,". */ 0591 KDB_EXPORT QStringList deserializeList(const QString &data); 0592 0593 /*! @return int list converted from @a data which was built using serializeList(). 0594 Separators are ',' characters, escaping is assumed as "\\,". 0595 If @a ok is not 0, *ok is set to result of the conversion. 0596 @see KDb::stringListToIntList() */ 0597 KDB_EXPORT QList<int> deserializeIntList(const QString &data, bool *ok); 0598 0599 /*! @return string value serialized from a variant value @a v. 0600 This functions works like QVariant::toString() except the case when @a v is of type: 0601 - QByteArray - in this case KDb::escapeBLOB(v.toByteArray(), KDb::BLOBEscapeHex) is used. 0602 - QStringList - in this case KDb::serializeList(v.toStringList()) is used. 0603 0604 This function is needed for handling values of random type, for example "defaultValue" 0605 property of table fields can contain value of any type. 0606 Note: the returned string is an unescaped string. */ 0607 KDB_EXPORT QString variantToString(const QVariant& v); 0608 0609 /*! @return variant value of type @a type for a string @a s that was previously serialized using 0610 @ref variantToString( const QVariant& v ) function. 0611 @a ok is set to the result of the operation. With exception for types mentioned in documentation 0612 of variantToString(), QVariant::convert() is used for conversion. */ 0613 KDB_EXPORT QVariant stringToVariant(const QString& s, QVariant::Type type, bool* ok); 0614 0615 /*! @return true if setting default value for @a field field is allowed. Fields with unique 0616 (and thus primary key) flags set do not accept default values. */ 0617 KDB_EXPORT bool isDefaultValueAllowed(const KDbField &field); 0618 0619 //! Provides limits for values of type @a type 0620 /*! The result is put into integers pointed by @a minValue and @a maxValue. 0621 The limits are machine-independent,. what is useful for format and protocol compatibility. 0622 Supported types are Byte, ShortInteger, Integer and BigInteger. 0623 The value of @a signedness controls the values; they can be limited to unsigned or not. 0624 Results for BigInteger or non-integer types are the same as for Integer due to limitation 0625 of int type. Signed integers are assumed. @a minValue and @a maxValue must not be 0. */ 0626 KDB_EXPORT void getLimitsForFieldType(KDbField::Type type, qlonglong *minValue, qlonglong *maxValue, 0627 KDb::Signedness signedness = KDb::Signed); 0628 0629 /*! @return type that's maximum of two integer types @a t1 and @a t2, e.g. Integer for (Byte, Integer). 0630 If one of the types is not of the integer group, KDbField::InvalidType is returned. 0631 Returned type may not fit to the result of evaluated expression that involves the arguments. 0632 For example, 100 is within Byte type, maximumForIntegerFieldTypes(Byte, Byte) is Byte but result 0633 of 100 * 100 exceeds the range of Byte. */ 0634 KDB_EXPORT KDbField::Type maximumForIntegerFieldTypes(KDbField::Type t1, KDbField::Type t2); 0635 0636 //! @return QVariant value converted from a @a data string 0637 /*! Conversion is based on the information about type @a type. 0638 @a type has to be an element from KDbField::Type, not greater than KDbField::LastType. 0639 For unsupported type this function fails. @a length value controls number of characters 0640 used in the conversion. It is optional value for all cases but for the BLOB type because 0641 for it @a data is not null-terminated so the length cannot be measured. 0642 The value of @a signedness controls the conversion in case of integer types; numbers can be 0643 limited to unsigned or not. 0644 If @a ok is not 0 *ok is set to false on failure and to true on success. On failure a null 0645 QVariant is returned. The function fails if @a data is 0. 0646 For rules of conversion to the boolean type see the documentation of @ref QVariant::toBool(), 0647 QVariant::toDate() for date type, QVariant::toDateTime() for date+time type, 0648 QVariant::toTime() for time type. */ 0649 KDB_EXPORT QVariant cstringToVariant(const char* data, KDbField::Type type, bool *ok, int length = -1, 0650 KDb::Signedness signedness = KDb::Signed); 0651 0652 /*! @return default file-based driver MIME type 0653 (typically something like "application/x-kexiproject-sqlite") */ 0654 KDB_EXPORT QString defaultFileBasedDriverMimeType(); 0655 0656 /*! @return default file-based driver ID (currently, "org.kde.kdb.sqlite"). */ 0657 KDB_EXPORT QString defaultFileBasedDriverId(); 0658 0659 /*! Escapes and converts value @a v (for type @a ftype) 0660 to string representation required by KDBSQL commands. 0661 For Date/Time type KDb::dateTimeToSql() is used. 0662 For BLOB type KDb::escapeBlob() with BLOBEscapingType::ZeroXHex conversion type is used. */ 0663 KDB_EXPORT KDbEscapedString valueToSql(KDbField::Type ftype, const QVariant& v); 0664 0665 /** 0666 * Converts date/time value to its string representation in ISO 8601 DateTime format - with "T" delimiter 0667 * 0668 * @note This method is deprecated since 3.1.1, use KDb::dateTimeToIsoString() which has identical 0669 * effect. The ISO format is no longer used for creating KDBSQL statements. 0670 * Prior to this version it was used to generate date/time constants in 0671 * KDb::valueToSql(KDbField::Type ftype, const QVariant& v) for KDbField::DateTime type. 0672 * KDb::dateTimeToIsoString() is still used as default implementation for drivers 0673 * in KDbDriver::dateTimeToSql(). 0674 * 0675 * KDb 3.1.0 improved type safety for KDBSQL so Text type are no longer compatible with 0676 * Date/Time types. By implementing wish https://bugs.kde.org/393094 format of date/time constants 0677 * for KDBSQL has been strictly defined in a backend-independent way. 0678 * See https://community.kde.org/Kexi/Plugins/Queries/SQL_Constants for details. 0679 */ 0680 KDB_DEPRECATED_EXPORT KDbEscapedString dateTimeToSql(const QDateTime& v); 0681 0682 /** 0683 * Converts date value to its string representation in ISO 8601 DateTime format 0684 * 0685 * The string is enclosed with single quotes "'". It is compatible with SQLite format for the 0686 * date type. It is used as default implementation for drivers in KDbDriver::dateToSql(). 0687 * 0688 * If the @a v value is convertible to KDbDate then KDbDate::toString() is used to obtain 0689 * the result. Otherwise the value is converted to QDate and QDate::toString(Qt::ISODate) is 0690 * used to obtain the result. 0691 * 0692 * "<INVALID_DATE>" string is returned for invalid (also null) date values. 0693 * 0694 * For specification of the ISO format see https://www.w3.org/TR/NOTE-datetime. 0695 * 0696 * Example value: "'1994-11-05'". 0697 * 0698 * @since 3.2.0 0699 */ 0700 KDB_EXPORT KDbEscapedString dateToIsoString(const QVariant& v); 0701 0702 /** 0703 * Converts time value to its string representation in ISO 8601 Time format 0704 * 0705 * The string is enclosed with single quotes "'". It is compatible with SQLite format for the 0706 * time type. It is used as default implementation for drivers in KDbDriver::timeToSql(). 0707 * 0708 * If the @a v value is convertible to KDbTime then KDbTime::toString() is used to obtain the result. 0709 * Otherwise the value is converted to QTime and QTime::toString() is used to obtain the result. 0710 * If the time's milliseconds value is zero, it is not included. 0711 * 0712 * "<INVALID_TIME>" string is returned for invalid (also null) time values. 0713 * 0714 * For specification of the ISO format see https://www.w3.org/TR/NOTE-datetime. 0715 * 0716 * Example values: "'13:15:30.123'", "'13:15:30'". 0717 * 0718 * @since 3.2.0 0719 */ 0720 KDB_EXPORT KDbEscapedString timeToIsoString(const QVariant& v); 0721 0722 /** 0723 * Converts date/time value to its string representation in ISO 8601 DateTime format - with "T" delimiter 0724 * 0725 * The string is enclosed with single quotes "'". It is compatible with SQLite format for the 0726 * date/time type. It is used as default implementation for drivers in KDbDriver::dateTimeToSql(). 0727 * 0728 * If the @a v value is convertible to KDbDateTime then KDbDateTime::toString() is used to obtain 0729 * the result. Otherwise the value is converted to QDateTime and QDateTime::toString() is 0730 * used as well as QTime::toString() to obtain the result. 0731 * If the time's milliseconds value is zero, it is not included. 0732 * 0733 * "<INVALID_DATETIME>" string is returned for invalid (also null) time values. 0734 * 0735 * For specification of the ISO format see https://www.w3.org/TR/NOTE-datetime. 0736 * 0737 * Example value: "'1994-11-05T13:15:30'", not "'1994-11-05 13:15:30'". 0738 * 0739 * @since 3.2.0 0740 */ 0741 KDB_EXPORT KDbEscapedString dateTimeToIsoString(const QVariant& v); 0742 0743 /** 0744 * Converts date value to its string representation required by KDBSQL commands 0745 * 0746 * The value can be of type QDate or KDbDate. If the value is not one of these types or is invalid 0747 * QDate or is a null KDbDate then "<INVALID_DATE>" is returned. If the value is of type KDbDate 0748 * that is not null then even if some components of the date are invalid, properly formatted string 0749 * is returned. 0750 * 0751 * Example values: "#1994-11-05", "#1994-9-05#". 0752 * 0753 * See https://community.kde.org/Kexi/Plugins/Queries/SQL_Constants for details. 0754 * 0755 * @since 3.2.0 0756 */ 0757 KDB_EXPORT KDbEscapedString dateToSql(const QVariant& v); 0758 0759 /** 0760 * Converts time value to its string representation required by KDBSQL commands 0761 * 0762 * The value can be of type QTime or KDbTime. If the value is not one of these types or is invalid 0763 * QTime or is a null KDbTime then "<INVALID_TIME>" is returned. If the value is of type KDbTime 0764 * that is not null then even if some components of the time are invalid, properly formatted string 0765 * is returned. If the time's milliseconds value is zero, it is not included. 0766 * 0767 * See https://community.kde.org/Kexi/Plugins/Queries/SQL_Constants for details. 0768 * 0769 * Example values: "#13:15#", "#13:9:30#", "#13:15:30.921#, "#7:20 AM#". 0770 * 0771 * @since 3.2.0 0772 */ 0773 KDB_EXPORT KDbEscapedString timeToSql(const QVariant& v); 0774 0775 /** 0776 * Converts date/time value to its string representation required by KDBSQL commands 0777 * 0778 * The value can be of type QDateTime or KDbDateTime. If the value is not one of these types or 0779 * is invalid QDateTime or is a null KDbDateTime then "<INVALID_DATETIME>" is returned. 0780 * If the value is of type KDbDateTime that is not null then even if some components of the 0781 * date/time are invalid, properly formatted string is returned. 0782 * If the time's milliseconds value is zero, it is not included. 0783 * 0784 * See https://community.kde.org/Kexi/Plugins/Queries/SQL_Constants for details. 0785 * 0786 * Example values: "#1994-11-05 13:15#", "#1994-11-05 13:9:30#", "#1994-9-05 13:15:30.921#". 0787 * 0788 * @since 3.2.0 0789 */ 0790 KDB_EXPORT KDbEscapedString dateTimeToSql(const QVariant& v); 0791 0792 #ifdef KDB_DEBUG_GUI 0793 //! A prototype of handler for GUI debugger 0794 typedef void(*DebugGUIHandler)(const QString&); 0795 0796 //! Sets handler for GUI debugger 0797 KDB_EXPORT void setDebugGUIHandler(DebugGUIHandler handler); 0798 0799 //! Outputs string @a text to the GUI debugger 0800 KDB_EXPORT void debugGUI(const QString& text); 0801 0802 //! A prototype of handler for GUI debugger (specialized for the Alter Table feature) 0803 typedef void(*AlterTableActionDebugGUIHandler)(const QString&, int); 0804 0805 //! Sets handler for GUI debugger (specialized for the Alter Table feature) 0806 KDB_EXPORT void setAlterTableActionDebugHandler(AlterTableActionDebugGUIHandler handler); 0807 0808 //! Outputs string @a text to the GUI debugger (specialized for the Alter Table feature); 0809 //! @a nestingLevel can be provided for nested outputs. 0810 KDB_EXPORT void alterTableActionDebugGUI(const QString& text, int nestingLevel = 0); 0811 #endif 0812 0813 //! @return @a string if it is not empty, else returns @a stringIfEmpty. 0814 /*! This function is an optimization in cases when @a string is a result of expensive 0815 functioncall because any evaluation will be performed once, not twice. Another advantage 0816 is simpified code through the functional approach. 0817 The function expects bool isEmpty() method to be present in type T, so T can typically 0818 be QString or QByteArray. */ 0819 template<typename T> 0820 T iifNotEmpty(const T &string, const T &stringIfEmpty) 0821 { 0822 return string.isEmpty() ? stringIfEmpty : string; 0823 } 0824 0825 //! @overload iifNotEmpty(const T &string, const T &stringIfEmpty) 0826 template<typename T> 0827 T iifNotEmpty(const QByteArray &string, const T &stringIfEmpty) 0828 { 0829 return iifNotEmpty(QLatin1String(string), stringIfEmpty); 0830 } 0831 0832 //! @overload iifNotEmpty(const T &string, const T &stringIfEmpty) 0833 template<typename T> 0834 T iifNotEmpty(const T &string, const QByteArray &stringIfEmpty) 0835 { 0836 return iifNotEmpty(string, QLatin1String(stringIfEmpty)); 0837 } 0838 0839 //! @return @a value if @a ok is true, else returns default value T(). 0840 template<typename T> 0841 T iif(bool ok, const T &value) 0842 { 0843 if (ok) { 0844 return value; 0845 } 0846 return T(); 0847 } 0848 0849 /*! @return a list of paths that KDb will search when dynamically loading libraries (plugins) 0850 This is basicaly list of directories returned QCoreApplication::libraryPaths() that have readable 0851 subdirectory "kdb". 0852 @see QCoreApplication::libraryPaths() */ 0853 KDB_EXPORT QStringList libraryPaths(); 0854 0855 /*! @return new temporary name suitable for creating new table. 0856 The name has mask tmp__{baseName}{rand} where baseName is passed as argument and {rand} 0857 is a 10 digits long hexadecimal number. @a baseName can be empty. It is adviced to use 0858 the returned name as quickly as possible for creating new physical table. 0859 It is not 100% guaranteed that table with this name will not exist at an attempt of creation 0860 but it is very unlikely. The function checks for existence of a table with temporary name 0861 for connection @a conn. Empty string is returned if @a conn is @c nullptr or is not open 0862 or if checking for existence of table with temporary name failed. 0863 */ 0864 KDB_EXPORT QString temporaryTableName(KDbConnection *conn, const QString &baseName); 0865 0866 /*! @return absolute path to "sqlite3" program. 0867 Empty string is returned if the program was not found. */ 0868 KDB_EXPORT QString sqlite3ProgramPath(); 0869 0870 /*! Imports file in SQL format from @a inputFileName into @a outputFileName. 0871 Works for any SQLite 3 dump file. Requires access to executing the "sqlite3" command. 0872 File named @a outputFileName will be silently overwritten with a new SQLite 3 database file. 0873 @return true on success. */ 0874 KDB_EXPORT bool importSqliteFile(const QString &inputFileName, const QString &outputFileName); 0875 0876 /*! @return @c true if @a s is a valid identifier, i.e. starts with a letter or '_' character 0877 and contains only letters, numbers and '_' character. */ 0878 KDB_EXPORT bool isIdentifier(const QString& s); 0879 0880 //! @overload isIdentifier(const QString& s) 0881 //! @since 3.1 0882 KDB_EXPORT bool isIdentifier(const QByteArray& s); 0883 0884 /*! @return valid identifier based on @a s. 0885 Non-alphanumeric characters (or spaces) are replaced with '_'. 0886 If a number is at the beginning, '_' is added at start. 0887 Empty strings are not changed. Case remains unchanged. */ 0888 KDB_EXPORT QString stringToIdentifier(const QString &s); 0889 0890 /*! @return useful message "Value of "valueName" field must be an identifier. 0891 "v" is not a valid identifier.". It is also used by KDbIdentifierValidator. */ 0892 KDB_EXPORT QString identifierExpectedMessage(const QString &valueName, 0893 const QVariant& v); 0894 0895 } // namespace KDb 0896 0897 #endif