1 #ifndef QUERYEXECUTOR_H 2 #define QUERYEXECUTOR_H 3 4 #include "db/db.h" 5 #include "parser/token.h" 6 #include "selectresolver.h" 7 #include "coreSQLiteStudio_global.h" 8 #include "common/bistrhash.h" 9 #include "datatype.h" 10 #include <QObject> 11 #include <QHash> 12 #include <QMutex> 13 #include <QRunnable> 14 15 /** @file */ 16 17 class Parser; 18 class SqliteQuery; 19 class QueryExecutorStep; 20 class DbPlugin; 21 class ChainExecutor; 22 23 /** 24 * @brief Advanced SQL query execution handler. 25 * 26 * QueryExecutor is an advanced SQL query execution handler, which lets you execute any query (with subqueries, joins, etc) 27 * and is capable of providing meta information about returned data, such as ROWID for all rows and columns, 28 * data sources (database, table and column) for every column, rows affected, total rows number for query, etc. 29 * All of this available for both SQLite versions: 2 and 3. 30 * 31 * Queries are executed asynchronously. To handle result a lambda function can be used (or any function pointer), 32 * or manual tracking of asynchronous execution ID and signals from this class. Function pointers and lambdas 33 * are recommended way to handle results. 34 * 35 * It also allows you to: 36 * <ul> 37 * <li>programatically define sorting on desired column.</li> 38 * <li>define result rows paging (page size and queried page)</li> 39 * <li>refer other databases by their symbolic name and they will be attached and detached on the fly</li> 40 * <li>define maximum cell data size (in bytes), so you won't read too much data at once</li> 41 * </ul> 42 * 43 * Total number of result rows is counted by a separate call to the database (using <tt>SELECT count(*) ...</tt>) 44 * and its result is provided later, which is signalized by signal resultsCountingFinished(). Row counting can 45 * be disabled with setSkipRowCounting(). See "Counting query" section below for details. 46 * 47 * The simplest use case would be: 48 * @code 49 * Db* db = getDb(); 50 * QueryExecutor *executor = new QueryExecutor(db, "SELECT * FROM table"); 51 * executor->exec([=](SqlQueryPtr results) 52 * { 53 * if (results->isError()) 54 * { 55 * qCritical() << "Error " << results->getErrorCode() << ": " << results->getErrorText() << "\n"; 56 * return; 57 * } 58 * qDebug() << results->valueList(); 59 * } 60 * @endcode 61 * 62 * Unless you want some of QueryExecutor's special features, it's recommended to use 63 * Db::exec() and Db::asyncExec(), because while QueryExecutor is powerful, it also does lots of thing underneeth 64 * you may not need at all. 65 * 66 * \note This class is used in SQL editor window (SqlQueryModel) to execute queries entered by the user. 67 * 68 * \section smart_simple_sec "smart mode" vs "simple mode" 69 * 70 * Documentation of this class references many times to "smart mode" and "simple mode" expressions. 71 * The "smart mode" means that the QueryExecutor was able to parse the input query, modify it for its needs 72 * (add some meta-information columns, etc) and executed modified query successfully. 73 * When the "smart mode" fails (which should be rare), the "simple mode" steps in as a fallback strategy. 74 * The "simple mode" doesn't modify input query, just directly executes in on the database 75 * and then QueryExecutor tries to extract as much meta-information from "simple mode" as it can (which is not much). 76 * 77 * The "simple mode" also doesn't apply any paging (see QueryExecutor::setPage()), nor data size limits 78 * (see QueryExecutor::setDataLengthLimit()). 79 * 80 * The meta-information is all the data from the query that is not the essential data requested in the input query. 81 * That is full description on all requested columns (their source tables, databases, data types), 82 * ROWID value for all returned data rows, and more... 83 * 84 * \section counting_query Counting query 85 * 86 * QueryExecutor can split results into pages. In such cases, results are not all read, instead they are limited 87 * at SQL level with LIMIT and OFFSET keywords. Because of that it is impossible to tell how many rows 88 * would actualy be returned if there were no limit keywords. 89 * 90 * To deal with it the QueryExecutor makes extra query execution, which happens asynchronously to the main query 91 * execution. This extra execution starts just after the main query execution has finished (with success). 92 * This extra query (aka "Counting query") is made of original query wrapped with: 93 * @code 94 * SELECT count(*) FROM (original_query) 95 * @endcode 96 * This way QueryExecutor know the true number of rows to be retuend by the query. 97 * 98 * Since this extra query execution takes some extra time, this is performed asynchronously and only after 99 * successful execution of the main query. If you need to work with QueryExecutor::getTotalRowsReturned(), 100 * wait for the QueryExecutor::resultsCountingFinished() signal first. 101 * 102 * Row counting query execution can be disabled with QueryExecutor::setSkipRowCounting(), 103 */ 104 class API_EXPORT QueryExecutor : public QObject, public QRunnable 105 { 106 Q_OBJECT 107 108 public: 109 /** 110 * @brief General reasons for which results data cannot be edited. 111 */ 112 enum class EditionForbiddenReason 113 { 114 NOT_A_SELECT, /**< Executed query was not a SELECT. Only SELECT results can be edited. */ 115 SMART_EXECUTION_FAILED /**< 116 * QueryExecutor could not perform "smart" execution, 117 * which means that it was unable to gather meta information 118 * about returned data and therefore it cannot tell what are ROWIDs 119 * or data sources for each column. Still it was able to perform 120 * simple (direct, without query modifications) execution 121 * and it returned results, so they can be presented to the user, 122 * but not edited. 123 * 124 * This happens usually when there's a but in SQLiteStudio, 125 * which caused - for example - error during query parsing by Parser, 126 * or other query syntax issues, that wasn't handled correctly 127 * by SQLiteStudio. 128 */ 129 }; 130 131 /** 132 * @brief Per-column reasons for which the data in the column cannot be edited. 133 */ 134 enum class ColumnEditionForbiddenReason 135 { 136 COMPOUND_SELECT, /**< 137 * The data cell comes from compound SELECT (UNION, EXCEPT, INTERSECT), 138 * which makes it problematic to SQLiteStudio to find out to which table 139 * does the particular row belong to. 140 * 141 * It might be resolved in future SQLiteStudio versions and this enum value 142 * would disappear then. 143 */ 144 GROUPED_RESULTS, /**< 145 * The data cell comes from SELECT with aggregated results, therefore it's 146 * hard to hard what were ROWIDs of each row in the results. 147 * 148 * It might be resolved in future SQLiteStudio versions and this enum value 149 * would disappear then. 150 */ 151 DISTINCT_RESULTS, /**< 152 * The data cell comes from SELECT DISTINCT clause, therefore extracting 153 * ROWIDs from the results is impossible, becasuse querying ROWID would 154 * make every row unique, therefore DISTINCT would not remove any rows, 155 * even the rest of the data (which matters to the user) would not be 156 * unique and should have been removed by the DISTINCT keyword. 157 * 158 * Because of that, SQLiteStudio doesn't extract ROWIDs for DISTINCT 159 * queries, so the results are accurate, but in consequence, 160 * the data cannot be edited. 161 */ 162 EXPRESSION, /**< 163 * The data cell is a result of a formula, function or other expression, 164 * which is not a direct data source, therefore it's impossible to change 165 * it's value. 166 */ 167 SYSTEM_TABLE, /**< 168 * The data cell comes from system table (sqlite_*) and those tables cannot 169 * be edited. 170 */ 171 COMM_TAB_EXPR, /**< 172 * The data cell comes from system "WITH common-table-expression" SELECT 173 * statement and those tables cannot be edited for the same reasons as 174 * in COMPOUND_SELECT case. To learn about common table expression statement, 175 * see http://sqlite.org/lang_with.html 176 */ 177 }; 178 179 /** 180 * @brief Sort order definition. 181 * 182 * QueryExecutor supports programmatic sort order definition. 183 * It supports smooth transition from/to Qt sorting direction enum 184 * and defines sorting column by its index (0-based). 185 */ 186 struct API_EXPORT Sort 187 { 188 /** 189 * @brief Sorting order. 190 */ 191 enum Order 192 { 193 ASC, /**< Ascending order */ 194 DESC, /**< Descending order */ 195 NONE /**< No sorting at all */ 196 }; 197 198 /** 199 * @brief Default constructor with no sorting defined. 200 * 201 * Constructed object uses NONE as sorting order. 202 */ 203 Sort(); 204 205 /** 206 * @brief Creates sort order with given order on given column. 207 * @param order Order to sort with. 208 * @param column 0-based column number. 209 */ 210 Sort(Order order, int column); 211 212 /** 213 * @brief Creates sort order with given order on given column. 214 * @param order Qt typed sort order (Qt::AscendingOrder, Qt::DescendingOrder). 215 * @param column 0-based column number. 216 */ 217 Sort(Qt::SortOrder order, int column); 218 219 /** 220 * @brief Gets Qt typed sort order. 221 * @return Sort order. 222 */ 223 Qt::SortOrder getQtOrder() const; 224 225 /** 226 * @brief Sorting order. 227 */ 228 Order order = NONE; 229 230 /** 231 * @brief 0-based column number to sort by. 232 */ 233 int column = -1; 234 }; 235 236 typedef QList<Sort> SortList; 237 238 /** 239 * @brief ResultColumn as represented by QueryExecutor. 240 * 241 * QueryExecutor has its own result column representation, because it provides more 242 * meta information on the column. 243 */ 244 struct API_EXPORT ResultColumn 245 { 246 /** 247 * @brief Database name that the result column comes from. 248 * 249 * It's an SQLite internal name of the database, which means it's either "main", or "temp", 250 * or symbolic name of registered database (as represented in the databases tree), 251 * or the name of any attached databases. 252 * 253 * Symbolic database name is provided when user used it in his query and SQLiteStudio attached 254 * it transparently. In that case the temporary name used for "ATTACH" statement would make no sense, 255 * because that database was detached automatically after the query execution finished. 256 * 257 * In case of databases attached manually by user, it's exactly the same string as used when executing 258 * "ATTACH" statement. 259 */ 260 QString database; 261 262 /** 263 * @brief Table name that the result column comes from. 264 */ 265 QString table; 266 267 /** 268 * @brief Table column name that the result column comes from. 269 */ 270 QString column; 271 272 /** 273 * @brief Alias defined for the result column in the query. 274 */ 275 QString alias; 276 277 /** 278 * @brief Table alias defined in the query. 279 * 280 * This is an alias defined in the query for the table that the result column comes from. 281 */ 282 QString tableAlias; 283 284 /** 285 * @brief Name of the column as presented to user. 286 * 287 * This is the name of a column as SQLite would present it to the user. 288 * If the query requested just a column from table, it will be that column name. 289 * If the query resuested two columns with the same name, then the second column will get 290 * suffix ":1", next one would get suffix ":2", and so on. 291 * For expressions the display name is direct copy of the SQL code used to define the expression. 292 * 293 * If the alias was defined in query, than it's used for the display name instead of anything else. 294 */ 295 QString displayName; 296 297 /** 298 * @brief QueryExecutor's internal alias for the column. 299 * 300 * This value has no sense outside of QueryExecutor. It's used by QueryExecutor to 301 * keep track of columns from subselects, etc. 302 */ 303 QString queryExecutorAlias; 304 305 /** 306 * @brief Set of reasons for which column editing is denied. 307 * 308 * If the set is empty, it means that the column can be edited. 309 */ 310 QSet<ColumnEditionForbiddenReason> editionForbiddenReasons; 311 312 /** 313 * @brief Flag indicating that the column is actually an expression. 314 * 315 * Column representing an expression is not just a column and it should not be ever wrapped with 316 * quoting wrapper ([], "", ``). Such a column is for example call to the SQL function. 317 * 318 * For regular columns this will be false. 319 */ 320 bool expression = false; 321 }; 322 323 /** 324 * @brief Shared pointer to ResultColumn. 325 */ 326 typedef QSharedPointer<ResultColumn> ResultColumnPtr; 327 328 /** 329 * @brief Combined row ID columns for tables in the query. 330 * 331 * Since version 3.8.2 SQLite introduced the "WITHOUT ROWID" clause. It allows tables to have no 332 * ROWID built-in. Such tables must have PRIMARY KEY defined, which does the job of the unique key 333 * for the table. 334 * 335 * This structure describes the unique key for the table, regardless if it's a regular ROWID, 336 * or if it's a PRIMARY KEY on a column, or if it's a multi-column PRIMARY KEY. 337 * 338 * You should always understand it as a set of PRIMARY KEY columns for given table. 339 * Referencing to that table using given columns will guarantee uniqueness of the row. 340 * 341 * In case of regular table (with no "WITHOUT ROWID" clause), there will be only one column 342 * defined in ResultRowIdColumn::columns and it will be named "ROWID". 343 */ 344 struct API_EXPORT ResultRowIdColumn 345 { 346 /** 347 * @brief Database name that the table with this row ID is in. 348 * 349 * It's the actual database name as SQLite sees it. That means it is a "main", or any attach name. 350 */ 351 QString database; 352 353 /** 354 * @brief Symbolic database name as listed in databases list. 355 * 356 * It can be empty if database was not explicitly passed in the query. 357 */ 358 QString dbName; 359 360 /** 361 * @brief Table name that the row ID is for. 362 */ 363 QString table; 364 365 /** 366 * @brief Table alias defined in the query. 367 * @see ResultColumn::tableAlias 368 */ 369 QString tableAlias; 370 371 /** 372 * @brief Mapping from alias to real column. 373 * 374 * This is mapping from QueryExecutor's internal aliases for columns 375 * into primary key column names of the table that the result column comes from. 376 * 377 * If you want to get list of column names used for RowId, use values() on this member. 378 * If you want to get list of query executor aliases, use keys() on this member. 379 */ 380 QHash<QString,QString> queryExecutorAliasToColumn; 381 }; 382 383 /** 384 * @brief Shared pointer to ResultRowIdColumn. 385 */ 386 typedef QSharedPointer<ResultRowIdColumn> ResultRowIdColumnPtr; 387 388 /** 389 * @brief Table that was a data source for at least one column in the query. 390 */ 391 struct API_EXPORT SourceTable 392 { 393 /** 394 * @brief Table's database. 395 * 396 * Same rules apply as for ResultColumn::database. 397 */ 398 QString database; 399 400 /** 401 * @brief Table name. 402 */ 403 QString table; 404 405 /** 406 * @brief Table alias defined in query. 407 */ 408 QString alias; 409 }; 410 411 /** 412 * @brief Shared pointer to SourceTable. 413 */ 414 typedef QSharedPointer<SourceTable> SourceTablePtr; 415 416 /** 417 * @brief Query execution context. 418 * 419 * This class is used to share data across all executor steps. 420 * It also provides initial configuration for executor steps. 421 */ 422 struct Context 423 { 424 /** 425 * @brief Query string after last query step processing. 426 * 427 * Before any step was executed, this is the same as originalQuery. 428 * 429 * The processed query is the one that will be executed in the end, 430 * so any steps should apply their changes to this query. 431 * 432 * This string should be modified and updated from QueryExecutorStep implementations. 433 * 434 * You won't usually modify this string directly. Instead you will 435 * want to use one of 2 methods: 436 * <ul> 437 * <li>Modify tokens</li> - modify tokens of top level objects in parsedQueries 438 * and call QueryExecutorStep::updateQueries(). 439 * <li>Modify parsed objects</li> - modify logical structure and values of 440 * objects in parsedQueries, then call on those objects SqliteStatement::rebuildTokens() 441 * and finally call QueryExecutorStep::updateQueries. 442 * </ul> 443 * 444 * The parsedQueries are refreshed every time when QueryExecutor executes 445 * QueryExecutorParse step. 446 */ 447 QString processedQuery; 448 449 /** 450 * @brief Number of milliseconds that query execution took. 451 * 452 * This is measured and set by QueryExecutorStepExecute step. 453 */ 454 qint64 executionTime = 0; 455 456 /** 457 * @brief Number of rows affected by the query. 458 */ 459 qint64 rowsAffected = 0; 460 461 /** 462 * @brief Total number of rows returned from query. 463 * 464 * It provides correct number for all queries, no matter if it's SELECT, PRAGMA, or other. 465 */ 466 qint64 totalRowsReturned = 0; 467 468 /** 469 * @brief Total number of pages. 470 * 471 * If there's a lot of result rows, they are split to pages. 472 * There's always at least one page of results. 473 */ 474 int totalPages = 1; 475 476 /** 477 * @brief Defines if row counting will be performed. 478 * 479 * In case of EXPLAIN or PRAGMA queries the number of result rows is not provided from 480 * SQLite (at least not from Qt's drivers for them). Instead we need to manually count 481 * number of rows. This is when this flag is set (it's done by QueryExecutor, 482 * no need to care about it). 483 */ 484 bool rowsCountingRequired = false; 485 486 /** 487 * @brief Executing query in EXPLAIN mode. 488 * 489 * This is configuration parameter passed from QueryExecutor just before executing 490 * the query. It can be defined by QueryExecutor::setExplainMode(). 491 */ 492 bool explainMode = false; 493 494 /** 495 * @brief Defines if row counting should be skipped. 496 * 497 * This is a configuration flag predefined by QueryExecutor just before executing starts. 498 * You can set it with QueryExecutor::setSkipRowCounting(). 499 * 500 * Row counting is done asynchronously, just after normal query execution is finished. 501 * It's done by executing yet another query, which is more or less an orginal query 502 * wrapped with "SELECT count(*) FROM (...)". 503 * 504 * Separate counting has to be done, because QueryExecutor adds LIMIT and OFFSET 505 * to SELECT queries for results paging. 506 * 507 * When counting is done, the resultsCountingFinished() signal is emitted. 508 */ 509 bool skipRowCounting = false; 510 511 /** 512 * @brief Parameters for query execution. 513 * 514 * It's defined by setParam(). 515 */ 516 QHash<QString,QVariant> queryParameters; 517 518 /** 519 * @brief Results handler function pointer. 520 * 521 * This serves the same purpose as in Db class. It's used for execution 522 * with results handled by provided function. See Db::QueryResultsHandler for details. 523 * 524 * It's defined by exec(). 525 */ 526 Db::QueryResultsHandler resultsHandler = nullptr; 527 528 /** 529 * @brief List of queries parsed from input query string. 530 * 531 * List of parsed queries is updated each time the QueryExecutorParseQuery step 532 * is executed. When it's called is defined by QueryExecutor::executionChain. 533 */ 534 QList<SqliteQueryPtr> parsedQueries; 535 536 /** 537 * @brief Results of executed query. 538 * 539 * This is results object defined by the final query execution. It means that the 540 * query executed passed all preprocessing steps and was executed in its final form. 541 * 542 * This member is defined by QueryExecutorExecute step. 543 */ 544 SqlQueryPtr executionResults; 545 546 /** 547 * @brief Currently attached databases. 548 * 549 * This is a cross-context information about currently attached databases. 550 * As QueryExecutorAttaches step does attaching, other steps may need information 551 * about attached databases. It's a map of orginal_db_name_used to attached_name. 552 */ 553 BiStrHash dbNameToAttach; 554 555 /** 556 * @brief Sequence used by executor steps to generate column names. 557 */ 558 int colNameSeq = 0; 559 560 /** 561 * @brief List of reasons that editing results is forbidden for. 562 * 563 * Executor steps may decide that the results of query cannot be edited. 564 * In that case they add proper enum to this set. 565 */ 566 QSet<EditionForbiddenReason> editionForbiddenReasons; 567 568 /** 569 * @brief Result columns that provide ROWID. 570 * 571 * QueryExecutorAddRowIds step adds those columns. There is one or more columns 572 * per data source table mentioned in the query. It depends on "WITHOUT ROWID" clause 573 * in CREATE TABLE of the source table. 574 */ 575 QList<ResultRowIdColumnPtr> rowIdColumns; 576 577 /** 578 * @brief Result columns from the query. 579 * 580 * List of result columns, just like they would be returned from regular execution 581 * of the query. Column in this list are not just a names of those columns, 582 * they provide full meta information about every single column. 583 */ 584 QList<ResultColumnPtr> resultColumns; 585 586 /** 587 * @brief Data source tables mentioned in the query. 588 * 589 * List of tables used as data source in the query. 590 */ 591 QSet<SourceTablePtr> sourceTables; 592 593 /** 594 * @brief Map of column aliases containing column types. 595 * 596 * Keys are query executor column aliases of column representing types 597 * and values are query executor column aliases of column to which these types apply to. 598 */ 599 QHash<QString, QString> typeColumnToResultColumnAlias; 600 601 /** 602 * @brief Query used for counting results. 603 * 604 * Filled with SQL to be used for results counting (even if counting is disabled). 605 * @see QueryExecutor::getCountingQuery() 606 */ 607 QString countingQuery; 608 609 /** 610 * @brief Flag indicating results preloading. 611 * 612 * Causes flag Db::Flag::PRELOAD to be added to the query execution. 613 */ 614 bool preloadResults = false; 615 616 /** 617 * @brief Tells if executed queries did modify database schema. 618 * 619 * This is defined by QueryExecutorDetectSchemaAlter step 620 * and can be accessed by QueryExecutor::wasSchemaModified(). 621 */ 622 bool schemaModified = false; 623 624 /** 625 * @brief Tells if executed query was one of DELETE, UPDATE or INSERT. 626 */ 627 bool dataModifyingQuery = false; 628 629 /** 630 * @brief Forbids QueryExecutor to return meta columns. 631 * 632 * See QueryExecutor::noMetaColumns for details. 633 */ 634 bool noMetaColumns = false; 635 636 /** 637 * @brief Contains error code from smart execution. 638 * 639 * This is always set by the smart execution method. It's useful if the smart execution 640 * failed and the simple execution method is being performed. In that case the query 641 * result will contain error code from simple execution, hiding the original error code 642 * from smart execution. 643 */ 644 int errorCodeFromSmartExecution = 0; 645 646 /** 647 * @brief Contains error message from smart execution. 648 * 649 * This is always set by the smart execution method. It's useful if the smart execution 650 * failed and the simple execution method is being performed. In that case the query 651 * result will contain error message from simple execution, hiding the original error 652 * message from smart execution. 653 */ 654 QString errorMessageFromSmartExecution; 655 }; 656 657 /** 658 * @brief Position for custom executor steps. 659 * 660 * These position define where in query executor chain of steps the new, registered step will be placed. 661 * It's used in arguments of registerStep() method. 662 * 663 * If multiple steps are registered at same position, they will be executed in order they were registered. 664 * 665 * Values of positions determin what actions have been already taken by the executor, so for example 666 * AFTER_ATTACHES means, that executor already attached referenced databases and replaced occurrences of objects 667 * from that databases. 668 * 669 * Enumerations are in order as the steps are executed. 670 * 671 * If you need more detailed description about certain steps performed by query executor, see documentation 672 * of their classes - all these classes name start with QueryExecutor prefix. 673 */ 674 enum StepPosition { 675 FIRST, /**< As first step */ 676 AFTER_ATTACHES, /**< After transparent attaching is applied (detected tables are defined to be attached first). */ 677 AFTER_REPLACED_VIEWS, /**< After referenced views have been replaced with subqueries */ 678 AFTER_ROW_IDS, /**< After ROWID columns have been added to result columns */ 679 AFTER_REPLACED_COLUMNS, /**< After all columns have been explicitly listed in result list, together with unique alias names */ 680 AFTER_ORDER, /**< After order clause was applied/modified */ 681 AFTER_DISTINCT_WRAP, /**< After wrapping SELECT was added in case of DISTINCT or GROUP BY clauses were used */ 682 AFTER_CELL_SIZE_LIMIT, /**< After cell result size was limited to save memory usage */ 683 AFTER_COLUMN_TYPES, /**< After typeof() result meta columns were added */ 684 AFTER_ROW_LIMIT_AND_OFFSET, /**< After LIMIT and ORDER clauses were added/modified. This is the last possible moment, directly ahead of final query execution */ 685 JUST_BEFORE_EXECUTION, /**< Same as AFTER_ROW_LIMIT_AND_OFFSET */ 686 LAST /**< Same as AFTER_ROW_LIMIT_AND_OFFSET */ 687 }; 688 689 /** 690 * @brief Interface for producing query executor steps. 691 * 692 * It can be used for overloaded version of registerStep() method, 693 * in case a step is stateful and needs to be created/deleted for every query executor processing. 694 * 695 * If step is stateless, it can be registered directly as an instance, using the other version of registerStep() method. 696 * 697 * This is an abstract class and not pointer to function, because it has to be comparable (and std::function is not), 698 * so it's possible to deregister the factory later on. 699 */ 700 class StepFactory { 701 public: 702 virtual QueryExecutorStep* produceQueryExecutorStep() = 0; 703 }; 704 705 /** 706 * @brief Creates query executor, initializes internal context object. 707 * @param db Optional database. If not provided, it has to be defined later with setDb(). 708 * @param query Optional query to execute. If not provided, it has to be defined later with setQuery(). 709 * @param parent Parent QObject. 710 */ 711 QueryExecutor(Db* db = nullptr, const QString& query = QString(), QObject *parent = 0); 712 713 /** 714 * @brief Releases internal resources. 715 */ 716 ~QueryExecutor(); 717 718 /** 719 * @brief Defined query to be executed. 720 * @param query SQL query string. 721 * 722 * The query string can actually be multiple queries separated with a semicolon, just like you would 723 * write multiple queries in the SQL Editor window. Query executor will handle that. 724 * 725 * The query can contain parameter placeholders (such as :param, \@param). To bind values to params 726 * use setParam(). 727 */ 728 void setQuery(const QString& query); 729 730 /** 731 * @brief Executes the query. 732 * @param resultsHandler Optional handler function pointer, can be lambda function. See Db::QueryResultsHandler for details. 733 * 734 * While execution is asynchronous, the executor notifies about results by signals. 735 * In case of success emits executionFinished(), in case of error emits executionFailed(). 736 */ 737 void exec(Db::QueryResultsHandler resultsHandler = nullptr); 738 739 /** 740 * @brief Interrupts current execution. 741 * 742 * Calls Db::asyncInterrupt() internally. 743 */ 744 void interrupt(); 745 746 /** 747 * @brief Executes counting query. 748 * @return true if counting query is executed (in async mode) or was executed correctly (in sync mode), false on error. 749 * 750 * Executes (asynchronously) counting query for currently defined query. After execution is done, the resultsCountingFinished() 751 * signal is emitted. 752 * 753 * Counting query is made of original query wrapped with "SELECT count(*) FROM (original_query)". 754 * 755 * It is executed after the main query execution has finished. 756 * 757 * If query is being executed in async mode, the true result (sucess/fail) will be known from later, not from this method. 758 */ 759 bool countResults(); 760 761 /** 762 * @brief Gets time of how long it took to execute query. 763 * @return Execution time in milliseconds. 764 * 765 * The execution time is number of milliseconds from begining of the query execution, till receiving of the results. 766 */ 767 qint64 getLastExecutionTime() const; 768 769 /** 770 * @brief Gets number of rows affected by the query. 771 * @return Affected rows number. 772 * 773 * Rows affected are defined by DbPlugin implementation and are usually a number of rows modified by UPDATE statement, 774 * or deleted by DELETE statement, or inserted by INSERT statement. 775 */ 776 qint64 getRowsAffected() const; 777 778 /** 779 * @brief Gets number of rows returned by the query. 780 * @return Number of rows. 781 * 782 * If QueryExecutor limits result rows number (if defined by setResultsPerPage()), the actual number of rows 783 * to be returned from query can be larger. This methods returns this true number of rows, 784 * that would be returned from the query. 785 * 786 * Calling this method makes sense only after resultsCountingFinished() was emitted, otherwise the value 787 * returned will not be accurate. 788 */ 789 qint64 getTotalRowsReturned() const; 790 791 /** 792 * @brief Gets type of the SQL statement in the defined query. 793 * @param index Index of the SQL statement in the query (statements are separated by semicolon character), or -1 to get the last one. 794 * @return Type of the query. If there were no parsed queries in the context, or if passed index is out of range, 795 * then SqliteQueryType::UNDEFINED is returned. 796 */ 797 SqliteQueryType getExecutedQueryType(int index = -1); 798 799 /** 800 * @brief Provides set of data source tables used in query. 801 * @return Set of tables. 802 */ 803 QSet<QueryExecutor::SourceTablePtr> getSourceTables() const; 804 805 /** 806 * @brief Gets number of pages available. 807 * @return Number of pages. 808 * 809 * Since QueryExecutor organizes results of the query into pages, this method gives number of pages that is necessary 810 * to display all the data. In other words: "results of this method" - 1 = "last page index". 811 * 812 * Single page size is defined by setResultsPerPage(). 813 */ 814 int getTotalPages() const; 815 816 /** 817 * @brief Gets ordered list of result columns. 818 * @return Result columns. 819 * 820 * See Context::resultColumns for details. 821 */ 822 QList<QueryExecutor::ResultColumnPtr> getResultColumns() const; 823 824 /** 825 * @brief Gets map of meta columns providing SQLite data types. 826 * @return Map of type column alias to target column alias (for which the type applies). 827 */ 828 QHash<QString, QString> getTypeColumns() const; 829 830 /** 831 * @brief Gets list of ROWID columns. 832 * @return ROWID columns. 833 * 834 * Note, that this returns list of ROWID columns as entities. This means that for ROWID a single ROWID column 835 * can be actually couple of columns in the results. To count the ROWID columns offset for extracting 836 * data columns use getMetaColumnCount(). 837 * 838 * See Context::rowIdColumns for details. 839 */ 840 QList<QueryExecutor::ResultRowIdColumnPtr> getRowIdResultColumns() const; 841 842 /** 843 * @brief Gives number of meta columns in the executed query. 844 * @return Number of the actual meta columns (such as ROWID columns) added to the executed query. 845 * 846 * This method should be used to find out the number of meta columns that were added to the begining 847 * of the result columns in the executed query. This way you can learn which column index use as a start 848 * for reading the actual data from the query. 849 * 850 * Meta columns are used by QueryExecutor to find more information about the query being executed 851 * (like ROWID of each row for example). 852 */ 853 int getMetaColumnCount() const; 854 855 /** 856 * @brief Gets reasons for which editing results is forbidden. 857 * @return Set of reasons. 858 * 859 * See Context::editionForbiddenReasons for details. 860 */ 861 QSet<EditionForbiddenReason> getEditionForbiddenGlobalReasons() const; 862 863 /** 864 * @brief Defines named bind parameter for the query. 865 * @param name Name of the parameter (without the : or @ prefix). 866 * @param value Value of the parameter. 867 * 868 * Positional (index oriented) parameters are not supported by the QueryExecutor. 869 * Always use named parameters with QueryExecutor. 870 */ 871 void setParam(const QString& name, const QVariant& value); 872 873 /** 874 * @brief Assigns all query parameters at once. 875 * @param params All bind parameters for the query. 876 * 877 * This is same as setParam(), except it overrides all current params with given ones. 878 * It allows for setting all params at once. 879 */ 880 void setParams(const QHash<QString, QVariant>& params); 881 882 /** 883 * @brief Gets currently defined database. 884 * @return Database object, or null pointer if not yet defined. 885 */ 886 Db* getDb() const; 887 888 /** 889 * @brief Defines new database for query execution. 890 * @param value Database object. It should be open before calling exec(). 891 */ 892 void setDb(Db* value); 893 894 /** 895 * @brief Gets original, not modified query. 896 * @return SQL query string. 897 */ 898 QString getOriginalQuery() const; 899 900 /** 901 * @brief Gets data size limit. 902 * @return Number of bytes, or UTF-8/UTF-16 characters. 903 * 904 * See setDataLengthLimit() for details. 905 */ 906 int getDataLengthLimit() const; 907 908 /** 909 * @brief Defines data size limit for results. 910 * @param value Number of bytes, or UTF-8/UTF-16 characters. 911 * 912 * Limit is not defined by default and in that case it's not applied 913 * to the query. To enable limit, set it to any positive number. 914 * To disable limit, set it to any negative number. 915 * 916 * When QueryExecutor prepares query for execution, it applies SUBSTR() 917 * to all result columns, so if the database has a huge value in some column, 918 * SQLiteStudio won't load 1000 rows with huge values - that would kill performance 919 * of the application. Instead it loads small chunk of every value. 920 * 921 * SqlQueryModel loads limited chunks of data and loads on-the-fly full cell values 922 * when user requests it (edits the cell, or views it in form editor). 923 * 924 * Parameter defined by this method is passed to SQLite's SUBSTR() function. 925 * As SQLite's documentation stand, numbers passed to that function are treated 926 * as number of bytes for non-textual data and for textual data they are number 927 * of characters (for UTF-8 and UTF-16 they can be made of more than 1 byte). 928 */ 929 void setDataLengthLimit(int value); 930 931 // TODO manual row counting -> should be done by query executor already and returned in total rows 932 /** 933 * @brief Tests if manual row counting is required. 934 * @return True if manual counting is required. 935 * 936 * In case of some queries the getTotalRowsReturned() won't provide proper value. 937 * Then you will need to count result rows from the results object. 938 * 939 * It's okay, because this applies only for EXPLAIN and PRAGMA queries, 940 * which will never return any huge row counts. 941 */ 942 bool isRowCountingRequired() const; 943 944 /** 945 * @brief Gets SQL query used for counting results. 946 * @return SQL query. 947 * 948 * This is the query used by countResults(). 949 */ 950 QString getCountingQuery() const; 951 952 /** 953 * @brief Gets number of rows per page. 954 * @return Number of rows. 955 * 956 * By default results are not split to pages and this method will return -1. 957 */ 958 int getResultsPerPage() const; 959 960 /** 961 * @brief Defines number of rows per page. 962 * @param value Number of rows. 963 * 964 * By default results are not split to pages. 965 * See setPage() for details on enabling and disabling paging. 966 */ 967 void setResultsPerPage(int value); 968 969 /** 970 * @brief Gets current results page. 971 * @return Page index. 972 * 973 * Results page is 0-based index. It's always value between 0 and (getTotalPages() - 1). 974 * If results paging is disabled (see setResultsPerPage()), then this method 975 * will always return 0, as this is the first page (and in that case - the only one). 976 */ 977 int getPage() const; 978 979 /** 980 * @brief Defines results page for next execution. 981 * @param value 0-based page index. 982 * 983 * If page value is negative, then paging is disabled. 984 * Any positive value or 0 enables paging and sets requested page of results to given page. 985 * 986 * If requested page value is greater than "getTotalPages() - 1", then no results will be returned. 987 * It's an invalid page value. 988 * If requested page value is lower then 0, then paging is disabled. 989 * 990 * Once the page is defined, the exec() must be called to get results 991 * from new defined page. 992 */ 993 void setPage(int value); 994 995 /** 996 * @brief Tests if there's any execution in progress at the moment. 997 * @return true if the execution is in progress, or false otherwise. 998 */ 999 bool isExecutionInProgress(); 1000 1001 /** 1002 * @brief Gets sorting defined for executor. 1003 * @return Sorting definition. 1004 * 1005 * See Sort for details. 1006 */ 1007 QueryExecutor::SortList getSortOrder() const; 1008 1009 /** 1010 * @brief Defines sorting for next query execution. 1011 * @param value Sorting definition. 1012 * 1013 * Once the sorting definition is changed, the exec() must be called 1014 * to receive results in new order. 1015 */ 1016 void setSortOrder(const QueryExecutor::SortList& value); 1017 1018 /** 1019 * @brief Tests if row counting is disabled. 1020 * @return true if row counting will be skipped, or false otherwise. 1021 * 1022 * See Context::skipRowCounting for details. 1023 */ 1024 bool getSkipRowCounting() const; 1025 1026 /** 1027 * @brief Defines if executor should skip row counting. 1028 * @param value New value for this parameter. 1029 * 1030 * See Context::skipRowCounting for details. 1031 */ 1032 void setSkipRowCounting(bool value); 1033 1034 /** 1035 * @brief Asynchronous executor processing in thread. 1036 * 1037 * This is an implementation of QRunnable::run(), so the QueryExecutor 1038 * does it's own asynchronous work on object members. 1039 */ 1040 void run(); 1041 1042 /** 1043 * @brief Tests if query execution should be performed in EXPLAIN mode. 1044 * @return true if the mode is enabled, or false otherwise. 1045 */ 1046 bool getExplainMode() const; 1047 1048 /** 1049 * @brief Defines EXPLAIN mode for next query execution. 1050 * @param value true to enable EXPLAIN mode, or false to disable it. 1051 * 1052 * EXPLAIN mode means simply that the EXPLAIN keyword will be prepended 1053 * to the query, except when the query already started with the EXPLAIN keyword. 1054 * 1055 * Once the mode is changed, the exec() must be called 1056 * to receive "explain" results. 1057 */ 1058 void setExplainMode(bool value); 1059 1060 /** 1061 * @brief Defines results preloading. 1062 * @param value true to preload results. 1063 * 1064 * Results preloading is disabled by default. See Db::Flag::PRELOAD for details. 1065 */ 1066 void setPreloadResults(bool value); 1067 1068 bool getAsyncMode() const; 1069 void setAsyncMode(bool value); 1070 1071 SqlQueryPtr getResults() const; 1072 bool wasSchemaModified() const; 1073 bool wasDataModifyingQuery() const; 1074 1075 static QList<DataType> resolveColumnTypes(Db* db, QList<ResultColumnPtr>& columns, bool noDbLocking = false); 1076 1077 bool getNoMetaColumns() const; 1078 void setNoMetaColumns(bool value); 1079 1080 void handleErrorsFromSmartAndSimpleMethods(SqlQueryPtr results); 1081 1082 /** 1083 * @brief Clears results handle and detaches any attached databases. 1084 */ 1085 void releaseResultsAndCleanup(); 1086 1087 const QStringList& getRequiredDbAttaches() const; 1088 1089 bool getForceSimpleMode() const; 1090 void setForceSimpleMode(bool value); 1091 1092 bool isInterrupted() const; 1093 1094 int getQueryCountLimitForSmartMode() const; 1095 void setQueryCountLimitForSmartMode(int value); 1096 1097 /** 1098 * @brief Adds new step to the chain of execution 1099 * @param position Where in chain should the step be placed. 1100 * @param step Step implementation instance. 1101 * 1102 * If multiple steps are registered for the same position, they will be executed in the order they were registered. 1103 * 1104 * If step is registered with a plugin, remember to deregister the step upon plugin unload. 1105 * Best place for that is in Plugin::deinit(). 1106 */ 1107 static void registerStep(StepPosition position, QueryExecutorStep* step); 1108 1109 /** 1110 * @brief Adds new step to chain of execution 1111 * @param position Where in chain should the step be placed. 1112 * @param stepFactory Factory for creating instance of the step. 1113 * 1114 * This is overloaded method for cases when the step is stateful and needs to be recreated for every invokation of query executor. 1115 */ 1116 static void registerStep(StepPosition position, StepFactory* stepFactory); 1117 1118 /** 1119 * @brief Removes extra step from the execution chain. 1120 * @param position Position from which the step should be removed. 1121 * @param step Step implementation instance. 1122 * 1123 * Removes step from list of additional steps to be performed. If such step was not on the list, this method does nothing. 1124 * 1125 * There is a position parameter to this method, becuase a step could be added to multiple different positions 1126 * and you decide from which you want to deregister it. 1127 */ 1128 static void deregisterStep(StepPosition position, QueryExecutorStep* step); 1129 1130 /** 1131 * @brief Removes extra step from the execution chain. 1132 * @param position Position from which the step should be removed. 1133 * @param stepFactory Factory to deregister. 1134 * 1135 * This is overloaded method to remove factory instead of instance of a step. To be used together with registerStep() 1136 * that also takes factory in parameters. 1137 */ 1138 static void deregisterStep(StepPosition position, StepFactory* stepFactory); 1139 1140 private: 1141 /** 1142 * @brief Executes query. 1143 * 1144 * It's called from run(). This is the execution of query but called from different 1145 * thread than exec() was called from. 1146 */ 1147 void execInternal(); 1148 1149 /** 1150 * @brief Raises execution error. 1151 * @param code Error code. Can be either from SQLite error codes, or from SqlErrorCode. 1152 * @param text Error message. 1153 * 1154 * This method is called when some of executor's preconditions has failed, or when SQLite 1155 * execution raised an error. 1156 */ 1157 void error(int code, const QString& text); 1158 1159 /** 1160 * @brief Build chain of executor steps. 1161 * 1162 * Defines executionChain by adding new QueryExecutorStep descendants. 1163 * Each step has its own purpose described in its class documentation. 1164 * See inheritance hierarchy of QueryExecutorStep. 1165 */ 1166 void setupExecutionChain(); 1167 1168 /** 1169 * @brief Deletes executor step objects. 1170 * 1171 * Deletes all QueryExecutorStep objects from executionChain clears the list. 1172 */ 1173 void clearChain(); 1174 1175 /** 1176 * @brief Executes all steps from executor chain. 1177 * 1178 * The steps chain is defined by setupExecutionChain(). 1179 * On execution error, the stepFailed() is called and the method returns. 1180 */ 1181 void executeChain(); 1182 1183 /** 1184 * @brief Executes the original, unmodified query. 1185 * 1186 * When smart execution (using steps chain) failed, then this method 1187 * is a fallback. It executes original query passed to the executor. 1188 * Given, that query was not modified, it cannot provide meta information, 1189 * therefore results of that execution won't editable. 1190 */ 1191 void executeSimpleMethod(); 1192 1193 /** 1194 * @brief Tests whether the original query is a SELECT statement. 1195 * @return true if the query is SELECT, or false otherwise. 1196 * 1197 * This method assumes that there was a problem with parsing the query with the Parser 1198 * (and that's why we're using simple execution method) and so it tries to figure out 1199 * a query type using other algorithms. 1200 */ 1201 bool simpleExecIsSelect(); 1202 1203 /** 1204 * @brief Releases resources acquired during query execution. 1205 * 1206 * Currently it just detaches databases attached for query execution needs (transparent 1207 * database attaching feature). 1208 */ 1209 void cleanup(); 1210 1211 /** 1212 * @brief Extracts counting query results. 1213 * @param asyncId Asynchronous ID of the counting query execution. 1214 * @param results Results from the counting query execution. 1215 * @return true if passed asyncId is the one for currently running counting query, or false otherwise. 1216 * 1217 * It's called from database asynchronous execution thread. The database might have executed 1218 * some other acynchronous queries too, so this method checks if the asyncId is the expected one. 1219 * 1220 * Basicly this method is called a result of countResults() call. Extracts counted number of rows 1221 * and stores it in query executor's context. 1222 */ 1223 bool handleRowCountingResults(quint32 asyncId, SqlQueryPtr results); 1224 1225 QStringList applyLimitForSimpleMethod(const QStringList &queries); 1226 1227 /** 1228 * @brief Creates instances of steps for all registered factories for given position. 1229 * @param position Position for which factories will be used. 1230 * @return List of instances of steps from given factories. 1231 */ 1232 QList<QueryExecutorStep*> createSteps(StepPosition position); 1233 1234 /** 1235 * @brief Query executor context object. 1236 * 1237 * Context object is shared across all execution steps. It's (re)initialized for every 1238 * call to exec(). Initialization involves copying configuration parameters (such as sortOrder, 1239 * explainMode, etc) from local members to the context. 1240 * 1241 * During steps execution the context is used to share information between steps. 1242 * For example if one step modifies query in anyway, it should store updated query 1243 * in Context::processedQuery. See QueryExecutorStep for details on possible methods 1244 * for updating Context::processedQuery (you don't always have to build the whole processed 1245 * query string by yourself). 1246 * 1247 * Finally, the context serves as a results container from all steps. QueryExecutor reads 1248 * result columns metadata, total rows number, affected rows and other information from the context. 1249 */ 1250 Context* context = nullptr; 1251 1252 /** 1253 * @brief Database that all queries will be executed on. 1254 * 1255 * It can be passed in constructor or defined later with setDb(), but it cannot be null 1256 * when calling exec(). The exec() will simply return with no execution performed 1257 * and will log a warning. 1258 */ 1259 Db* db = nullptr; 1260 1261 /** 1262 * @brief Synchronization mutex for "execution in progress" state of executor. 1263 * 1264 * The state of "execution in progress" is the only value synchronized between threads. 1265 * It makes sure that single QueryExecutor will execute only one query at the time. 1266 */ 1267 mutable QMutex executionMutex; 1268 mutable QMutex interruptionMutex; 1269 1270 /** 1271 * @brief Query to execute as defined by the user. 1272 * 1273 * This is a copy of original query provided by user to the executor. 1274 */ 1275 QString originalQuery; 1276 1277 QStringList queriesForSimpleExecution; 1278 1279 /** 1280 * @brief Predefined number of results per page. 1281 * 1282 * See setResultsPerPage() for details. 1283 */ 1284 int resultsPerPage = -1; 1285 1286 /** 1287 * @brief Predefined results page index. 1288 * 1289 * See setPage() for details. 1290 */ 1291 int page = -1; 1292 1293 /** 1294 * @brief Predefined sorting order. 1295 * 1296 * There's no sorting predefined by default. If you want it, you have to apply it with setSortOrder(). 1297 */ 1298 SortList sortOrder; 1299 1300 /** 1301 * @brief Flag indicating that the execution is currently in progress. 1302 * 1303 * This variable is synchronized across threads and therefore you can always ask QueryExecutor 1304 * if it's currently busy (with isExecutionInProgress()). 1305 */ 1306 bool executionInProgress = false; 1307 1308 /** 1309 * @brief Flag indicating that the most recent execution was made in "simple mode". 1310 * 1311 * This flag is set by executeSimpleMethod() method. See its documentation for details. 1312 * The exec() resets this flag to false each time, but each time the smart execution fails, 1313 * the executeSimpleMethod() is called and the flag is set to true. 1314 */ 1315 bool simpleExecution = false; 1316 1317 /** 1318 * @brief Flag indicating that the most recent execution was interrupted. 1319 * 1320 * This flag is set only if execution was interrupted by call to interrupt() on this class. 1321 * If the execution was interrupted by another thread (which called sqlite_interrupt() 1322 * or Db::interrupt()), then this flag is not set. 1323 * 1324 * This variable is tested at several stages of query execution in order to abort 1325 * execution if the interruption was already requested. 1326 */ 1327 bool interrupted = false; 1328 1329 /** 1330 * @brief Flag indicating that the execution is performed in EXPLAIN mode. 1331 * 1332 * See setExplainMode() for details. 1333 */ 1334 bool explainMode = false; 1335 1336 /** 1337 * @brief Flag indicating that the row counting was disabled. 1338 * 1339 * See Context::skipRowCounting for details. 1340 */ 1341 bool skipRowCounting = false; 1342 1343 /** 1344 * @brief Defines results data size limit. 1345 * 1346 * See setDataLengthLimit() for details. 1347 */ 1348 int dataLengthLimit = -1; 1349 1350 /** 1351 * @brief Limit of queries, after which simple mode is used. 1352 * 1353 * Up to the defined limit the smart execution will be used (unless #forceSimpleMode was set). 1354 * After exceeding this limit, the simple mode will be used. 1355 * Set to negative number to disable this limit. 1356 */ 1357 int queryCountLimitForSmartMode = -1; 1358 1359 /** 1360 * @brief Exact moment when query execution started. 1361 * 1362 * Expressed in number of milliseconds since 1970-01-01 00:00:00. 1363 */ 1364 qint64 simpleExecutionStartTime; 1365 1366 /** 1367 * @brief Asynchronous ID of counting query execution. 1368 * 1369 * Asynchronous ID returned from Db::asyncExec() for the counting query execution. 1370 * See countResults() for details on counting query. 1371 */ 1372 quint32 resultsCountingAsyncId = 0; 1373 1374 /** 1375 * @brief Flag indicating results preloading. 1376 * 1377 * See Context::preloadResults. 1378 */ 1379 bool preloadResults = false; 1380 1381 /** 1382 * @brief Determinates if asynchronous mode is used. 1383 * 1384 * By default QueryExecutor runs in asynchronous mode (in another thread). 1385 * You can set this to false to make exec() work synchronously, on calling thread. 1386 */ 1387 bool asyncMode = true; 1388 1389 /** 1390 * @brief Defines if the QueryExecutor will provide meta columns in the results. 1391 * 1392 * Set to true to forbid providing meta columns, or leave as false to let QueryExecutor 1393 * provide meta columns. 1394 * 1395 * Meta columns are additional columns that are not part of the query that was passed to the executor. 1396 * Those are for example ROWID columns (currently those are the only meta columns). 1397 * 1398 * You can always find out number of ROWID columns from getRowIdResultColumns(). 1399 * 1400 * Meta columns are placed always at the begining. 1401 */ 1402 bool noMetaColumns = false; 1403 1404 /** 1405 * @brief List of required databases to attach. 1406 * 1407 * List of database names (symbolic names, as they appear on the list) that needs to be 1408 * attached to access all columns returned by the most recent successful execution. 1409 * 1410 * This is set after every successful execution. 1411 */ 1412 QStringList requiredDbAttaches; 1413 1414 /** 1415 * @brief Chain of executor steps. 1416 * 1417 * Executor step list is set up by setupExecutionChain() and cleaned up after 1418 * execution is finished. Steps are executed in order they appear in this list. 1419 * 1420 * Steps are executed one by one and if any of them raises the error, 1421 * execution stops and error from QueryExecutor is raised (with executionFailed() signal). 1422 */ 1423 QList<QueryExecutorStep*> executionChain; 1424 1425 /** 1426 * @brief List of registered additional steps to be performed 1427 * 1428 * It's a map, where keys describe where in chain should the steps be placed 1429 * and values are list of steps to be inserted at that position. 1430 * 1431 * They are added/removed by methods: registerStep() and deregisterStep(). 1432 */ 1433 static QHash<StepPosition, QList<QueryExecutorStep*>> additionalStatelessSteps; 1434 1435 /** 1436 * @brief List of all registered additional steps 1437 * 1438 * This is a list of all registered additional steps (registered instances of steps), regardless of their position. 1439 * This is used to identify registered stateless steps, so they are not deleted on query executor cleanup. 1440 * 1441 * Only steps created with a factory are deleted upon executor cleanup (and of course all internal steps created by the executor itself). 1442 */ 1443 static QList<QueryExecutorStep*> allAdditionalStatelsssSteps; 1444 1445 /** 1446 * @brief List of registered factories that create additional steps to be performed 1447 * 1448 * This is similar to additionalSteps, except it holds factories, instead of step instances. 1449 * 1450 * Steps created with a factory are appended after stateless steps registered as direct 1451 * instances (held by additionalSteps) - that is for case when both instance and factory 1452 * are registered for the same step position. 1453 */ 1454 static QHash<StepPosition, QList<StepFactory*>> additionalStatefulStepFactories; 1455 1456 /** 1457 * @brief Execution results handler. 1458 * 1459 * This member keeps address of function that was defined for handling results. 1460 * It is defined only if exec() method was called with the handler function argument. 1461 * 1462 * Results handler function is evaluated once the query execution has finished 1463 * with success. It's not called on failure. 1464 */ 1465 Db::QueryResultsHandler resultsHandler = nullptr; 1466 1467 /** 1468 * @brief Parameters for query execution. 1469 * 1470 * It's defined by setParam(). 1471 */ 1472 QHash<QString,QVariant> queryParameters; 1473 1474 bool forceSimpleMode = false; 1475 ChainExecutor* simpleExecutor = nullptr; 1476 1477 signals: 1478 /** 1479 * @brief Emitted on successful query execution. 1480 * @param results Results from query execution. 1481 * 1482 * It's emitted at the very end of the whole query execution process 1483 * and only on successful execution. It doesn't matter if the execution was 1484 * performed in "smart mode" or "simple mode". 1485 */ 1486 void executionFinished(SqlQueryPtr results); 1487 1488 /** 1489 * @brief Emitted on failed query execution. 1490 * @param code Error code. 1491 * @param errorMessage Error message. 1492 * 1493 * It doesn't matter if the execution was performed in "smart mode" or "simple mode". 1494 */ 1495 void executionFailed(int code, QString errorMessage); 1496 1497 /** 1498 * @brief Emitted on successful counting query execution. 1499 * @param rowsAffected Rows affected by the original query. 1500 * @param rowsReturned Rows returned by the original query. 1501 * @param totalPages Number of pages needed to represent all rows given the value defined with setResultsPerPage(). 1502 * 1503 * This signal is emitted only when setSkipRowCounting() was set to false (it is by default) 1504 * and the counting query execution was successful. 1505 * 1506 * The counting query actually counts only \p rowsReturned, while \p rowsAffected and \p totalPages 1507 * are extracted from original query execution. 1508 */ 1509 void resultsCountingFinished(quint64 rowsAffected, quint64 rowsReturned, int totalPages); 1510 1511 public slots: 1512 /** 1513 * @brief Executes given query. 1514 * @param originalQuery to be executed. 1515 * 1516 * This is a shorthand for: 1517 * @code 1518 * queryExecutor->setQuery(query); 1519 * queryExecutor->exec(); 1520 * @endcode 1521 * 1522 * This exec() version is a SLOT, while the other exec() method is not. 1523 */ 1524 void exec(const QString& originalQuery); 1525 1526 private slots: 1527 /** 1528 * @brief Calledn when an executor step has failed with its job. 1529 * 1530 * An executor step reported an error. "Smart execution" failed and now the executor will try 1531 * to execute query with a "simple method". 1532 */ 1533 void stepFailed(QueryExecutorStep *currentStep); 1534 1535 /** 1536 * @brief Cleanup routines after failed query execution. 1537 * @param code Error code. 1538 * @param errorMessage Error message. 1539 * 1540 * Releases resources that are no longer used. Currently simply calls cleanup(). 1541 */ 1542 void cleanupAfterExecFailed(int code, QString errorMessage); 1543 1544 /** 1545 * @brief Called when the currently set db is about to be destroyed. 1546 * 1547 * Deletes results from the Context if there were any, so they are not referencing anything 1548 * from deleted Db. Keeping results is dangerous, becuase the Db driver (plugin) is most likely to 1549 * be unloaded soon and we won't be able to call results destructor. 1550 */ 1551 void cleanupBeforeDbDestroy(Db* dbToBeUnloaded); 1552 1553 /** 1554 * @brief Handles results of simple execution. 1555 * @param results Results object returned from Db. 1556 * 1557 * Checks results for errors and extracts basic meta information, 1558 * such as rows affected, total result rows and time of execution. 1559 * 1560 * In case of success emits executionFinished(), in case of error emits executionFailed(). 1561 */ 1562 void simpleExecutionFinished(SqlQueryPtr results); 1563 1564 /** 1565 * @brief Handles asynchronous database execution results. 1566 * @param asyncId Asynchronous ID of the execution. 1567 * @param results Results from the execution. 1568 * 1569 * QueryExecutor checks whether the \p asyncId belongs to the counting query execution, 1570 * or the simple execution. 1571 * Dispatches query results to a proper handler method. 1572 */ 1573 void dbAsyncExecFinished(quint32 asyncId, SqlQueryPtr results); 1574 }; 1575 1576 int qHash(QueryExecutor::EditionForbiddenReason reason); 1577 int qHash(QueryExecutor::ColumnEditionForbiddenReason reason); 1578 int qHash(QueryExecutor::SourceTable sourceTable); 1579 int operator==(const QueryExecutor::SourceTable& t1, const QueryExecutor::SourceTable& t2); 1580 1581 #endif // QUERYEXECUTOR_H 1582