
b709e29 Fix URL typo in release notes 01f203c Update release notes c49810a Update COPYRIGHT e327526 Add BSL version number to LICENSE.TXT 07e3a4e Remove superfluous COPURIGHT.md and LICENSE.md 54c3310 Replace Dynamic Data Routing Platform with Database Proxy 305d02f Remove *.cmake wildcard from .gitignore b0b5208 Cleanup of spaces aeca6d0 Extend maxscaled error messages 817d74c Document where the CDC users are stored 9a569db Update license ff8697a MXS-716: Fix table level privilege detection 2071a8c Only check replies of slaves that are in use f8dfa42 Fix possible hangs in CDC python scripts fa1d99e Removed "filestem option" from example 009b549 Removed "filestem option" from example 8d515c2 Add example Kafka producer script for Python 64e976b Fix sporadic SSL authentication failures 5a655dc MXS-814: Check service/monitor permissions on all servers 2a7f596 Add note about galeramon priority to Galera tutorials b90b5a6 Fixed SHOW SLAVE STATUS in binlog router e22fe39 Changed couln size for SHOW SLAVE STATUS ae97b18 Fix avrorouter build failure with older sqlite libraries 56ef8b7 Replace GPL license with BSL license in scripts and tests 552836f Initialize all fields when MySQL users are loaded from cache bf42947 Update all licensing related files b29db9d Remove optimize_wildcard parameter from use 5170844 Make readwritesplit diagnosting output more clear 262ffb1 Fix crash when a config parameter has no section 33ac9e6 Add note about LEAST_BEHIND_MASTER and server weights e13e860 Fix a memory leak when backend authentication fails 75d00c2 MXS-801: Set the default value of strip_db_esc to true bd5f2db MXS-800: Add a log message about the working directory 4b1dd8c Update MySQL Monitor documentation on detect_replication_lag 559bc99 Fix installation of license file b057587 Change LICENSE to LICENSE.TXT 223fa43 Remove null characters from log messages 36fd05b Fix fatal signal handler log message 053dc8a Fix typos in documentation 371dc87 Fix Galera text in Master-Slave tutorial 30b6265 Disable adding of new objects at runtime db92311 Update the documentation on configuration reloading 0923d40 Update Connector-C version c4738b5 Add define for avro-conversion.ini 196e6ac Update license from GPL to BSL. e612366 Correctly calculate the number of bytes read in dcb_read 93a2a03 Update rotate documentation in admin tutorial c5eb854 MXS-585: Fix authentication handling regression 6330070 Fix schemarouter memory leak aa5827e Fix CDC authentication memory leak a5af4ad Fix avro memory leaks 627d73f Fix Avro scripts 0ff7556 Add build instructions to avrorouter documentation 734a1c8 Fix doxygen mainpage e51ce09 Add licence text to avro scripts 4d27c14 Update Avro documentation and fix installation directories a58a330 Fix readconnroute error message about router_options 22b138c MXS-772: Fix postinstall script a9960b7 Fix function declaration in mysql_backend.c cbe1704 Add missing newline 09d76ee Fix avro documentation default values 1d3f8f3 Added refresh users on START SLAVE 880db34 Make router configuration errors fatal 3bad5ca Update documentation and add logging to avrorouter 10f3384 Disable SSLv3 ca8d902 Fix rwsplit error reporting when master is lost e816d65 Fix MaxScale Tutorial deca3e1 Update MaxScale man page f1735b7 Update release notes 9238714 qc: Change type of DEALLOCATE PREPARE 0b77c3b dbfwfilter: Do not require a trailing new line 1152ca9 Remove copyright message a038a85 Remove debug assertion on ERANGE error in galeramon 12ab235 Fix comparison error for connections limit. 5de1a8f qc_sqlite: Correct string recognition b63d754 Fix links in documentation contents 05d457e CDC protocol link fix 50676ef Fix monitor code formatting 218ba09 Remove MaxScale-and-SSL.md 0d6845b Add images to Avro documentation and tutorial 8dd2c9b Update MaxScale-2.0.0-Release-Notes.md 6d4b593 Change avrorouter default transaction grouping 4c629de Add notes about monitor changes to upgrading and release notes 267d0dc Update Binlogrouter.md c624781 Update Replication-Proxy-Binlog-Router-Tutorial.md f3261bc CDC users 1368797 Format authenticator and module headers ab01749 Format filters 8b05d32 Format core and include files f3974e5 Add GPL LICENSE to qc_mysqlembedded bfec36a astyle rabbitmq_consumer/consumer.c 54b960a Check that the Avro directory is writable 3d4cd2e Fix cdc_users using the wrong path for service users cache 1e738dd Add CDC client program documentation f6809fd Remove superfluous rabbitmw_consumer/LICENSE 6b5e667 Update license text in files 9bfcb46 Change CDC protocol documentation formatting 607f25c REQUEST-DATA formatting 8175ab4 CDC protocol update d5ca272 CDC protocol update 6c91764 Only check wsrep_local_index if node is joined f12e2c2 Do not use SSL for monitors and services 6d2cd99 Fix TestAdminUsers f4ae50d Apply astyle to server/core/test/*.c 7cc2824 Update build instructions cf8e2b5 Update release notes 03c7a6c Remove wrong function prototypes 5a11eed Revert "Remove duplicate functions" 80ed488 Remove duplicate functions bb0de8d Add info on SSL and throttling to release notes for 2.0. 0934aee Update MaxAdmin reference guide 2a3fe9b Update source URL in release notes e575cf0 Merge branch 'MXS-177-develop' into develop cc8c88d Change header for BSL ecde266 Change header for BSL 890b208 Log a message when a script is executed 9c365df Added information on server side SSL to config guide. aa3e002 Remove obsolete heading 79dd73a Make dprintAllSessions use dprintSession 1fc0db9 Align output of "show services" 1b9d301 Make monitorShowAll use monitorShow 983615e Adjust output of 'show modules' 436badd qc_sqlite: The module is now beta a7cbbe5 Update Upgrade document 71ac13f Remove obsolete user/password from example eb20ff8 Fix and clean up Avrorouter diagnostics code 31d4052 Change MaxScale to MariaDB MaxScale e6e4858 Fix `source` parameter not working with `router_options` d8de99a Update module version numbers eb81add Merge remote-tracking branch 'origin/develop' into MXS-177-develop daba563 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop 678f417 Changes in response to reviews. 410fb81 Changes in response to reviews. 60135e5 Add initial release notes about Avrorouter 7400ecc qc_sqlite: Remove uninitialized read 536962c Update version number 018f044 Fix debug assertion in client command processing 51f0804 Prevent 'show monitor' from crashing with failed monitor 559347e Fix "Too many connections" message; add comments. 01d3929 Add printf format checking to dcb_printf fbd49a6 dbfwfilter: Require complete parsing only when needed 1885863 Add information to release notes about readwritesplit changes 73b56a2 Update MaxScale section in release notes. 0a2f56f MaxAdmin: Remove debug information from 'show users' 3cf3279 MaxAdmin: Report SSL information as well 29c2b66 Always use SSL if server configured with SSL 7d6b335 dprintAllServers should use dprintServer 02a5246 qc_sqlite: Correctly detect parsing context 469419b compare: Add strict mode 8c5b3d3 compare: Allow the comparison of a single statement 4691514 Add Updgrade to 2.0 document 38b3ecb Expand the checks done before a monitor is stopped 8e2cfb9 Add backend name to authentication error message 9600a07 Fix MaxInfo crash 91c58b0 Removed log message for duplicate entry while adding an user 40392fe Fixed log message priority 0ec35b8 maxadmin: Allow the last user to be removed 5a0ebed maxadmin: Change name of user file 87aa8f1 maxadmin: Always allow root to connect bf37751 Fix COM_QUIT packet detection 7c93ee4 Update avrorouter documentation and tutorial 95ce463 Fix wrong directory in avrorouter log message cfe54c7 Update ChangeLog d69562c Fix LOAD DATA LOCAL INFILE data size tracking 24e7cd6 MXS-584: added support for SET @@session.autocommit d6f6f76 Fixes, correct too many connections message efeb924 Update release notes for 2.0.0 8f71a87 qc_sqlite: Adjust error messages b967d60 Remove copy of enum enum_server_command 822b7e3 Update package license b58301a Update MaxScale License for overlooked files c09ee47 Update MaxScale License 49f46fa Tidy up. Comment out config items not yet supported. f5c3470 Updated and simplified the Building from Source document 98b98e2 Add note about master failure modes to documentation e036f2c Update Limitations document 62219a5 Merge remote-tracking branch 'origin/drain-writeq' into develop 5caf667 Invoke DCB_REASON_DRAINED more frequently. 77b107b qc_sqlite: Add support for LOAD DATA INFILE 8e70f26 compare: Optionally print out the parse result ad750e6 Merge remote-tracking branch 'origin/MXS-651-develop-merge' into develop ef85779 Merge remote-tracking branch 'origin/develop' into MXS-651-develop-merge ea9fdda MXS-477: Add LONGBLOB support for readconnroute eae6d42 qc_sqlite: Remove superfluous columnname definition 8fe2b21 Add binlog source to avrorouter b25cc37 qc_sqlite: Add missing destructors 8a749e7 qc_sqlite: Reduce number of keywords 5f4bb8b compare: Output query immediately 2456e52 dbfwfilter: Reject queries that cannot be parsed 5f1fbbd qc_sqlite: Extend SET grammar b8d8418 dbfwfilter: Remove 'allow' from firewall filter rule 0bd2a44 MXS-741 When no events are read from binlog file, ... a07c491 Remove duplicated function (merge error, probably) b237008 Save conflict resolution, missed last time. a0c0b40 Merge remote-tracking branch 'origin/develop' into MXS-651-develop 385d47d Change SSL logic, fix large read problem. b93b5e0 Remove false debug assertion b953b1f Turn off SSL read ahead. e0d46a5 Fix error messages and remove commented code 49b4655 MXS-739: Fix invalid JSON in Maxinfo 0c30692 qc_sqlite: Handle GROUP_CONCAT arguments 54e48a1 qc_sqlite: Consider \ as an escape character in strings 713a5d6 qc_sqlite: Add test cases 20d1b51 qc_sqlite: Handle qualified names in CREATE VIEW 1019313 qc_sqlite: Make QUERY_TYPE_WRITE default for SHOW 059c14e qc_sqlite: Accept qualified function names in SELECT db34989 qc_sqlite: Accept qualified function names b93e2f1 qc_sqlite: Add limited support for GRAND and REVOKE 678672d qc_sqlite: Cleanup copying of database and table names 9b744b9 qc_sqlite: Update table and database names at the same time db75e61 qc: Support getting the qualified table names 1f867f4 qc: Add join.test 9c7e02a qc_sqlite: Accept "...from NATURAL straight_join..." 93d1c31 qc_sqlite: Both " and ' can enclose a string literal 8055b21 qc_sqlite: Set more information based upon tokens 37e3663 qc_sqlite: Do not blindly add affected fields 50f1360 qc: Correctly collect affected fields 71c234e qc_sqlite: Recognize CREATE TABLE ... UNION 01803f1 qc_sqlite: Recognize {DEALLOCATE|DROP} PREPARE ... 6ecd4b3 qc_sqlite: Parse index hints 0bdab01 qc: Compare sets of tables b908c8f Fix double freeing of internal DCBs 8903556 qc_sqlite: Recognize LEFT, INSERT and REPLACE 266e6c0 qc: Log all problems by default (compare program) 7b54cac qc_sqlite: Fix logging bug 9566e9f qc_sqlite: Plug a leak b0a860d qc: Run compare a specified number of times 050d698 qc_sqlite: Simplified argument handling 97c56b8 qc: Allow arguments to be passed to the query classifier 09a46e0 qc_sqlite: Add argument log_unrecognized_statements fd98153 qc: Allow arguments to be provided to the query classifier 313aa7e Fix Problems SSL assertion; non SSL connect to SSL 1d721e6 Fix DEB packaging errors 96bdc39 Fix RPM packaging failures on CentOS 7 6ba900d qc_sqlite: Recognize more SHOW commands 2869d0b qc_sqlite: Exclude support for sqlite's PRAGMA 0be68a3 qc_sqlite: Enhance SELECT syntax 28f3e1a Merge branch 'develop' into MXS-729 e18bd41 qc: Expose the result of the parsing 5896085 Add BUILD_AVRO to the CMake cache daeb896 Remove changes to blr_master.c memory handling d523821 Add comments 4eb9a66 Empty admin users file is now handled 52b46c6 qc: Update create.test db09711 qc_sqlite: Ignore case when looking for test language keywords f042a1d qc_sqlite: Extend CREATE TABLE syntax 177d2de qc_sqlite: Extend CREATE TABLE syntax d3ca8e6 qc_sqlite: Add some support for HANDLER 86c6a96 qc_sqlite: Recognize RENAME TABLE 471594f qc_sqlite: Accept more table options at CREATE TABLE 3da6cde qc_sqlite: Remove unused keywords bd89662 Fix crash on corrupted passwd file b5d1764 MXS-733: Always print session states 043e2db Remove unused CMake variables 5604fe2 Restore missing line, fixes logic error. 66d15a5 Added log message warning for old users found 5be9fca Changes in response to review by Johan 899e0e2 Removed password parameter from admin_user_add and admin_remove_user a2d9302 Merge branch 'develop' into MXS-729 bcaf82f Code review update e61c716 Nagios plugin update with Maxadmin using UNIX socket only d7150a2 qc_sqlite: Extend column syntax 3b78df0 qc_sqlite: Accept VALUE in addition to VALUES 85a705b qc_sqlite: Accept CHARSET in addition to CHARACTER SET db9cec8 qc_sqlite: Accept qualified column names in CREATE TABLE a9cabb0 qc_sqlite: Extend SELECT syntax f5e9878 qc_sqlite: Add set type 675cb93 qc_sqlite: Allow BINARY to turn into an identifier b04a760 qc_sqlite: Accept DROP TABLES 1075d9c qc_sqlite: Allow qualified name with LIKE in CREATE 420ac56 qc_sqlite: Extend EXPLAIN grammar 727d626 Add missing error message to readwritesplit f4fd09e Change templates and testing configurations to use sockets 1ef2e06 Add configurable default admin user a723731 Remove wrong file 7c3b02b Maxadmin/maxscaled UNIX socket update eed78d4 qc_sqlite: Pick out more information from select when CREATEing 267f091 qc_sqlite: Recognise DROP TEMPORARY TABLE 54fc29f qc_sqlite: Accept $ as a valid character in identifiers afa2ec9 qc_sqlite: Allow keywords to be used in qualified name db0427d MXS-729 code review update a3b3000 Merge branch 'develop' into MXS-729 e73d66c qc_sqlite: Identify qualified identifiers 5bacade Trailing space fix 3bc9be3 MXS-729 socket=default support in maxscale.cnf 1a5c23c Code review update for MXS-729 d6665c7 qc_sqlite: Extend CREATE TABLE grammar 91725ce qc_sqlite: Dequote table and database names cd7a022 qc: Add create test 1aa4e6b qc: Update test files 762b0c2 qc_mysqlembedded: Do not return "*" as table name cd9968f qc_sqlite: Update delete.test f16703d qc_sqlite: Add support for CALL e3ca9b4 qc_mysqlembedded: Do not return an array of empty strings 5878a22 qc_sqlite: Support selects in DELETE 1cf0444 qc_sqlite: Fix bug in DELETE grammar 0bf39a1 qc_sqlite: Add support for CHECK TABLE 4a8feca qc_sqlite: Add helper for catenating SrcLists ab299b3 qc_sqlite: Extend DELETE syntax 5778856 qc_sqlite: Extract database name as well 99901f1 qc_sqlite: Extend DELETE syntax 63396f8 qc_sqlite: Match "autocommit" caseinsensitively e804dd3 qc_sqlite: Add support for LOCK/UNLOCK c23e442 qc_sqlite: Extend DELETE syntax 5460e31 qc: Add delete test ab392ad qc_sqlite: Free unused data 598c6f0 qc: Measure time of parsing 2fa3844 qc_sqlite: Put all changes being {%|#}ifdefs 1b43992 qc_sqlite: Modified update.test 1676ea4 qc_sqlite: LEFT|RIGHT are not required with JOIN 224ebd3 qc_sqlite: Extend UPDATE grammar dbecca9 qc_sqlite: Extend UPDATE grammar b6ca3b3 MaxAdmin security modification MXS-729 8fb47dd Remove copying of MariaDB embedded library files 22e1257 Normalize whitespace when canonicalizing queries 269cff2 MXS-697: Fix dbfwfilter logging for matched queries 6344f6f Ignore Apple .DS_Store files. d606977 Improve comments in response to code review. 619aa13 Add configuration check flag to MaxScale 27c860b Drain write queue improvements. 33d4154 Read only one configuration file d104c19 Format more core files 83fdead Format part of core source code 311d5de Format gateway.c and config.c with Astyle 8cbb48e Don't build maxavro library if BUILD_AVRO is not defined 32bb77a Merge branch 'MXS-483' into develop db72c5d Format CDC/Avro related files 3c26e27 qc_sqlite: Use SrcList instead of Expr f96ad6a Merge branch 'develop' into MXS-729 0728734 Fix query canonical form tests e68262d Merge remote-tracking branch 'gpl-maxscale/master' into develop 65460dc Fix missing symbols from MySQLAuth 791c821 MaxAdmin listens on UNIX socket only and maxadmin can connect 89afed6 MXS-66: All configuration errors are fatal errors d613053 Add more details to galeramon documentation 22f4f57 qc: Add support for multi UPDATE 0dba25a Added default port to blr_make_registration 9d8248c qc_sqlit: Plug leaks and access errors 057551a qc_sqlite: Fix to small an allocation 1f73820 qc_sqlite: Free memory allocated during parsing 93fefb9 qc: Enable compare to run the same test repeatedly e52c578 qc_sqlite: Handle last_insert_id() 929e02a qc_sqlite: Extend UPDATE grammar de3b9f7 qc_sqlite: Defines provided when running cmake and make 4d5c3b2 qc_sqlite: Add support for multiple-table DELETE FROM 36a4296 qc_mysqlembedded: Handle SQLCOM_DELETE_MULTI 41f613a Fix DCB and SESSION removal from free object pools 00f2ddd Move some common code used in only one protocol into protocol. 6fbd0b0 Format Go source with gofmt abfbbcb Fix build failures and internal test suite 31de74a Merge branch 'develop' into MXS-483 20d461d Remove uniqueness constrain on oneshot tasks 6c09288 Add missing error message to converter task 0c2c389 Merge branch 'develop' into MXS-483 fa0accc Set freed memory to NULL after authentication failure 63f24e4 Install cdc_schema.go 5123c21 Fix ALTER TABLE parsing 004acc2 Merge branch 'develop' into MXS-483 f69a671 Remove array foreach macro use a159cd9 qc_sqlite: Add support for SHOW DATABASES 31a2118 Make qc_mysqlembedded optional 27ef30e Changed the default query classifier 359010d Add -h flag as the alias for --host bebc086 Fix minor bugs c7ca253 qc_sqlite: Recognize START [TRANSACTION] 240f8bf qc_sqlite: Collect info from nested SELECTs 93ea393 qc_sqlite: Pass along the relative position of a token cc960af qc_sqlite: Fix incorrect assigment 22a6fef Fix `gtid` avro index table 4c38bef qc_sqlite: STATUS is not a registered word cace998 qc_sqlite: Include all fields of UPDATE 997b19c qc: Add update tests 7601b3f qc_sqlite: Parse "INSERT INTO t VALUES (), ();" correctly ca426f1 qc_sqlite: Handle CREATE TRIGGER f54f963 qc_sqlite: Allow INSERT without INTO e4a1b6d Remove foreign keys from Avro index e4501a2 Merge branch 'develop' into MXS-483 82b9585 Fix MMMon never assigning master status a45a709 qc_mysqlembedded: Find the leaf name 2f3ca8f qc_mysqlembedded: Recognize SQLCOM_REPLACE cc7ad83 qc_mysqlembedded: Pick up fields for INSERT SELECT as well 0e6b39e qc: Cleanup of select.test 9113f4f qc_sqlite: Pickup more fields from INSERT 4d58f98 Dummy query classifier dfe824f Document `query_classifier` option 4aa329b MXS-718: Collect fields of INSERT 53818f2 Modify packet number for SSL backend connection 346f973 qc_sqlite: Accept qualified column names 8a83616 Fix in-memory SQLite table structure 6f2c884 Further backend SSL development 4444e92 qc_sqlite: Extend INSERT grammar 2aebcab qc_sqlite: Add support for TRUNCATE 1a6742e qc_sqlite: Accept DEFAULT as value in INSERT 07dec05 qc_sqlite: Crude classification made based on seen keywords a90a579 Add missing function documentation 72bd0cf qc_sqlite: Change CREATE TABLE grammar 6e04bc8 qc: Add INSERT tests 3666bda qc_sqlite: Add SELECT test d27e173 Add server/mysql-test/t/select.test to query_classifier 562d004 qc_sqlite: Cleanup error logging. 819cacb Merge branch 'develop' into MXS-483 0d3a789 Add warnings and comments to Avro row event processing 2fab570 Added support for SET autocommit=1 1aa83cf Code review fix c999f0a Addition of SELECT USER() 8c723da Clean up avro_client.c and avro_file.c eb21ee8 Clean up avro.c 946a284 Added Avro schema to table metadata processing 72f90be qc_sqlite: Add support for CREATE {FUNCTION|PROCEDURE} ... 4a4ab49 qc: Update line number also when skipping a block ffddb2a qc_sqlite: Allow queries using INTERVAL b8b03bd qc_sqlite: Add support for SELECT * FROM tbl2 = tbl1; 77a261a qc_sqlite: Add support for GROUP BY ... WITH ROLLUP 0ead41e cdc_schema now generates lowercase JSON 66e327a Classifier has to be specified explicitly 9074b91 Updated Avrorouter documentation cf06c7a qc_sqlite: Some comments added. f579eff Added simple Go based Avro schema generator f448e90 MXS-419: Added ulimit calls to init scripts b4ad257 Added FindAvro.cmake 56cc9b9 Added the last transaction script to installations 2d52da2 Added temporary avro-alpha package name 6ada071 Fixed cdc_users script 61f0206 Renaming and minor fixes to CDC Python scripts 9d77c32 Moved GTID table tracking to an in-memory database 8ae7cb0 MXS-704: Fixed `which` usage in post-install scripts 195e118 Readwritesplit sessions aren't created if master is down 2be91da Added affected tables to avro diagnostics b185320 QUERY-LAST-TRANSACTION now returns proper table names 90860b5 Log stale master message only once 4859c60 Table name to GTID mapping f77bd23 First steps to backend SSL, not yet working. 68b5bf0 qc_sqlite: Don't treat TRUE and FALSE as identifiers fca8e59 qc_sqlite: Collect database names as well 6b0e04d qc_sqlite: Add support for SHOW CREATE VIEW 77f4b34 qc_mysqlembedded: Report more, rather than less a73e033 qc_sqlite: Extend builtin functions 9d9650e qc_sqlite: SQL_BUFFER_RESULT must decay to an id 83fe99d qc_sqlite: Support INSERT IGNORE 9d1c9ca Added avrorouter limitations and tutorial 8dd094d qc_sqlite: Recognize builtin functions 2edc3d6 Moved write operations of the maxavro library to a different file 1364e54 Added more comments to the Avro RBR handling code f711588 Added warnign about unsupported field types df0d250 Added SQLite3 based indexing to avrorouter 0c55706 Added GTID event flag check in AVRO processing bfe28dd qc_sqlite: Accept SET GLOBAL|SESSION ... a8d2068 qc_mysqlembedded: Exlude code that won't compile on 5.5.42 16ea0b3 qc_sqlite: Add support for DROP FUNCTION 1c0f1fc qc: Report stats after comparison 02345b2 qc_sqlite: Recognize builtin readonly functions c7a5e75 qc_sqlite: Recognize := 0aa849d qc: Make compare undestand the delimiter command fb0a877 qc_mysqlembedded: Examine Item::SUBSELECT_ITEMs 045cf8d qc: Add missing mtl commands e5c6f45 qc_sqlite: Relax qc_get_type comparison ac3b2df qc_sqlite: Add support for SHOW STATUS 73a34fb qc_sqlite: Add initial support for FLUSH 4ffbe79 qc_sqlite: Extend CREATE TABLE syntax 009af81 qc_sqlite: Add support for SHOW WARNINGS 001de97 qc: Ignore mysqltest constructs 128307d Merge branch 'release-1.4.3' into gpl-master 5e8a06a SET NAMES XXX added 3ca12ba MXS-685: MMMon clears server state before setting it dc4d2b0 Further steps to connection limit, non-working. ef70257 MXS-636: Master failures are no longer fatal errors 99f4c64 Updated QUERY-LAST-TRANSACTION format d1ff157 Changed QUERY-LAST-TRANSACTION format to JSON 8b2f1ac Fixed formatting of the avrorouter 61543df Added QUERY-LAST-TRANSACTION command c10d10b qc_sqlite: Add support for SHOW CREATE TABLE 106a38f qc_sqlite: Add support for DROP INDEX 2a85421 qc_sqlite: Extend what can be stated about a table 794cd1c qc_sqlite: Add support for MATCH ... AGAINST dd7b747 qc_sqlite: Accept FULLTEXT and SPATIAL in CREATE TABLE a13d6ce qc_sqlite: Add support for PREPARE and EXECUTE 0c5d29f qc_sqlite: Add support for ANALYZE a6cd32b qc_sqlite: Extend SET syntax 5d47704 qc_sqlite: Pick out fields from UPDATE t SET i = ... 0e05735 qc: Understand --error in server test files 8535975 qc_sqlite: Extend CREATE VIEW syntax b35e638 qc: Igore read type bit if write bit is on 818a814 qc_sqlite: Add support for SHOW VARIABLES 1aa877b qc_sqlite: Add initial support for DO e92913a qc_sqlite: Add support for CREATE VIEW d53a46d qc_sqlite: Recognize bit field literals b'1010' 1fb7977 Added GTID event timestmap into struct gtid_pos 8f95b10 Added new fields in AVRO diagnostics cb4db54 Added tests with large SQL packets to modutil tests e4dbd6b MXS-621: More fixes to log messages at startup 4f1e9ee qc: compare tester can now read server MySQL tests cd8154b qc_sqlite: Allow CHARACTER SET to be specified for column 6f8d053 Added MariaDB 10.1 check for new flags in GTID event 71c471b qc_mysqlembedded: Fix type bits setting 26b00a7 qc_sqlite: Extend ALTER grammar ea6057c qc_sqlite: Handle also pInto when dupping a struct select 2271559 qc_sqlite: Add support for SHOW TABLE STATUS 9caaf27 qc_sqlite: Add support for CREATE ... LIKE oldtable cd19932 Merge tag '1.4.2' into master 9e9e4d8 Merge branch 'develop' of https://github.com/mariadb-corporation/maxscale-bsl into develop 267cb60 qc_mysqlembedded: Look into parenthesized comma expressions 77c6ca9 qc_sqlite: Recognize token "<=>" 5ca9a9f qc_sqlite: Allow comma expressions in where clause b08e910 qc_sqlite: Add SELECT options d11e581 qc_sqlite: Some recursion cleanup d53d063 Add but don't invoke connection queue functionality. 6818104 Fix logic error in connections limiter 3c61605 qc_sqlite: Find more affected fields 9af8dfd Allow the classifiers to be specified on the command line 5d4a134 Activate call to protocol for max connections error message. 16638e7 Fix another mistake 234f9e6 Fix mistake 843a6fc Fix mistake. 2c6e9ad Fix errors in config.c; enable call to protocol on connection limit. fd27849 Introduce configuration items for Maximum and Queued Service connections 60d198d Implement very simple connection limit. 84d8f0f Merge remote-tracking branch 'origin/develop' into MXS-177 8a58e63 Merge remote-tracking branch 'origin/develop' into develop 08487cd Add assertion to enforce number of free DCBs not being negative. f73af2f Added MariaDB 10.1 check for new flags in GTID event 23898ec Fix wrong sprintf specifier, trailing white space. ea6cfa3 readwritesplit: Cleaned up routeQuery 3858df0 Cleaned up select_connect_backend_servers c38ee13 Added more buffer tests 48816df Added more modutils tests 537eac2 Added tests for modutil_get_complete_packets 22a6095 MXS-669: modutil_get_complete_packets no longer makes the buffer contiguous 51af97e qc_sqlite: Add support for CREATE INDEX e50c573 qc_sqlite: Dig out fields for IN f58c6df qc_sqlite: Dequote table name 319422b qc_sqlite: Accept ENUM as type for a column 5d6a45c qc_sqlite: Allow UNSIGNED to fallback to an id 16a5f20 qc_sqlite: Extend CREATE TABLE syntax d6268da qc_sqlite: Accept RIGHT and FULL OUTER joins 2207415 qc_sqlite: Allow STRAIGHT_JOIN in SELECT 6fee546 qc_sqlite: Pick upp more table names 9de5f84 Remove trailing white space. 758f84d Improve comments and messages in dcb.c and session.c re recycle memory. 1c2de21 Merge remote-tracking branch 'origin/develop' into dcb-optimise 6614944 DCB code tidying. Fix missing spinlock release; remove redundant variables ecd5e5c Remove extra code introduced by merge. 877127a Merge commit '3c0d3e5ab6ddde59da764ec904b517759074a31e' into develop 4275bbe Updated the Connector-C version to 2.2.3 c71042b Some tentative list management code; provide for counting service clients. ad0c8a6 qc_sqlite: Allow empty insert statement 72e75e5 qc_sqlite: Add support for SELECT ... INTO cc553fa qc_sqlite: MAXSCALE define can now be used everywhere 3305c6e qc_sqlite: Handle CASE in SELECT 702f62e qc_sqlite: Extend CREATE TABLE grammar 941c212 qc_sqlite: Add support for SHOW [INDEX|INDEXES|KEYS] 6a79136 qc_sqlite: Extend grammar for SHOW TABLES and SHOW COLUMNS f175d2d qc_sqlite: Add SHOW COLUMNS support 6e47951 qc_sqlite: Add support for SHOW TABLES bcfa0e7 qc_mysqlembedded: Return the actual name and not as-name 3e19f2e Fixed qlafilter build failure 810b24e MXS-675: Standardized qlafilter output be92173 qc_sqlite: Exclude alias names from affected fields 9479280 qc_sqlite: Add support for explain EXTENDED 13b0e10 qc_sqlite: Add support for DELETE a6ccfea qc_mysqlembedded: Look at all conditional items b428041 qc_sqlite: Extend SELECT options 83f829f query_classifier: Correctly calculate the length of a GWBUF 2ddb24c query_classifier: Ensure that -- comments are handled fa7a746 qc_sqlite: Allow STRAIGHT_JOIN in SELECTS 6f47819 FindLibUUID update 5ed897b Added FindLibUUID cmake file 16e02bb Added FindLibUUID cmake file aff63e0 MXS-680: qc_mysqlembedded does not look into functions 8a0eeb4 query_classifier: Improve output of compare 6f08185 Query classifier can now convert enums to strings 124e2b9 MXS-679: Correctly collect fields of WHERE 353c97c transaction_safety default is off 896e37b qc_sqlite: Invert stop logic and be more verbose 7a44d4d qc_sqlite: Extend what is accepted in CREATE TABLE 4dbf499 qc_sqlite: Accept FIRST in ALTER TABLE 3f655c0 qc_sqlite: Update table and affected fields for INSERT 8e1e275 qc_sqlite: Make AS optional in CREATE statement 5f2084b qc_sqlite: Add support for ENGINE when creating a table 242f183 qc_sqlite: CREATE paramters handled in the correct place 8ed2e25 qc_sqlite: Trace only when needed 63d4531 qc_sqlite: Update affected fields also from functions 118cdc3 qc_sqlite: Allow multiple index names in USE|IGNORE INDEX 912da76 qc_sqlite: Add initial support for ...IGNORE INDEX... 0aa7de6 qc_sqlite: Log detailed message on error 3e3bf1a qc_sqlite: Extend create syntax. c4a4572 qc_sqlite: Exclude quoted values 1621f49 Removed MYSQL_EMBEDDED_LIBRARIES d3e324c UUID generation now comes from libuuid e8fe678 qc_sqlite: Enable confitional compilation a9522ba qc_sqlite: Handle X.Y selects 9bc9770 qc_sqlite: Use same stream when outputting padding 366257a qc_sqlite: Add support for UNSIGNED and ZEROFILL d4d90ff qc_sqlite: Add support for DROP VIEW d0519bd qc_sqlite: Extend DROP TABLE syntax c1e4894 qc_sqlite: Add flag to compare for stopping at first error 9fd6344 MXS-674: Maxinfo generates invalid JSON 3c0d3e5 Fix stupid errors. 9d32b2d Include read queue in buffer provided by dcb_read; changes to match. b690797 Fix double spinlock release in random_jkiss. 6a4328f Fix problems of memory not being freed in some error cases. 2112e56 Change DCB and Session handling to recycle memory; fix bug in random_jkiss. 3912f72 MXS-631, MXS-632: Cleaned up default value CMake files 383ccb8 Fixed build failure on MariaDB 5.5 a60bca5 Merge branch '1.2.1-binlog_router_trx' into develop 3c2a062 Fix to crashes in embedded library with MariaDB 10.0 d3fe938 MXS-662: Service protocol check no longer ignores bind address c3da49b qc_sqlite: Update affected fields from everywhere 7a0fab8 qc_sqlite: Allow verbosity of compare test to be controlled 81d6822 qc_sqlite: Cleanup handling of select columns 13e5c59 qc_sqlite: Introduce custom allocation functions 026f27d qc_sqlite: Add support for "USE database" 99079df qc_sqlite: Ignore duplicates when comparing affected fields ca45cd6 qc_sqlite: Add initial support for qc_get_database_names 75970b6 qc_sqlite: Add support for DROP TABLE. b97e45d qc_sqlite: Move get_affected_fields() to other helpers cb0fa96 qc_sqlite: Collect table names of INSERT 3a7c513 qc_mysqlembedded: Only look for created name if CREATE 308b0a4 qc_sqlite: Add support for gc_get_created_table_name. 0dc4af2 qc_sqlite: Add qc_has_clause() handling to update e9f2d1d qc_sqlite: Update now also provides table names c3192e4 qc_sqlite: Add initial support for get_table_names c51eafd qc_sqlite: Add support for qc_has_clause f318fb2 qc_mysqlembedded: Work around embedded lib bug 4ba2e11 qc_sqlite: Add initial support for qc_get_affected_fields 080dea5 qc_sqlite: Support is_read_query 3f94df1 Fixed compare.cc build failure 868a712 Updated freeing of buffer chains in readwritesplit 9bf7fca Formatted readwritesplit source code de4da2b Add assertion to spinlock release to detect release of already released spinlock. d30955a qc_sqlite: Handle the default case of affected fields. 5d02b3f qc_sqlite: Set operation when creating table 94a334d Add test for comparing qc-output aa6f5d6 Allow a specific query classifier to be loaded explicitly c799d37 Test both qc_mysqlembedded and qc_sqlite f8d9aa1 qc_sqlite: Enable "set @user_var=@@system_var" f190bdc qc_sqlite: Recognize /*!-comments b694b55 Fixed binary Avro format streaming c95fa86 qc_sqlite: Report correctly the type of set autocommit 9cb236c qc_sqlite: Add test case 77b4e62 Ensure classify test checks all types 962039e Change return type of qc_get_type ae00df8 qc_sqlite: Add initial support for the SET statement. 88253c5 qc_sqlite: Rename functions fa48043 Rework of MySQL backend protocol clean up to fix fault. 3851064 qc_sqlite: Correct recognition of system variables (@@xyz). 9d86f7f qc_sqlite: Detect user and system variables. a683297 qc_sqlite: Recognize and accept system variables (@@xyz). a4f64dd qc_sqlite: Add initial support for CREATE [TEMPORARY] TABLE f834b4f MXS-661: Only COM_QUERY packets are parsed 30077c1 CMake policies set only for correct versions a166f34 Suppress warning about unknown CMake target 1412730 Added more variables to launchable monitor scripts 358c194 MXS-656: Galera nodes with index 0 can be master again 842aec5 qc_sqlite: Add support for BEGIN, COMMIT, ROLLBACK b9cad6d Add initial support for UPDATE. 95741cb Add initial support for insert. 3796158 Re-install sqlite whenever parse.y has changed 5bcd8cf Ensure that the query is the one passed cf05533 Add support for obtaining the type of a query 400d8b4 Always log the outcome 45cf632 Fixed resource leaks and minor bugs fa9e970 Printout the query when there is a mismatch. 263cb07 All classify to be used with any query classifier ea381b9 Further cleanup of classify.c 23f6f30 Merge pull request #107 from godmodelabs/typo-dpkg 8c2a64e Fixed classify build failure 0c3070b Fixed binlog to Avro conversion bugs b827ba9 MXS-653: Silence maxpasswd 30d981c MXS-654: Add test for checking maxpasswd 984039b Rearrange classify.c 837e46d Add log initialization 1cc7a6e Reformat query_classifier/test/classify.c 065a4e5 Merge branch 'develop' into develop-MXS-544-b-merge ca27f13 Fixed binlog build failure fb81be2 fixed typo dpgk <-> dpkg 1e88d5d Added python based CDC user creation script 040bbdd MXS-633: Monitor permission checks moved to modules cde7595 Master-Slave clusters are now robust by default 158c776 Cleaned up core test suite 94c6e66 Fixed bugs resulting from merge a491e11 Merge remote-tracking branch 'origin/MXS-544-b' into develop-MXS-544-b-merge 30f9f25 Cleaned up avro.c 6286f64 Merge branch 'release-1.4.1' into develop 00206ac MXS-194: Added support for more query types to dbfwfilter 267832b Fixed diagnostic output a64b694 Fixed bugs in avrorouter 8faaba1 Fixed a bug in GTID seeking a5fafb7 Fixed typos in avrorouter documentation 8080379 Added avrorouter documentation fa07d8a Fixed dbfwfilter rule parser build failure 744ce0d Constraints are ignored in DDL statement processing 50808c6 Cleaned up avrorouter 47f6032 Merge branch '1.2.1-binlog_router_trx_lint' into develop caa0956 Added missing dependencies to maxscale-core 92df61a Remove parallel make from travis coverity builds fa2b2b4 Added more error logging to Avro record reading 9a98e8b Support for GTID requests and data bursts c2a787b Small diagnostic fix c4cee7e Added format output requested by client 50483c7 Cleaning up of Avro code d485379 Added support for binary Avro protocol c22cdbb Converted Avro GTID from string to integer representation 5795ca9 Added coverity notification email to .travis.yml a06e44d Added coverity_scan to Travis 6b94384 Fixed memory leak in avro_schema.c a11096c Support for db.table request for Avrorouter 4e5cbbf Fixed bugs in Avro record reading a99e427 Fixed minor bugs in avrorouter 01db8ae Fixed errors with CREATE TABLE statements f5f3d7a Diagnostic routine update 209324f Added missing include for log_manager.h e62f764 Added sending of schemas and file rotation 8c8fcbb Added missing log_manager.h include b13942d Changed printf calls in maxavro library to MXS_ERROR 1168962 More lint inspired changes, mainly in blr_master.c and blr_slave.c ced8f2f Fixed directory checks in avrorouter a8ae6be Minor fix to string processing fbd2d95 Fixed typo in dbfwfilter's CMakeLists.txt 29c3cf4 Merge pull request #106 from mariadb-corporation/willfong-patch-1 854d4e9 Add password column name to example 2f956df Moved server state change logging to a common function 007121f Fixed truncated string values 782892b Fix lint errors and warnings for blr_file.c 4f99fc5 Added Avro testing script 2820980 Small fix to help clear lint problems in blr.c 3afeda4 Fixed errors and warnings located by lint ecfff82 Fix most lint problems in blr.c 223689c Added ALTER TABLE support 80bc935 Fix final lint problems with mysql_common protocol functions. e068310 Added preliminary alter table parsing 8c723f1 Lint monitor modules fdb5620 Fix lint issues in authenticators. 84f0e04 Added function documentation and renamed files 365d9f5 Tidy up, mainly for lint 2ff3005 Added update rows event processing and event types to avro records 2ae0371 Fixed failing regex and improved data streaming f19206a Renamed avrorouter header aa7174b Moved relpacement and storage of ddl statements to a separate function 0c10be8 Improved client notification and added Avro block size managemet 91405a7 Cleaned up instance creation dd97485 Removed useless vars af64e9e Added CDC authentication with a db file b73a118 Streamline and lint MySQL backend protocol. 65034ce Merge branch 'release-1.4.0' into develop 28f7e4e Added callback for AVRO client async data transmission 628c27a Added MAXAVRO_FILE struct to AVRO_CLIENT 32b3645 Fixed slavelag build failure 7b15542 Added default authentication method for CDC protocol 5f8e20f Renamed maxavro types and formatted files that use them 882cf84 Added more function documentation to maxavro library 9532f0b Fixed CDC protocol build failure 35a1d3a Added support for offsets in client requests 94577ac Fixed, formatted and refactored CDC protocol da9bcad Use the maxavro library to read data from Avro files 3ececee Added low level error checking to maxavro library 01b0b8b Tidy and lint mysql_client.c 943f0a7 Added handling of Avro boolean data types to maxavro library 4c781f7 Cleaned up maxavro library and avrorouter 6b2e85d Renamed functions more consistently and cleaned up code e07158a Moved query event handling to its own function df7d4c0 Added avro_ prefix to rbr.c fcbfceb Added seeking to a position in an Avro file 068243a CDC auth decoding 3584d54 Add checks to simplify downstream logic. 9b2c323 Removed useless fprintf bd5cd52 Added missing authfunc setup e4aff59 Added record value processing 5cc8615 Added value length functions 7921ecc Merge branch 'MXS-615' into MXS-483 4b09cca Added Travis status to readme.md cca3a48 Simplify interface to max admin authentication. 4739838 Authenticator API update 233505f Maxavrocheck now accepts multiple files 3fdd137 Improved the Avro file handling a6ba913 Merge from MXS-615 417d742 Added maxavrocheck 014f9cf Remove obsolete second parameter from authenticate function in authenticators. ece7ece MaxAdmin authentication converted to a module. Fix quirk in SSL setup. 7c8b37e Moved contents of avro_schema.h into mxs_avro.h d6660cf Improvements to type handling 71ed0cf Protocol API to have entry point for obtaining default authenticator name. 9d35de2 Fixed transaction tracking 5be02a2 Avrorouter internal state is now stored in the Avro file directory 9293464 Added new info to avro diagnostics 06e0e93 Protocol modules can still handle the authentication outside authenticator modules 6d7108b Added JSON output when Requesting an avro file 6188211 Added new CDC protocol state c8af27f CDC authentication uses its own authenticator 6590f94 Factor out qc_get_qtype_str b7880f1 Fix qc_sqlite CMakeLists.txt bd4ff43 Fixed connector-c being updated and built after every make invokation 0d9e57b Fixed non-MariaDB connectors being used in builds 3d3b779 FIX BUG IN CLIENT DCB SHUTDOWN THAT CAN CAUSE CRASHES e45ba33 Fixed Connector-C .cmake files c130189 Fixed connector-c being updated and built after every make invokation 7f3cdf3 Fixed errors on binlog rotation 9d3c83a Remove qc_sqlite 15e8ba5 CDC protocol is now compliant with new protocol structure 4460869 Merge branch 'release-1.4.0' into MXS-483 ea40812 Cleaned up the binlog processing loop cb646ca Add minimal select recognition to qc_sqlite ac1a9c5 Fixed binlogrouter test 85dd227 Re-route sqlite's sqlite3Select. 7a2e6f3 Update CMakeLists.txt for qc_sqlite 7a751c3 Added timestamps to records and fixed minor bugs f73bdde Avrorouter state storage to disk fcf0488 Fixed Connector-C .cmake files 48b8e4e Merge branch 'MXS-615' into MXS-615-binlog-merge 7c8e19f Add missing dependencies for qc_sqlite bb9b667 Improvements to type handling and binlog position tracking dc66b74 Client UUID added f12fce4 AVRO registration is now handled by avro router 575b809 Add skeleton sqlite-based query classifier. d09d5fc Build sqlite 146d1f9 Fixed BLOB type handling and refined error messages 6e9e521 Added client user to diagnostics 4538bb8 Merge pull request #104 from rasmushoj/develop 7e18d95 Avro router diagnostics routine update 01e3f75 reverted changes in CMakeLists.txt 52f7c78 reverted changes in postinst.in eaed577 Added sqlite 3110100 a58cdda Travis configuration for MaxScale. ... 38b452d MIGRATE FREE CLIENT DATA TO AUTH MODULE; BUG FIXES; TIDY UP 6e64506 Fixed minor bugs aff2411 Enabled CDC protocol f669100 Fixed NULL Avro value being assigned to a field which cannot be NULL 8f6b16a Added row event processing to avrorouter 2939fe0 Updated Avro schema management to use actual column names 9e3b0cb Removed use of RBR related functions in binlogrouter d674903 Formatted avro files fe028d1 DEVELOPMENT OF AUTHENTICATION AS MODULE - WILL NOT WORK YET 977aded Added authenticator modules to the build a2b384f MOVE MYSQL AUTH CODE INTO AUTHENTICATOR MODULES DIRECTORY a5d7484 PRELIMINARY CHANGES TO CREATE AUTHENTICATORS AS MODULES 66cf802 Merge remote-tracking branch 'origin/develop' into MXS-615 bca0a7d MINOR CHANGES TO SATISFY LINT 5a9e397 Added Avrorouter binlog file walking fbc737f Fixed binlogrouter test 3c7c9d7 Added avrorouter main event handling loop 07ad81b Moved common binlogrouter code to a separate file 8c605ed Fixed avrorouter build failures aa1ba05 Moved binlog definitions to a separate header and fixed build failures eee7c55 Added create table statement detection e52b27e Added AVRO_INSTANCE and AVRO_CLIENT 0830caa Change test for client DCB to use role being DCB_ROLE_CLIENT_HANDLER. ... 997bbca Change protocols to continue looping if an accept fails; ... 522e42d Make use of dcb_accept and dcb_listen in httpd and telnetd protocols. 4e692b0 Generalise dcb_listen to tailor log messages to different protocols. ... 52c431d Remove support for passing default port number when handling ... afe5abc Fix bug in creation of SSL listener structure; fix bugs in ... 0bd6c77 Merge remote-tracking branch 'origin/MXS-544' into MXS-544-a ... 7598597 Add dcb_listen function to make a given DCB into a listener, ... a275d89 Maxbinlogcheck avro version can detect proper end of file 9bb55a5 Moved row event and table map event handling to a separate file b7d9e09 Add/improve comments, fix mistake with premature return. c598770 First attempt at extracting general code into dcb_accept, ... f20f28f Testing with maxbinlogcheck b3c60b7 Added mysql_binlog files 0ff9971 Added MariaDB/MySQL binary data processing functions 124560c Merge branch '1.2.1-binlog_router_trx' into MXS-483 4deccff New router fro cdc client 2c11434 Fixed test compiler errors c1f7d24 Obliged to merge remote-tracking branch 'origin/develop' ... 1775599 Merge remote-tracking branch 'origin/MXS-544' into Test-dev-544-merge c5317da Small modifications in comments 11c0666 Code cleanup 64a5e9a Merge branch 'release-1.3.0' into MXS-483 2c11e89 First Implementation of CDC
5658 lines
201 KiB
C
5658 lines
201 KiB
C
/*
|
|
** 2001 September 15
|
|
**
|
|
** The author disclaims copyright to this source code. In place of
|
|
** a legal notice, here is a blessing:
|
|
**
|
|
** May you do good and not evil.
|
|
** May you find forgiveness for yourself and forgive others.
|
|
** May you share freely, never taking more than you give.
|
|
**
|
|
*************************************************************************
|
|
** This file contains C code routines that are called by the parser
|
|
** to handle SELECT statements in SQLite.
|
|
*/
|
|
#include "sqliteInt.h"
|
|
|
|
/*
|
|
** Trace output macros
|
|
*/
|
|
#if SELECTTRACE_ENABLED
|
|
/***/ int sqlite3SelectTrace = 0;
|
|
# define SELECTTRACE(K,P,S,X) \
|
|
if(sqlite3SelectTrace&(K)) \
|
|
sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
|
|
(S)->zSelName,(S)),\
|
|
sqlite3DebugPrintf X
|
|
#else
|
|
# define SELECTTRACE(K,P,S,X)
|
|
#endif
|
|
|
|
|
|
/*
|
|
** An instance of the following object is used to record information about
|
|
** how to process the DISTINCT keyword, to simplify passing that information
|
|
** into the selectInnerLoop() routine.
|
|
*/
|
|
typedef struct DistinctCtx DistinctCtx;
|
|
struct DistinctCtx {
|
|
u8 isTnct; /* True if the DISTINCT keyword is present */
|
|
u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
|
|
int tabTnct; /* Ephemeral table used for DISTINCT processing */
|
|
int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
|
|
};
|
|
|
|
/*
|
|
** An instance of the following object is used to record information about
|
|
** the ORDER BY (or GROUP BY) clause of query is being coded.
|
|
*/
|
|
typedef struct SortCtx SortCtx;
|
|
struct SortCtx {
|
|
ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
|
|
int nOBSat; /* Number of ORDER BY terms satisfied by indices */
|
|
int iECursor; /* Cursor number for the sorter */
|
|
int regReturn; /* Register holding block-output return address */
|
|
int labelBkOut; /* Start label for the block-output subroutine */
|
|
int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
|
|
int labelDone; /* Jump here when done, ex: LIMIT reached */
|
|
u8 sortFlags; /* Zero or more SORTFLAG_* bits */
|
|
};
|
|
#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
|
|
|
|
/*
|
|
** Delete all the content of a Select structure. Deallocate the structure
|
|
** itself only if bFree is true.
|
|
*/
|
|
static void clearSelect(sqlite3 *db, Select *p, int bFree){
|
|
while( p ){
|
|
Select *pPrior = p->pPrior;
|
|
sqlite3ExprListDelete(db, p->pEList);
|
|
sqlite3SrcListDelete(db, p->pSrc);
|
|
sqlite3ExprDelete(db, p->pWhere);
|
|
sqlite3ExprListDelete(db, p->pGroupBy);
|
|
sqlite3ExprDelete(db, p->pHaving);
|
|
sqlite3ExprListDelete(db, p->pOrderBy);
|
|
sqlite3ExprDelete(db, p->pLimit);
|
|
sqlite3ExprDelete(db, p->pOffset);
|
|
sqlite3WithDelete(db, p->pWith);
|
|
#ifdef MAXSCALE
|
|
sqlite3ExprListDelete(db, p->pInto);
|
|
#endif
|
|
if( bFree ) sqlite3DbFree(db, p);
|
|
p = pPrior;
|
|
bFree = 1;
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Initialize a SelectDest structure.
|
|
*/
|
|
void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
|
|
pDest->eDest = (u8)eDest;
|
|
pDest->iSDParm = iParm;
|
|
pDest->affSdst = 0;
|
|
pDest->iSdst = 0;
|
|
pDest->nSdst = 0;
|
|
}
|
|
|
|
|
|
/*
|
|
** Allocate a new Select structure and return a pointer to that
|
|
** structure.
|
|
*/
|
|
Select *sqlite3SelectNew(
|
|
Parse *pParse, /* Parsing context */
|
|
ExprList *pEList, /* which columns to include in the result */
|
|
SrcList *pSrc, /* the FROM clause -- which tables to scan */
|
|
Expr *pWhere, /* the WHERE clause */
|
|
ExprList *pGroupBy, /* the GROUP BY clause */
|
|
Expr *pHaving, /* the HAVING clause */
|
|
ExprList *pOrderBy, /* the ORDER BY clause */
|
|
u16 selFlags, /* Flag parameters, such as SF_Distinct */
|
|
Expr *pLimit, /* LIMIT value. NULL means not used */
|
|
Expr *pOffset /* OFFSET value. NULL means no offset */
|
|
#ifdef MAXSCALE
|
|
,
|
|
ExprList *pInto /* the INTO clause */
|
|
#endif
|
|
){
|
|
Select *pNew;
|
|
Select standin;
|
|
sqlite3 *db = pParse->db;
|
|
pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
|
|
if( pNew==0 ){
|
|
assert( db->mallocFailed );
|
|
pNew = &standin;
|
|
}
|
|
if( pEList==0 ){
|
|
#ifndef MAXSCALE
|
|
pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
|
|
#endif
|
|
}
|
|
pNew->pEList = pEList;
|
|
pNew->op = TK_SELECT;
|
|
pNew->selFlags = selFlags;
|
|
pNew->iLimit = 0;
|
|
pNew->iOffset = 0;
|
|
#if SELECTTRACE_ENABLED
|
|
pNew->zSelName[0] = 0;
|
|
#endif
|
|
pNew->addrOpenEphm[0] = -1;
|
|
pNew->addrOpenEphm[1] = -1;
|
|
pNew->nSelectRow = 0;
|
|
if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
|
|
pNew->pSrc = pSrc;
|
|
pNew->pWhere = pWhere;
|
|
pNew->pGroupBy = pGroupBy;
|
|
pNew->pHaving = pHaving;
|
|
pNew->pOrderBy = pOrderBy;
|
|
pNew->pPrior = 0;
|
|
pNew->pNext = 0;
|
|
pNew->pLimit = pLimit;
|
|
pNew->pOffset = pOffset;
|
|
pNew->pWith = 0;
|
|
#ifdef MAXSCALE
|
|
pNew->pInto = pInto;
|
|
#endif
|
|
assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
|
|
if( db->mallocFailed ) {
|
|
clearSelect(db, pNew, pNew!=&standin);
|
|
pNew = 0;
|
|
}else{
|
|
assert( pNew->pSrc!=0 || pParse->nErr>0 );
|
|
}
|
|
assert( pNew!=&standin );
|
|
return pNew;
|
|
}
|
|
|
|
#if SELECTTRACE_ENABLED
|
|
/*
|
|
** Set the name of a Select object
|
|
*/
|
|
void sqlite3SelectSetName(Select *p, const char *zName){
|
|
if( p && zName ){
|
|
sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
|
|
}
|
|
}
|
|
#endif
|
|
|
|
|
|
/*
|
|
** Delete the given Select structure and all of its substructures.
|
|
*/
|
|
void sqlite3SelectDelete(sqlite3 *db, Select *p){
|
|
clearSelect(db, p, 1);
|
|
}
|
|
|
|
/*
|
|
** Return a pointer to the right-most SELECT statement in a compound.
|
|
*/
|
|
static Select *findRightmost(Select *p){
|
|
while( p->pNext ) p = p->pNext;
|
|
return p;
|
|
}
|
|
|
|
/*
|
|
** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
|
|
** type of join. Return an integer constant that expresses that type
|
|
** in terms of the following bit values:
|
|
**
|
|
** JT_INNER
|
|
** JT_CROSS
|
|
** JT_OUTER
|
|
** JT_NATURAL
|
|
** JT_LEFT
|
|
** JT_RIGHT
|
|
**
|
|
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
|
|
**
|
|
** If an illegal or unsupported join type is seen, then still return
|
|
** a join type, but put an error in the pParse structure.
|
|
*/
|
|
int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
|
|
int jointype = 0;
|
|
Token *apAll[3];
|
|
Token *p;
|
|
/* 0123456789 123456789 123456789 123 */
|
|
static const char zKeyText[] = "naturaleftouterightfullinnercross";
|
|
static const struct {
|
|
u8 i; /* Beginning of keyword text in zKeyText[] */
|
|
u8 nChar; /* Length of the keyword in characters */
|
|
u8 code; /* Join type mask */
|
|
} aKeyword[] = {
|
|
/* natural */ { 0, 7, JT_NATURAL },
|
|
/* left */ { 6, 4, JT_LEFT|JT_OUTER },
|
|
/* outer */ { 10, 5, JT_OUTER },
|
|
/* right */ { 14, 5, JT_RIGHT|JT_OUTER },
|
|
/* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
|
|
/* inner */ { 23, 5, JT_INNER },
|
|
/* cross */ { 28, 5, JT_INNER|JT_CROSS },
|
|
};
|
|
int i, j;
|
|
apAll[0] = pA;
|
|
apAll[1] = pB;
|
|
apAll[2] = pC;
|
|
for(i=0; i<3 && apAll[i]; i++){
|
|
p = apAll[i];
|
|
for(j=0; j<ArraySize(aKeyword); j++){
|
|
if( p->n==aKeyword[j].nChar
|
|
&& sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
|
|
jointype |= aKeyword[j].code;
|
|
break;
|
|
}
|
|
}
|
|
testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
|
|
if( j>=ArraySize(aKeyword) ){
|
|
jointype |= JT_ERROR;
|
|
break;
|
|
}
|
|
}
|
|
if(
|
|
(jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
|
|
(jointype & JT_ERROR)!=0
|
|
){
|
|
const char *zSp = " ";
|
|
assert( pB!=0 );
|
|
if( pC==0 ){ zSp++; }
|
|
sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
|
|
"%T %T%s%T", pA, pB, zSp, pC);
|
|
jointype = JT_INNER;
|
|
}else if( (jointype & JT_OUTER)!=0
|
|
&& (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
|
|
#ifndef MAXSCALE
|
|
sqlite3ErrorMsg(pParse,
|
|
"RIGHT and FULL OUTER JOINs are not currently supported");
|
|
#endif
|
|
jointype = JT_INNER;
|
|
}
|
|
return jointype;
|
|
}
|
|
|
|
/*
|
|
** Return the index of a column in a table. Return -1 if the column
|
|
** is not contained in the table.
|
|
*/
|
|
static int columnIndex(Table *pTab, const char *zCol){
|
|
int i;
|
|
for(i=0; i<pTab->nCol; i++){
|
|
if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
** Search the first N tables in pSrc, from left to right, looking for a
|
|
** table that has a column named zCol.
|
|
**
|
|
** When found, set *piTab and *piCol to the table index and column index
|
|
** of the matching column and return TRUE.
|
|
**
|
|
** If not found, return FALSE.
|
|
*/
|
|
static int tableAndColumnIndex(
|
|
SrcList *pSrc, /* Array of tables to search */
|
|
int N, /* Number of tables in pSrc->a[] to search */
|
|
const char *zCol, /* Name of the column we are looking for */
|
|
int *piTab, /* Write index of pSrc->a[] here */
|
|
int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
|
|
){
|
|
int i; /* For looping over tables in pSrc */
|
|
int iCol; /* Index of column matching zCol */
|
|
|
|
assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
|
|
for(i=0; i<N; i++){
|
|
iCol = columnIndex(pSrc->a[i].pTab, zCol);
|
|
if( iCol>=0 ){
|
|
if( piTab ){
|
|
*piTab = i;
|
|
*piCol = iCol;
|
|
}
|
|
return 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/*
|
|
** This function is used to add terms implied by JOIN syntax to the
|
|
** WHERE clause expression of a SELECT statement. The new term, which
|
|
** is ANDed with the existing WHERE clause, is of the form:
|
|
**
|
|
** (tab1.col1 = tab2.col2)
|
|
**
|
|
** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
|
|
** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
|
|
** column iColRight of tab2.
|
|
*/
|
|
static void addWhereTerm(
|
|
Parse *pParse, /* Parsing context */
|
|
SrcList *pSrc, /* List of tables in FROM clause */
|
|
int iLeft, /* Index of first table to join in pSrc */
|
|
int iColLeft, /* Index of column in first table */
|
|
int iRight, /* Index of second table in pSrc */
|
|
int iColRight, /* Index of column in second table */
|
|
int isOuterJoin, /* True if this is an OUTER join */
|
|
Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
|
|
){
|
|
sqlite3 *db = pParse->db;
|
|
Expr *pE1;
|
|
Expr *pE2;
|
|
Expr *pEq;
|
|
|
|
assert( iLeft<iRight );
|
|
assert( pSrc->nSrc>iRight );
|
|
assert( pSrc->a[iLeft].pTab );
|
|
assert( pSrc->a[iRight].pTab );
|
|
|
|
pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
|
|
pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
|
|
|
|
pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
|
|
if( pEq && isOuterJoin ){
|
|
ExprSetProperty(pEq, EP_FromJoin);
|
|
assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
|
|
ExprSetVVAProperty(pEq, EP_NoReduce);
|
|
pEq->iRightJoinTable = (i16)pE2->iTable;
|
|
}
|
|
*ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
|
|
}
|
|
|
|
/*
|
|
** Set the EP_FromJoin property on all terms of the given expression.
|
|
** And set the Expr.iRightJoinTable to iTable for every term in the
|
|
** expression.
|
|
**
|
|
** The EP_FromJoin property is used on terms of an expression to tell
|
|
** the LEFT OUTER JOIN processing logic that this term is part of the
|
|
** join restriction specified in the ON or USING clause and not a part
|
|
** of the more general WHERE clause. These terms are moved over to the
|
|
** WHERE clause during join processing but we need to remember that they
|
|
** originated in the ON or USING clause.
|
|
**
|
|
** The Expr.iRightJoinTable tells the WHERE clause processing that the
|
|
** expression depends on table iRightJoinTable even if that table is not
|
|
** explicitly mentioned in the expression. That information is needed
|
|
** for cases like this:
|
|
**
|
|
** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
|
|
**
|
|
** The where clause needs to defer the handling of the t1.x=5
|
|
** term until after the t2 loop of the join. In that way, a
|
|
** NULL t2 row will be inserted whenever t1.x!=5. If we do not
|
|
** defer the handling of t1.x=5, it will be processed immediately
|
|
** after the t1 loop and rows with t1.x!=5 will never appear in
|
|
** the output, which is incorrect.
|
|
*/
|
|
static void setJoinExpr(Expr *p, int iTable){
|
|
while( p ){
|
|
ExprSetProperty(p, EP_FromJoin);
|
|
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
|
|
ExprSetVVAProperty(p, EP_NoReduce);
|
|
p->iRightJoinTable = (i16)iTable;
|
|
if( p->op==TK_FUNCTION && p->x.pList ){
|
|
int i;
|
|
for(i=0; i<p->x.pList->nExpr; i++){
|
|
setJoinExpr(p->x.pList->a[i].pExpr, iTable);
|
|
}
|
|
}
|
|
setJoinExpr(p->pLeft, iTable);
|
|
p = p->pRight;
|
|
}
|
|
}
|
|
|
|
/*
|
|
** This routine processes the join information for a SELECT statement.
|
|
** ON and USING clauses are converted into extra terms of the WHERE clause.
|
|
** NATURAL joins also create extra WHERE clause terms.
|
|
**
|
|
** The terms of a FROM clause are contained in the Select.pSrc structure.
|
|
** The left most table is the first entry in Select.pSrc. The right-most
|
|
** table is the last entry. The join operator is held in the entry to
|
|
** the left. Thus entry 0 contains the join operator for the join between
|
|
** entries 0 and 1. Any ON or USING clauses associated with the join are
|
|
** also attached to the left entry.
|
|
**
|
|
** This routine returns the number of errors encountered.
|
|
*/
|
|
static int sqliteProcessJoin(Parse *pParse, Select *p){
|
|
SrcList *pSrc; /* All tables in the FROM clause */
|
|
int i, j; /* Loop counters */
|
|
struct SrcList_item *pLeft; /* Left table being joined */
|
|
struct SrcList_item *pRight; /* Right table being joined */
|
|
|
|
pSrc = p->pSrc;
|
|
pLeft = &pSrc->a[0];
|
|
pRight = &pLeft[1];
|
|
for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
|
|
Table *pLeftTab = pLeft->pTab;
|
|
Table *pRightTab = pRight->pTab;
|
|
int isOuter;
|
|
|
|
if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
|
|
isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
|
|
|
|
/* When the NATURAL keyword is present, add WHERE clause terms for
|
|
** every column that the two tables have in common.
|
|
*/
|
|
if( pRight->fg.jointype & JT_NATURAL ){
|
|
if( pRight->pOn || pRight->pUsing ){
|
|
sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
|
|
"an ON or USING clause", 0);
|
|
return 1;
|
|
}
|
|
for(j=0; j<pRightTab->nCol; j++){
|
|
char *zName; /* Name of column in the right table */
|
|
int iLeft; /* Matching left table */
|
|
int iLeftCol; /* Matching column in the left table */
|
|
|
|
zName = pRightTab->aCol[j].zName;
|
|
if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
|
|
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
|
|
isOuter, &p->pWhere);
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Disallow both ON and USING clauses in the same join
|
|
*/
|
|
if( pRight->pOn && pRight->pUsing ){
|
|
sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
|
|
"clauses in the same join");
|
|
return 1;
|
|
}
|
|
|
|
/* Add the ON clause to the end of the WHERE clause, connected by
|
|
** an AND operator.
|
|
*/
|
|
if( pRight->pOn ){
|
|
if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
|
|
p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
|
|
pRight->pOn = 0;
|
|
}
|
|
|
|
/* Create extra terms on the WHERE clause for each column named
|
|
** in the USING clause. Example: If the two tables to be joined are
|
|
** A and B and the USING clause names X, Y, and Z, then add this
|
|
** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
|
|
** Report an error if any column mentioned in the USING clause is
|
|
** not contained in both tables to be joined.
|
|
*/
|
|
if( pRight->pUsing ){
|
|
IdList *pList = pRight->pUsing;
|
|
for(j=0; j<pList->nId; j++){
|
|
char *zName; /* Name of the term in the USING clause */
|
|
int iLeft; /* Table on the left with matching column name */
|
|
int iLeftCol; /* Column number of matching column on the left */
|
|
int iRightCol; /* Column number of matching column on the right */
|
|
|
|
zName = pList->a[j].zName;
|
|
iRightCol = columnIndex(pRightTab, zName);
|
|
if( iRightCol<0
|
|
|| !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
|
|
){
|
|
sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
|
|
"not present in both tables", zName);
|
|
return 1;
|
|
}
|
|
addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
|
|
isOuter, &p->pWhere);
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* Forward reference */
|
|
static KeyInfo *keyInfoFromExprList(
|
|
Parse *pParse, /* Parsing context */
|
|
ExprList *pList, /* Form the KeyInfo object from this ExprList */
|
|
int iStart, /* Begin with this column of pList */
|
|
int nExtra /* Add this many extra columns to the end */
|
|
);
|
|
|
|
/*
|
|
** Generate code that will push the record in registers regData
|
|
** through regData+nData-1 onto the sorter.
|
|
*/
|
|
static void pushOntoSorter(
|
|
Parse *pParse, /* Parser context */
|
|
SortCtx *pSort, /* Information about the ORDER BY clause */
|
|
Select *pSelect, /* The whole SELECT statement */
|
|
int regData, /* First register holding data to be sorted */
|
|
int regOrigData, /* First register holding data before packing */
|
|
int nData, /* Number of elements in the data array */
|
|
int nPrefixReg /* No. of reg prior to regData available for use */
|
|
){
|
|
Vdbe *v = pParse->pVdbe; /* Stmt under construction */
|
|
int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
|
|
int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
|
|
int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
|
|
int regBase; /* Regs for sorter record */
|
|
int regRecord = ++pParse->nMem; /* Assembled sorter record */
|
|
int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
|
|
int op; /* Opcode to add sorter record to sorter */
|
|
int iLimit; /* LIMIT counter */
|
|
|
|
assert( bSeq==0 || bSeq==1 );
|
|
assert( nData==1 || regData==regOrigData );
|
|
if( nPrefixReg ){
|
|
assert( nPrefixReg==nExpr+bSeq );
|
|
regBase = regData - nExpr - bSeq;
|
|
}else{
|
|
regBase = pParse->nMem + 1;
|
|
pParse->nMem += nBase;
|
|
}
|
|
assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
|
|
iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
|
|
pSort->labelDone = sqlite3VdbeMakeLabel(v);
|
|
sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
|
|
SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
|
|
if( bSeq ){
|
|
sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
|
|
}
|
|
if( nPrefixReg==0 ){
|
|
sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
|
|
if( nOBSat>0 ){
|
|
int regPrevKey; /* The first nOBSat columns of the previous row */
|
|
int addrFirst; /* Address of the OP_IfNot opcode */
|
|
int addrJmp; /* Address of the OP_Jump opcode */
|
|
VdbeOp *pOp; /* Opcode that opens the sorter */
|
|
int nKey; /* Number of sorting key columns, including OP_Sequence */
|
|
KeyInfo *pKI; /* Original KeyInfo on the sorter table */
|
|
|
|
regPrevKey = pParse->nMem+1;
|
|
pParse->nMem += pSort->nOBSat;
|
|
nKey = nExpr - pSort->nOBSat + bSeq;
|
|
if( bSeq ){
|
|
addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
|
|
}else{
|
|
addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
|
|
}
|
|
VdbeCoverage(v);
|
|
sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
|
|
pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
|
|
if( pParse->db->mallocFailed ) return;
|
|
pOp->p2 = nKey + nData;
|
|
pKI = pOp->p4.pKeyInfo;
|
|
memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
|
|
sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
|
|
testcase( pKI->nXField>2 );
|
|
pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
|
|
pKI->nXField-1);
|
|
addrJmp = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
|
|
pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
|
|
pSort->regReturn = ++pParse->nMem;
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
|
|
sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
|
|
if( iLimit ){
|
|
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
|
|
VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeJumpHere(v, addrFirst);
|
|
sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
|
|
sqlite3VdbeJumpHere(v, addrJmp);
|
|
}
|
|
if( pSort->sortFlags & SORTFLAG_UseSorter ){
|
|
op = OP_SorterInsert;
|
|
}else{
|
|
op = OP_IdxInsert;
|
|
}
|
|
sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
|
|
if( iLimit ){
|
|
int addr;
|
|
addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
|
|
sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
|
|
sqlite3VdbeJumpHere(v, addr);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Add code to implement the OFFSET
|
|
*/
|
|
static void codeOffset(
|
|
Vdbe *v, /* Generate code into this VM */
|
|
int iOffset, /* Register holding the offset counter */
|
|
int iContinue /* Jump here to skip the current record */
|
|
){
|
|
if( iOffset>0 ){
|
|
sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
|
|
VdbeComment((v, "OFFSET"));
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Add code that will check to make sure the N registers starting at iMem
|
|
** form a distinct entry. iTab is a sorting index that holds previously
|
|
** seen combinations of the N values. A new entry is made in iTab
|
|
** if the current N values are new.
|
|
**
|
|
** A jump to addrRepeat is made and the N+1 values are popped from the
|
|
** stack if the top N elements are not distinct.
|
|
*/
|
|
static void codeDistinct(
|
|
Parse *pParse, /* Parsing and code generating context */
|
|
int iTab, /* A sorting index used to test for distinctness */
|
|
int addrRepeat, /* Jump to here if not distinct */
|
|
int N, /* Number of elements */
|
|
int iMem /* First element */
|
|
){
|
|
Vdbe *v;
|
|
int r1;
|
|
|
|
v = pParse->pVdbe;
|
|
r1 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
/*
|
|
** Generate an error message when a SELECT is used within a subexpression
|
|
** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
|
|
** column. We do this in a subroutine because the error used to occur
|
|
** in multiple places. (The error only occurs in one place now, but we
|
|
** retain the subroutine to minimize code disruption.)
|
|
*/
|
|
static int checkForMultiColumnSelectError(
|
|
Parse *pParse, /* Parse context. */
|
|
SelectDest *pDest, /* Destination of SELECT results */
|
|
int nExpr /* Number of result columns returned by SELECT */
|
|
){
|
|
int eDest = pDest->eDest;
|
|
if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
|
|
sqlite3ErrorMsg(pParse, "only a single result allowed for "
|
|
"a SELECT that is part of an expression");
|
|
return 1;
|
|
}else{
|
|
return 0;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
/*
|
|
** This routine generates the code for the inside of the inner loop
|
|
** of a SELECT.
|
|
**
|
|
** If srcTab is negative, then the pEList expressions
|
|
** are evaluated in order to get the data for this row. If srcTab is
|
|
** zero or more, then data is pulled from srcTab and pEList is used only
|
|
** to get number columns and the datatype for each column.
|
|
*/
|
|
static void selectInnerLoop(
|
|
Parse *pParse, /* The parser context */
|
|
Select *p, /* The complete select statement being coded */
|
|
ExprList *pEList, /* List of values being extracted */
|
|
int srcTab, /* Pull data from this table */
|
|
SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
|
|
DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
|
|
SelectDest *pDest, /* How to dispose of the results */
|
|
int iContinue, /* Jump here to continue with next row */
|
|
int iBreak /* Jump here to break out of the inner loop */
|
|
){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i;
|
|
int hasDistinct; /* True if the DISTINCT keyword is present */
|
|
int regResult; /* Start of memory holding result set */
|
|
int eDest = pDest->eDest; /* How to dispose of results */
|
|
int iParm = pDest->iSDParm; /* First argument to disposal method */
|
|
int nResultCol; /* Number of result columns */
|
|
int nPrefixReg = 0; /* Number of extra registers before regResult */
|
|
|
|
assert( v );
|
|
assert( pEList!=0 );
|
|
hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
|
|
if( pSort && pSort->pOrderBy==0 ) pSort = 0;
|
|
if( pSort==0 && !hasDistinct ){
|
|
assert( iContinue!=0 );
|
|
codeOffset(v, p->iOffset, iContinue);
|
|
}
|
|
|
|
/* Pull the requested columns.
|
|
*/
|
|
nResultCol = pEList->nExpr;
|
|
|
|
if( pDest->iSdst==0 ){
|
|
if( pSort ){
|
|
nPrefixReg = pSort->pOrderBy->nExpr;
|
|
if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
|
|
pParse->nMem += nPrefixReg;
|
|
}
|
|
pDest->iSdst = pParse->nMem+1;
|
|
pParse->nMem += nResultCol;
|
|
}else if( pDest->iSdst+nResultCol > pParse->nMem ){
|
|
/* This is an error condition that can result, for example, when a SELECT
|
|
** on the right-hand side of an INSERT contains more result columns than
|
|
** there are columns in the table on the left. The error will be caught
|
|
** and reported later. But we need to make sure enough memory is allocated
|
|
** to avoid other spurious errors in the meantime. */
|
|
pParse->nMem += nResultCol;
|
|
}
|
|
pDest->nSdst = nResultCol;
|
|
regResult = pDest->iSdst;
|
|
if( srcTab>=0 ){
|
|
for(i=0; i<nResultCol; i++){
|
|
sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
|
|
VdbeComment((v, "%s", pEList->a[i].zName));
|
|
}
|
|
}else if( eDest!=SRT_Exists ){
|
|
/* If the destination is an EXISTS(...) expression, the actual
|
|
** values returned by the SELECT are not required.
|
|
*/
|
|
u8 ecelFlags;
|
|
if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
|
|
ecelFlags = SQLITE_ECEL_DUP;
|
|
}else{
|
|
ecelFlags = 0;
|
|
}
|
|
sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
|
|
}
|
|
|
|
/* If the DISTINCT keyword was present on the SELECT statement
|
|
** and this row has been seen before, then do not make this row
|
|
** part of the result.
|
|
*/
|
|
if( hasDistinct ){
|
|
switch( pDistinct->eTnctType ){
|
|
case WHERE_DISTINCT_ORDERED: {
|
|
VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
|
|
int iJump; /* Jump destination */
|
|
int regPrev; /* Previous row content */
|
|
|
|
/* Allocate space for the previous row */
|
|
regPrev = pParse->nMem+1;
|
|
pParse->nMem += nResultCol;
|
|
|
|
/* Change the OP_OpenEphemeral coded earlier to an OP_Null
|
|
** sets the MEM_Cleared bit on the first register of the
|
|
** previous value. This will cause the OP_Ne below to always
|
|
** fail on the first iteration of the loop even if the first
|
|
** row is all NULLs.
|
|
*/
|
|
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
|
|
pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
|
|
pOp->opcode = OP_Null;
|
|
pOp->p1 = 1;
|
|
pOp->p2 = regPrev;
|
|
|
|
iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
|
|
for(i=0; i<nResultCol; i++){
|
|
CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
|
|
if( i<nResultCol-1 ){
|
|
sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
|
|
VdbeCoverage(v);
|
|
}else{
|
|
sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
|
|
VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
|
|
sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
|
|
}
|
|
assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
|
|
sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
|
|
break;
|
|
}
|
|
|
|
case WHERE_DISTINCT_UNIQUE: {
|
|
sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
|
|
break;
|
|
}
|
|
|
|
default: {
|
|
assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
|
|
codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
|
|
regResult);
|
|
break;
|
|
}
|
|
}
|
|
if( pSort==0 ){
|
|
codeOffset(v, p->iOffset, iContinue);
|
|
}
|
|
}
|
|
|
|
switch( eDest ){
|
|
/* In this mode, write each query result to the key of the temporary
|
|
** table iParm.
|
|
*/
|
|
#ifndef SQLITE_OMIT_COMPOUND_SELECT
|
|
case SRT_Union: {
|
|
int r1;
|
|
r1 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
break;
|
|
}
|
|
|
|
/* Construct a record from the query result, but instead of
|
|
** saving that record, use it as a key to delete elements from
|
|
** the temporary table iParm.
|
|
*/
|
|
case SRT_Except: {
|
|
sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
|
|
break;
|
|
}
|
|
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
|
|
|
|
/* Store the result as data using a unique key.
|
|
*/
|
|
case SRT_Fifo:
|
|
case SRT_DistFifo:
|
|
case SRT_Table:
|
|
case SRT_EphemTab: {
|
|
int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
|
|
testcase( eDest==SRT_Table );
|
|
testcase( eDest==SRT_EphemTab );
|
|
testcase( eDest==SRT_Fifo );
|
|
testcase( eDest==SRT_DistFifo );
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
|
|
#ifndef SQLITE_OMIT_CTE
|
|
if( eDest==SRT_DistFifo ){
|
|
/* If the destination is DistFifo, then cursor (iParm+1) is open
|
|
** on an ephemeral index. If the current row is already present
|
|
** in the index, do not write it to the output. If not, add the
|
|
** current row to the index and proceed with writing it to the
|
|
** output table as well. */
|
|
int addr = sqlite3VdbeCurrentAddr(v) + 4;
|
|
sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
|
|
VdbeCoverage(v);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
|
|
assert( pSort==0 );
|
|
}
|
|
#endif
|
|
if( pSort ){
|
|
pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
|
|
}else{
|
|
int r2 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
|
|
sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
|
|
sqlite3ReleaseTempReg(pParse, r2);
|
|
}
|
|
sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
|
|
break;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
|
|
** then there should be a single item on the stack. Write this
|
|
** item into the set table with bogus data.
|
|
*/
|
|
case SRT_Set: {
|
|
assert( nResultCol==1 );
|
|
pDest->affSdst =
|
|
sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
|
|
if( pSort ){
|
|
/* At first glance you would think we could optimize out the
|
|
** ORDER BY in this case since the order of entries in the set
|
|
** does not matter. But there might be a LIMIT clause, in which
|
|
** case the order does matter */
|
|
pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
|
|
}else{
|
|
int r1 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
|
|
sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
}
|
|
break;
|
|
}
|
|
|
|
/* If any row exist in the result set, record that fact and abort.
|
|
*/
|
|
case SRT_Exists: {
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
|
|
/* The LIMIT clause will terminate the loop for us */
|
|
break;
|
|
}
|
|
|
|
/* If this is a scalar select that is part of an expression, then
|
|
** store the results in the appropriate memory cell and break out
|
|
** of the scan loop.
|
|
*/
|
|
case SRT_Mem: {
|
|
assert( nResultCol==1 );
|
|
if( pSort ){
|
|
pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
|
|
}else{
|
|
assert( regResult==iParm );
|
|
/* The LIMIT clause will jump out of the loop for us */
|
|
}
|
|
break;
|
|
}
|
|
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
|
|
|
|
case SRT_Coroutine: /* Send data to a co-routine */
|
|
case SRT_Output: { /* Return the results */
|
|
testcase( eDest==SRT_Coroutine );
|
|
testcase( eDest==SRT_Output );
|
|
if( pSort ){
|
|
pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
|
|
nPrefixReg);
|
|
}else if( eDest==SRT_Coroutine ){
|
|
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
|
|
}else{
|
|
sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
|
|
sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
|
|
}
|
|
break;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_CTE
|
|
/* Write the results into a priority queue that is order according to
|
|
** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
|
|
** index with pSO->nExpr+2 columns. Build a key using pSO for the first
|
|
** pSO->nExpr columns, then make sure all keys are unique by adding a
|
|
** final OP_Sequence column. The last column is the record as a blob.
|
|
*/
|
|
case SRT_DistQueue:
|
|
case SRT_Queue: {
|
|
int nKey;
|
|
int r1, r2, r3;
|
|
int addrTest = 0;
|
|
ExprList *pSO;
|
|
pSO = pDest->pOrderBy;
|
|
assert( pSO );
|
|
nKey = pSO->nExpr;
|
|
r1 = sqlite3GetTempReg(pParse);
|
|
r2 = sqlite3GetTempRange(pParse, nKey+2);
|
|
r3 = r2+nKey+1;
|
|
if( eDest==SRT_DistQueue ){
|
|
/* If the destination is DistQueue, then cursor (iParm+1) is open
|
|
** on a second ephemeral index that holds all values every previously
|
|
** added to the queue. */
|
|
addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
|
|
regResult, nResultCol);
|
|
VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
|
|
if( eDest==SRT_DistQueue ){
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
|
|
}
|
|
for(i=0; i<nKey; i++){
|
|
sqlite3VdbeAddOp2(v, OP_SCopy,
|
|
regResult + pSO->a[i].u.x.iOrderByCol - 1,
|
|
r2+i);
|
|
}
|
|
sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
|
|
if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
sqlite3ReleaseTempRange(pParse, r2, nKey+2);
|
|
break;
|
|
}
|
|
#endif /* SQLITE_OMIT_CTE */
|
|
|
|
|
|
|
|
#if !defined(SQLITE_OMIT_TRIGGER)
|
|
/* Discard the results. This is used for SELECT statements inside
|
|
** the body of a TRIGGER. The purpose of such selects is to call
|
|
** user-defined functions that have side effects. We do not care
|
|
** about the actual results of the select.
|
|
*/
|
|
default: {
|
|
assert( eDest==SRT_Discard );
|
|
break;
|
|
}
|
|
#endif
|
|
}
|
|
|
|
/* Jump to the end of the loop if the LIMIT is reached. Except, if
|
|
** there is a sorter, in which case the sorter has already limited
|
|
** the output for us.
|
|
*/
|
|
if( pSort==0 && p->iLimit ){
|
|
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Allocate a KeyInfo object sufficient for an index of N key columns and
|
|
** X extra columns.
|
|
*/
|
|
KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
|
|
int nExtra = (N+X)*(sizeof(CollSeq*)+1);
|
|
KeyInfo *p = sqlite3Malloc(sizeof(KeyInfo) + nExtra);
|
|
if( p ){
|
|
p->aSortOrder = (u8*)&p->aColl[N+X];
|
|
p->nField = (u16)N;
|
|
p->nXField = (u16)X;
|
|
p->enc = ENC(db);
|
|
p->db = db;
|
|
p->nRef = 1;
|
|
memset(&p[1], 0, nExtra);
|
|
}else{
|
|
sqlite3OomFault(db);
|
|
}
|
|
return p;
|
|
}
|
|
|
|
/*
|
|
** Deallocate a KeyInfo object
|
|
*/
|
|
void sqlite3KeyInfoUnref(KeyInfo *p){
|
|
if( p ){
|
|
assert( p->nRef>0 );
|
|
p->nRef--;
|
|
if( p->nRef==0 ) sqlite3DbFree(0, p);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Make a new pointer to a KeyInfo object
|
|
*/
|
|
KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
|
|
if( p ){
|
|
assert( p->nRef>0 );
|
|
p->nRef++;
|
|
}
|
|
return p;
|
|
}
|
|
|
|
#ifdef SQLITE_DEBUG
|
|
/*
|
|
** Return TRUE if a KeyInfo object can be change. The KeyInfo object
|
|
** can only be changed if this is just a single reference to the object.
|
|
**
|
|
** This routine is used only inside of assert() statements.
|
|
*/
|
|
int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
|
|
#endif /* SQLITE_DEBUG */
|
|
|
|
/*
|
|
** Given an expression list, generate a KeyInfo structure that records
|
|
** the collating sequence for each expression in that expression list.
|
|
**
|
|
** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
|
|
** KeyInfo structure is appropriate for initializing a virtual index to
|
|
** implement that clause. If the ExprList is the result set of a SELECT
|
|
** then the KeyInfo structure is appropriate for initializing a virtual
|
|
** index to implement a DISTINCT test.
|
|
**
|
|
** Space to hold the KeyInfo structure is obtained from malloc. The calling
|
|
** function is responsible for seeing that this structure is eventually
|
|
** freed.
|
|
*/
|
|
static KeyInfo *keyInfoFromExprList(
|
|
Parse *pParse, /* Parsing context */
|
|
ExprList *pList, /* Form the KeyInfo object from this ExprList */
|
|
int iStart, /* Begin with this column of pList */
|
|
int nExtra /* Add this many extra columns to the end */
|
|
){
|
|
int nExpr;
|
|
KeyInfo *pInfo;
|
|
struct ExprList_item *pItem;
|
|
sqlite3 *db = pParse->db;
|
|
int i;
|
|
|
|
nExpr = pList->nExpr;
|
|
pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
|
|
if( pInfo ){
|
|
assert( sqlite3KeyInfoIsWriteable(pInfo) );
|
|
for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
|
|
CollSeq *pColl;
|
|
pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
|
|
if( !pColl ) pColl = db->pDfltColl;
|
|
pInfo->aColl[i-iStart] = pColl;
|
|
pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
|
|
}
|
|
}
|
|
return pInfo;
|
|
}
|
|
|
|
/*
|
|
** Name of the connection operator, used for error messages.
|
|
*/
|
|
static const char *selectOpName(int id){
|
|
char *z;
|
|
switch( id ){
|
|
case TK_ALL: z = "UNION ALL"; break;
|
|
case TK_INTERSECT: z = "INTERSECT"; break;
|
|
case TK_EXCEPT: z = "EXCEPT"; break;
|
|
default: z = "UNION"; break;
|
|
}
|
|
return z;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
/*
|
|
** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
|
|
** is a no-op. Otherwise, it adds a single row of output to the EQP result,
|
|
** where the caption is of the form:
|
|
**
|
|
** "USE TEMP B-TREE FOR xxx"
|
|
**
|
|
** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
|
|
** is determined by the zUsage argument.
|
|
*/
|
|
static void explainTempTable(Parse *pParse, const char *zUsage){
|
|
if( pParse->explain==2 ){
|
|
Vdbe *v = pParse->pVdbe;
|
|
char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
|
|
sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Assign expression b to lvalue a. A second, no-op, version of this macro
|
|
** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
|
|
** in sqlite3Select() to assign values to structure member variables that
|
|
** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
|
|
** code with #ifndef directives.
|
|
*/
|
|
# define explainSetInteger(a, b) a = b
|
|
|
|
#else
|
|
/* No-op versions of the explainXXX() functions and macros. */
|
|
# define explainTempTable(y,z)
|
|
# define explainSetInteger(y,z)
|
|
#endif
|
|
|
|
#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
|
|
/*
|
|
** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
|
|
** is a no-op. Otherwise, it adds a single row of output to the EQP result,
|
|
** where the caption is of one of the two forms:
|
|
**
|
|
** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
|
|
** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
|
|
**
|
|
** where iSub1 and iSub2 are the integers passed as the corresponding
|
|
** function parameters, and op is the text representation of the parameter
|
|
** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
|
|
** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
|
|
** false, or the second form if it is true.
|
|
*/
|
|
static void explainComposite(
|
|
Parse *pParse, /* Parse context */
|
|
int op, /* One of TK_UNION, TK_EXCEPT etc. */
|
|
int iSub1, /* Subquery id 1 */
|
|
int iSub2, /* Subquery id 2 */
|
|
int bUseTmp /* True if a temp table was used */
|
|
){
|
|
assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
|
|
if( pParse->explain==2 ){
|
|
Vdbe *v = pParse->pVdbe;
|
|
char *zMsg = sqlite3MPrintf(
|
|
pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
|
|
bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
|
|
);
|
|
sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
|
|
}
|
|
}
|
|
#else
|
|
/* No-op versions of the explainXXX() functions and macros. */
|
|
# define explainComposite(v,w,x,y,z)
|
|
#endif
|
|
|
|
/*
|
|
** If the inner loop was generated using a non-null pOrderBy argument,
|
|
** then the results were placed in a sorter. After the loop is terminated
|
|
** we need to run the sorter and output the results. The following
|
|
** routine generates the code needed to do that.
|
|
*/
|
|
static void generateSortTail(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The SELECT statement */
|
|
SortCtx *pSort, /* Information on the ORDER BY clause */
|
|
int nColumn, /* Number of columns of data */
|
|
SelectDest *pDest /* Write the sorted results here */
|
|
){
|
|
Vdbe *v = pParse->pVdbe; /* The prepared statement */
|
|
int addrBreak = pSort->labelDone; /* Jump here to exit loop */
|
|
int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
|
|
int addr;
|
|
int addrOnce = 0;
|
|
int iTab;
|
|
ExprList *pOrderBy = pSort->pOrderBy;
|
|
int eDest = pDest->eDest;
|
|
int iParm = pDest->iSDParm;
|
|
int regRow;
|
|
int regRowid;
|
|
int nKey;
|
|
int iSortTab; /* Sorter cursor to read from */
|
|
int nSortData; /* Trailing values to read from sorter */
|
|
int i;
|
|
int bSeq; /* True if sorter record includes seq. no. */
|
|
#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
|
|
struct ExprList_item *aOutEx = p->pEList->a;
|
|
#endif
|
|
|
|
assert( addrBreak<0 );
|
|
if( pSort->labelBkOut ){
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
|
|
sqlite3VdbeGoto(v, addrBreak);
|
|
sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
|
|
}
|
|
iTab = pSort->iECursor;
|
|
if( eDest==SRT_Output || eDest==SRT_Coroutine ){
|
|
regRowid = 0;
|
|
regRow = pDest->iSdst;
|
|
nSortData = nColumn;
|
|
}else{
|
|
regRowid = sqlite3GetTempReg(pParse);
|
|
regRow = sqlite3GetTempReg(pParse);
|
|
nSortData = 1;
|
|
}
|
|
nKey = pOrderBy->nExpr - pSort->nOBSat;
|
|
if( pSort->sortFlags & SORTFLAG_UseSorter ){
|
|
int regSortOut = ++pParse->nMem;
|
|
iSortTab = pParse->nTab++;
|
|
if( pSort->labelBkOut ){
|
|
addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
|
|
if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
|
|
addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
|
|
VdbeCoverage(v);
|
|
codeOffset(v, p->iOffset, addrContinue);
|
|
sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
|
|
bSeq = 0;
|
|
}else{
|
|
addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
|
|
codeOffset(v, p->iOffset, addrContinue);
|
|
iSortTab = iTab;
|
|
bSeq = 1;
|
|
}
|
|
for(i=0; i<nSortData; i++){
|
|
sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
|
|
VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
|
|
}
|
|
switch( eDest ){
|
|
case SRT_EphemTab: {
|
|
sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
|
|
sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
|
|
break;
|
|
}
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
case SRT_Set: {
|
|
assert( nColumn==1 );
|
|
sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
|
|
&pDest->affSdst, 1);
|
|
sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
|
|
break;
|
|
}
|
|
case SRT_Mem: {
|
|
assert( nColumn==1 );
|
|
sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
|
|
/* The LIMIT clause will terminate the loop for us */
|
|
break;
|
|
}
|
|
#endif
|
|
default: {
|
|
assert( eDest==SRT_Output || eDest==SRT_Coroutine );
|
|
testcase( eDest==SRT_Output );
|
|
testcase( eDest==SRT_Coroutine );
|
|
if( eDest==SRT_Output ){
|
|
sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
|
|
sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
|
|
}else{
|
|
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
if( regRowid ){
|
|
sqlite3ReleaseTempReg(pParse, regRow);
|
|
sqlite3ReleaseTempReg(pParse, regRowid);
|
|
}
|
|
/* The bottom of the loop
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, addrContinue);
|
|
if( pSort->sortFlags & SORTFLAG_UseSorter ){
|
|
sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
|
|
}else{
|
|
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
|
|
}
|
|
if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
|
|
sqlite3VdbeResolveLabel(v, addrBreak);
|
|
}
|
|
|
|
/*
|
|
** Return a pointer to a string containing the 'declaration type' of the
|
|
** expression pExpr. The string may be treated as static by the caller.
|
|
**
|
|
** Also try to estimate the size of the returned value and return that
|
|
** result in *pEstWidth.
|
|
**
|
|
** The declaration type is the exact datatype definition extracted from the
|
|
** original CREATE TABLE statement if the expression is a column. The
|
|
** declaration type for a ROWID field is INTEGER. Exactly when an expression
|
|
** is considered a column can be complex in the presence of subqueries. The
|
|
** result-set expression in all of the following SELECT statements is
|
|
** considered a column by this function.
|
|
**
|
|
** SELECT col FROM tbl;
|
|
** SELECT (SELECT col FROM tbl;
|
|
** SELECT (SELECT col FROM tbl);
|
|
** SELECT abc FROM (SELECT col AS abc FROM tbl);
|
|
**
|
|
** The declaration type for any expression other than a column is NULL.
|
|
**
|
|
** This routine has either 3 or 6 parameters depending on whether or not
|
|
** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
|
|
*/
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
|
|
#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
|
|
# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
|
|
#endif
|
|
static const char *columnTypeImpl(
|
|
NameContext *pNC,
|
|
Expr *pExpr,
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
const char **pzOrigDb,
|
|
const char **pzOrigTab,
|
|
const char **pzOrigCol,
|
|
#endif
|
|
u8 *pEstWidth
|
|
){
|
|
char const *zType = 0;
|
|
int j;
|
|
u8 estWidth = 1;
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
char const *zOrigDb = 0;
|
|
char const *zOrigTab = 0;
|
|
char const *zOrigCol = 0;
|
|
#endif
|
|
|
|
assert( pExpr!=0 );
|
|
assert( pNC->pSrcList!=0 );
|
|
switch( pExpr->op ){
|
|
case TK_AGG_COLUMN:
|
|
case TK_COLUMN: {
|
|
/* The expression is a column. Locate the table the column is being
|
|
** extracted from in NameContext.pSrcList. This table may be real
|
|
** database table or a subquery.
|
|
*/
|
|
Table *pTab = 0; /* Table structure column is extracted from */
|
|
Select *pS = 0; /* Select the column is extracted from */
|
|
int iCol = pExpr->iColumn; /* Index of column in pTab */
|
|
testcase( pExpr->op==TK_AGG_COLUMN );
|
|
testcase( pExpr->op==TK_COLUMN );
|
|
while( pNC && !pTab ){
|
|
SrcList *pTabList = pNC->pSrcList;
|
|
for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
|
|
if( j<pTabList->nSrc ){
|
|
pTab = pTabList->a[j].pTab;
|
|
pS = pTabList->a[j].pSelect;
|
|
}else{
|
|
pNC = pNC->pNext;
|
|
}
|
|
}
|
|
|
|
if( pTab==0 ){
|
|
/* At one time, code such as "SELECT new.x" within a trigger would
|
|
** cause this condition to run. Since then, we have restructured how
|
|
** trigger code is generated and so this condition is no longer
|
|
** possible. However, it can still be true for statements like
|
|
** the following:
|
|
**
|
|
** CREATE TABLE t1(col INTEGER);
|
|
** SELECT (SELECT t1.col) FROM FROM t1;
|
|
**
|
|
** when columnType() is called on the expression "t1.col" in the
|
|
** sub-select. In this case, set the column type to NULL, even
|
|
** though it should really be "INTEGER".
|
|
**
|
|
** This is not a problem, as the column type of "t1.col" is never
|
|
** used. When columnType() is called on the expression
|
|
** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
|
|
** branch below. */
|
|
break;
|
|
}
|
|
|
|
assert( pTab && pExpr->pTab==pTab );
|
|
if( pS ){
|
|
/* The "table" is actually a sub-select or a view in the FROM clause
|
|
** of the SELECT statement. Return the declaration type and origin
|
|
** data for the result-set column of the sub-select.
|
|
*/
|
|
if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
|
|
/* If iCol is less than zero, then the expression requests the
|
|
** rowid of the sub-select or view. This expression is legal (see
|
|
** test case misc2.2.2) - it always evaluates to NULL.
|
|
**
|
|
** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
|
|
** caught already by name resolution.
|
|
*/
|
|
NameContext sNC;
|
|
Expr *p = pS->pEList->a[iCol].pExpr;
|
|
sNC.pSrcList = pS->pSrc;
|
|
sNC.pNext = pNC;
|
|
sNC.pParse = pNC->pParse;
|
|
zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
|
|
}
|
|
}else if( pTab->pSchema ){
|
|
/* A real table */
|
|
assert( !pS );
|
|
if( iCol<0 ) iCol = pTab->iPKey;
|
|
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
if( iCol<0 ){
|
|
zType = "INTEGER";
|
|
zOrigCol = "rowid";
|
|
}else{
|
|
zType = pTab->aCol[iCol].zType;
|
|
zOrigCol = pTab->aCol[iCol].zName;
|
|
estWidth = pTab->aCol[iCol].szEst;
|
|
}
|
|
zOrigTab = pTab->zName;
|
|
if( pNC->pParse ){
|
|
int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
|
|
zOrigDb = pNC->pParse->db->aDb[iDb].zName;
|
|
}
|
|
#else
|
|
if( iCol<0 ){
|
|
zType = "INTEGER";
|
|
}else{
|
|
zType = pTab->aCol[iCol].zType;
|
|
estWidth = pTab->aCol[iCol].szEst;
|
|
}
|
|
#endif
|
|
}
|
|
break;
|
|
}
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
case TK_SELECT: {
|
|
/* The expression is a sub-select. Return the declaration type and
|
|
** origin info for the single column in the result set of the SELECT
|
|
** statement.
|
|
*/
|
|
NameContext sNC;
|
|
Select *pS = pExpr->x.pSelect;
|
|
Expr *p = pS->pEList->a[0].pExpr;
|
|
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
|
|
sNC.pSrcList = pS->pSrc;
|
|
sNC.pNext = pNC;
|
|
sNC.pParse = pNC->pParse;
|
|
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
|
|
break;
|
|
}
|
|
#endif
|
|
}
|
|
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
if( pzOrigDb ){
|
|
assert( pzOrigTab && pzOrigCol );
|
|
*pzOrigDb = zOrigDb;
|
|
*pzOrigTab = zOrigTab;
|
|
*pzOrigCol = zOrigCol;
|
|
}
|
|
#endif
|
|
if( pEstWidth ) *pEstWidth = estWidth;
|
|
return zType;
|
|
}
|
|
|
|
/*
|
|
** Generate code that will tell the VDBE the declaration types of columns
|
|
** in the result set.
|
|
*/
|
|
static void generateColumnTypes(
|
|
Parse *pParse, /* Parser context */
|
|
SrcList *pTabList, /* List of tables */
|
|
ExprList *pEList /* Expressions defining the result set */
|
|
){
|
|
#ifndef SQLITE_OMIT_DECLTYPE
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i;
|
|
NameContext sNC;
|
|
sNC.pSrcList = pTabList;
|
|
sNC.pParse = pParse;
|
|
for(i=0; i<pEList->nExpr; i++){
|
|
Expr *p = pEList->a[i].pExpr;
|
|
const char *zType;
|
|
#ifdef SQLITE_ENABLE_COLUMN_METADATA
|
|
const char *zOrigDb = 0;
|
|
const char *zOrigTab = 0;
|
|
const char *zOrigCol = 0;
|
|
zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
|
|
|
|
/* The vdbe must make its own copy of the column-type and other
|
|
** column specific strings, in case the schema is reset before this
|
|
** virtual machine is deleted.
|
|
*/
|
|
sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
|
|
sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
|
|
sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
|
|
#else
|
|
zType = columnType(&sNC, p, 0, 0, 0, 0);
|
|
#endif
|
|
sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
|
|
}
|
|
#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
|
|
}
|
|
|
|
/*
|
|
** Generate code that will tell the VDBE the names of columns
|
|
** in the result set. This information is used to provide the
|
|
** azCol[] values in the callback.
|
|
*/
|
|
static void generateColumnNames(
|
|
Parse *pParse, /* Parser context */
|
|
SrcList *pTabList, /* List of tables */
|
|
ExprList *pEList /* Expressions defining the result set */
|
|
){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i, j;
|
|
sqlite3 *db = pParse->db;
|
|
int fullNames, shortNames;
|
|
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
/* If this is an EXPLAIN, skip this step */
|
|
if( pParse->explain ){
|
|
return;
|
|
}
|
|
#endif
|
|
|
|
if( pParse->colNamesSet || db->mallocFailed ) return;
|
|
assert( v!=0 );
|
|
assert( pTabList!=0 );
|
|
pParse->colNamesSet = 1;
|
|
fullNames = (db->flags & SQLITE_FullColNames)!=0;
|
|
shortNames = (db->flags & SQLITE_ShortColNames)!=0;
|
|
sqlite3VdbeSetNumCols(v, pEList->nExpr);
|
|
for(i=0; i<pEList->nExpr; i++){
|
|
Expr *p;
|
|
p = pEList->a[i].pExpr;
|
|
if( NEVER(p==0) ) continue;
|
|
if( pEList->a[i].zName ){
|
|
char *zName = pEList->a[i].zName;
|
|
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
|
|
}else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
|
|
Table *pTab;
|
|
char *zCol;
|
|
int iCol = p->iColumn;
|
|
for(j=0; ALWAYS(j<pTabList->nSrc); j++){
|
|
if( pTabList->a[j].iCursor==p->iTable ) break;
|
|
}
|
|
assert( j<pTabList->nSrc );
|
|
pTab = pTabList->a[j].pTab;
|
|
if( iCol<0 ) iCol = pTab->iPKey;
|
|
assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
|
|
if( iCol<0 ){
|
|
zCol = "rowid";
|
|
}else{
|
|
zCol = pTab->aCol[iCol].zName;
|
|
}
|
|
if( !shortNames && !fullNames ){
|
|
sqlite3VdbeSetColName(v, i, COLNAME_NAME,
|
|
sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
|
|
}else if( fullNames ){
|
|
char *zName = 0;
|
|
zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
|
|
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
|
|
}else{
|
|
sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
|
|
}
|
|
}else{
|
|
const char *z = pEList->a[i].zSpan;
|
|
z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
|
|
sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
|
|
}
|
|
}
|
|
generateColumnTypes(pParse, pTabList, pEList);
|
|
}
|
|
|
|
/*
|
|
** Given an expression list (which is really the list of expressions
|
|
** that form the result set of a SELECT statement) compute appropriate
|
|
** column names for a table that would hold the expression list.
|
|
**
|
|
** All column names will be unique.
|
|
**
|
|
** Only the column names are computed. Column.zType, Column.zColl,
|
|
** and other fields of Column are zeroed.
|
|
**
|
|
** Return SQLITE_OK on success. If a memory allocation error occurs,
|
|
** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
|
|
*/
|
|
int sqlite3ColumnsFromExprList(
|
|
Parse *pParse, /* Parsing context */
|
|
ExprList *pEList, /* Expr list from which to derive column names */
|
|
i16 *pnCol, /* Write the number of columns here */
|
|
Column **paCol /* Write the new column list here */
|
|
){
|
|
sqlite3 *db = pParse->db; /* Database connection */
|
|
int i, j; /* Loop counters */
|
|
u32 cnt; /* Index added to make the name unique */
|
|
Column *aCol, *pCol; /* For looping over result columns */
|
|
int nCol; /* Number of columns in the result set */
|
|
Expr *p; /* Expression for a single result column */
|
|
char *zName; /* Column name */
|
|
int nName; /* Size of name in zName[] */
|
|
Hash ht; /* Hash table of column names */
|
|
|
|
sqlite3HashInit(&ht);
|
|
if( pEList ){
|
|
nCol = pEList->nExpr;
|
|
aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
|
|
testcase( aCol==0 );
|
|
}else{
|
|
nCol = 0;
|
|
aCol = 0;
|
|
}
|
|
assert( nCol==(i16)nCol );
|
|
*pnCol = nCol;
|
|
*paCol = aCol;
|
|
|
|
for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
|
|
/* Get an appropriate name for the column
|
|
*/
|
|
p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
|
|
if( (zName = pEList->a[i].zName)!=0 ){
|
|
/* If the column contains an "AS <name>" phrase, use <name> as the name */
|
|
}else{
|
|
Expr *pColExpr = p; /* The expression that is the result column name */
|
|
Table *pTab; /* Table associated with this expression */
|
|
while( pColExpr->op==TK_DOT ){
|
|
pColExpr = pColExpr->pRight;
|
|
assert( pColExpr!=0 );
|
|
}
|
|
if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
|
|
/* For columns use the column name name */
|
|
int iCol = pColExpr->iColumn;
|
|
pTab = pColExpr->pTab;
|
|
if( iCol<0 ) iCol = pTab->iPKey;
|
|
zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
|
|
}else if( pColExpr->op==TK_ID ){
|
|
assert( !ExprHasProperty(pColExpr, EP_IntValue) );
|
|
zName = pColExpr->u.zToken;
|
|
}else{
|
|
/* Use the original text of the column expression as its name */
|
|
zName = pEList->a[i].zSpan;
|
|
}
|
|
}
|
|
zName = sqlite3MPrintf(db, "%s", zName);
|
|
|
|
/* Make sure the column name is unique. If the name is not unique,
|
|
** append an integer to the name so that it becomes unique.
|
|
*/
|
|
cnt = 0;
|
|
while( zName && sqlite3HashFind(&ht, zName)!=0 ){
|
|
nName = sqlite3Strlen30(zName);
|
|
if( nName>0 ){
|
|
for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
|
|
if( zName[j]==':' ) nName = j;
|
|
}
|
|
zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
|
|
if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
|
|
}
|
|
pCol->zName = zName;
|
|
sqlite3ColumnPropertiesFromName(0, pCol);
|
|
if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
|
|
sqlite3OomFault(db);
|
|
}
|
|
}
|
|
sqlite3HashClear(&ht);
|
|
if( db->mallocFailed ){
|
|
for(j=0; j<i; j++){
|
|
sqlite3DbFree(db, aCol[j].zName);
|
|
}
|
|
sqlite3DbFree(db, aCol);
|
|
*paCol = 0;
|
|
*pnCol = 0;
|
|
return SQLITE_NOMEM;
|
|
}
|
|
return SQLITE_OK;
|
|
}
|
|
|
|
/*
|
|
** Add type and collation information to a column list based on
|
|
** a SELECT statement.
|
|
**
|
|
** The column list presumably came from selectColumnNamesFromExprList().
|
|
** The column list has only names, not types or collations. This
|
|
** routine goes through and adds the types and collations.
|
|
**
|
|
** This routine requires that all identifiers in the SELECT
|
|
** statement be resolved.
|
|
*/
|
|
static void selectAddColumnTypeAndCollation(
|
|
Parse *pParse, /* Parsing contexts */
|
|
Table *pTab, /* Add column type information to this table */
|
|
Select *pSelect /* SELECT used to determine types and collations */
|
|
){
|
|
sqlite3 *db = pParse->db;
|
|
NameContext sNC;
|
|
Column *pCol;
|
|
CollSeq *pColl;
|
|
int i;
|
|
Expr *p;
|
|
struct ExprList_item *a;
|
|
u64 szAll = 0;
|
|
|
|
assert( pSelect!=0 );
|
|
assert( (pSelect->selFlags & SF_Resolved)!=0 );
|
|
assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
|
|
if( db->mallocFailed ) return;
|
|
memset(&sNC, 0, sizeof(sNC));
|
|
sNC.pSrcList = pSelect->pSrc;
|
|
a = pSelect->pEList->a;
|
|
for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
|
|
p = a[i].pExpr;
|
|
if( pCol->zType==0 ){
|
|
pCol->zType = sqlite3DbStrDup(db,
|
|
columnType(&sNC, p,0,0,0, &pCol->szEst));
|
|
}
|
|
szAll += pCol->szEst;
|
|
pCol->affinity = sqlite3ExprAffinity(p);
|
|
if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
|
|
pColl = sqlite3ExprCollSeq(pParse, p);
|
|
if( pColl && pCol->zColl==0 ){
|
|
pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
|
|
}
|
|
}
|
|
pTab->szTabRow = sqlite3LogEst(szAll*4);
|
|
}
|
|
|
|
/*
|
|
** Given a SELECT statement, generate a Table structure that describes
|
|
** the result set of that SELECT.
|
|
*/
|
|
Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
|
|
Table *pTab;
|
|
sqlite3 *db = pParse->db;
|
|
int savedFlags;
|
|
|
|
savedFlags = db->flags;
|
|
db->flags &= ~SQLITE_FullColNames;
|
|
db->flags |= SQLITE_ShortColNames;
|
|
sqlite3SelectPrep(pParse, pSelect, 0);
|
|
if( pParse->nErr ) return 0;
|
|
while( pSelect->pPrior ) pSelect = pSelect->pPrior;
|
|
db->flags = savedFlags;
|
|
pTab = sqlite3DbMallocZero(db, sizeof(Table) );
|
|
if( pTab==0 ){
|
|
return 0;
|
|
}
|
|
/* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
|
|
** is disabled */
|
|
assert( db->lookaside.bDisable );
|
|
pTab->nRef = 1;
|
|
pTab->zName = 0;
|
|
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
|
|
sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
|
|
selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
|
|
pTab->iPKey = -1;
|
|
if( db->mallocFailed ){
|
|
sqlite3DeleteTable(db, pTab);
|
|
return 0;
|
|
}
|
|
return pTab;
|
|
}
|
|
|
|
/*
|
|
** Get a VDBE for the given parser context. Create a new one if necessary.
|
|
** If an error occurs, return NULL and leave a message in pParse.
|
|
*/
|
|
Vdbe *sqlite3GetVdbe(Parse *pParse){
|
|
Vdbe *v = pParse->pVdbe;
|
|
if( v==0 ){
|
|
v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
|
|
if( v ) sqlite3VdbeAddOp0(v, OP_Init);
|
|
if( pParse->pToplevel==0
|
|
&& OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
|
|
){
|
|
pParse->okConstFactor = 1;
|
|
}
|
|
|
|
}
|
|
return v;
|
|
}
|
|
|
|
|
|
/*
|
|
** Compute the iLimit and iOffset fields of the SELECT based on the
|
|
** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
|
|
** that appear in the original SQL statement after the LIMIT and OFFSET
|
|
** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
|
|
** are the integer memory register numbers for counters used to compute
|
|
** the limit and offset. If there is no limit and/or offset, then
|
|
** iLimit and iOffset are negative.
|
|
**
|
|
** This routine changes the values of iLimit and iOffset only if
|
|
** a limit or offset is defined by pLimit and pOffset. iLimit and
|
|
** iOffset should have been preset to appropriate default values (zero)
|
|
** prior to calling this routine.
|
|
**
|
|
** The iOffset register (if it exists) is initialized to the value
|
|
** of the OFFSET. The iLimit register is initialized to LIMIT. Register
|
|
** iOffset+1 is initialized to LIMIT+OFFSET.
|
|
**
|
|
** Only if pLimit!=0 or pOffset!=0 do the limit registers get
|
|
** redefined. The UNION ALL operator uses this property to force
|
|
** the reuse of the same limit and offset registers across multiple
|
|
** SELECT statements.
|
|
*/
|
|
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
|
|
Vdbe *v = 0;
|
|
int iLimit = 0;
|
|
int iOffset;
|
|
int n;
|
|
if( p->iLimit ) return;
|
|
|
|
/*
|
|
** "LIMIT -1" always shows all rows. There is some
|
|
** controversy about what the correct behavior should be.
|
|
** The current implementation interprets "LIMIT 0" to mean
|
|
** no rows.
|
|
*/
|
|
sqlite3ExprCacheClear(pParse);
|
|
assert( p->pOffset==0 || p->pLimit!=0 );
|
|
if( p->pLimit ){
|
|
p->iLimit = iLimit = ++pParse->nMem;
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( v!=0 );
|
|
if( sqlite3ExprIsInteger(p->pLimit, &n) ){
|
|
sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
|
|
VdbeComment((v, "LIMIT counter"));
|
|
if( n==0 ){
|
|
sqlite3VdbeGoto(v, iBreak);
|
|
}else if( n>=0 && p->nSelectRow>(u64)n ){
|
|
p->nSelectRow = n;
|
|
}
|
|
}else{
|
|
sqlite3ExprCode(pParse, p->pLimit, iLimit);
|
|
sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
|
|
VdbeComment((v, "LIMIT counter"));
|
|
sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
|
|
}
|
|
if( p->pOffset ){
|
|
p->iOffset = iOffset = ++pParse->nMem;
|
|
pParse->nMem++; /* Allocate an extra register for limit+offset */
|
|
sqlite3ExprCode(pParse, p->pOffset, iOffset);
|
|
sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
|
|
VdbeComment((v, "OFFSET counter"));
|
|
sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
|
|
VdbeComment((v, "LIMIT+OFFSET"));
|
|
}
|
|
}
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_COMPOUND_SELECT
|
|
/*
|
|
** Return the appropriate collating sequence for the iCol-th column of
|
|
** the result set for the compound-select statement "p". Return NULL if
|
|
** the column has no default collating sequence.
|
|
**
|
|
** The collating sequence for the compound select is taken from the
|
|
** left-most term of the select that has a collating sequence.
|
|
*/
|
|
static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
|
|
CollSeq *pRet;
|
|
if( p->pPrior ){
|
|
pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
|
|
}else{
|
|
pRet = 0;
|
|
}
|
|
assert( iCol>=0 );
|
|
/* iCol must be less than p->pEList->nExpr. Otherwise an error would
|
|
** have been thrown during name resolution and we would not have gotten
|
|
** this far */
|
|
if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
|
|
pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
|
|
}
|
|
return pRet;
|
|
}
|
|
|
|
/*
|
|
** The select statement passed as the second parameter is a compound SELECT
|
|
** with an ORDER BY clause. This function allocates and returns a KeyInfo
|
|
** structure suitable for implementing the ORDER BY.
|
|
**
|
|
** Space to hold the KeyInfo structure is obtained from malloc. The calling
|
|
** function is responsible for ensuring that this structure is eventually
|
|
** freed.
|
|
*/
|
|
static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
|
|
ExprList *pOrderBy = p->pOrderBy;
|
|
int nOrderBy = p->pOrderBy->nExpr;
|
|
sqlite3 *db = pParse->db;
|
|
KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
|
|
if( pRet ){
|
|
int i;
|
|
for(i=0; i<nOrderBy; i++){
|
|
struct ExprList_item *pItem = &pOrderBy->a[i];
|
|
Expr *pTerm = pItem->pExpr;
|
|
CollSeq *pColl;
|
|
|
|
if( pTerm->flags & EP_Collate ){
|
|
pColl = sqlite3ExprCollSeq(pParse, pTerm);
|
|
}else{
|
|
pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
|
|
if( pColl==0 ) pColl = db->pDfltColl;
|
|
pOrderBy->a[i].pExpr =
|
|
sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
|
|
}
|
|
assert( sqlite3KeyInfoIsWriteable(pRet) );
|
|
pRet->aColl[i] = pColl;
|
|
pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
|
|
}
|
|
}
|
|
|
|
return pRet;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_CTE
|
|
/*
|
|
** This routine generates VDBE code to compute the content of a WITH RECURSIVE
|
|
** query of the form:
|
|
**
|
|
** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
|
|
** \___________/ \_______________/
|
|
** p->pPrior p
|
|
**
|
|
**
|
|
** There is exactly one reference to the recursive-table in the FROM clause
|
|
** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
|
|
**
|
|
** The setup-query runs once to generate an initial set of rows that go
|
|
** into a Queue table. Rows are extracted from the Queue table one by
|
|
** one. Each row extracted from Queue is output to pDest. Then the single
|
|
** extracted row (now in the iCurrent table) becomes the content of the
|
|
** recursive-table for a recursive-query run. The output of the recursive-query
|
|
** is added back into the Queue table. Then another row is extracted from Queue
|
|
** and the iteration continues until the Queue table is empty.
|
|
**
|
|
** If the compound query operator is UNION then no duplicate rows are ever
|
|
** inserted into the Queue table. The iDistinct table keeps a copy of all rows
|
|
** that have ever been inserted into Queue and causes duplicates to be
|
|
** discarded. If the operator is UNION ALL, then duplicates are allowed.
|
|
**
|
|
** If the query has an ORDER BY, then entries in the Queue table are kept in
|
|
** ORDER BY order and the first entry is extracted for each cycle. Without
|
|
** an ORDER BY, the Queue table is just a FIFO.
|
|
**
|
|
** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
|
|
** have been output to pDest. A LIMIT of zero means to output no rows and a
|
|
** negative LIMIT means to output all rows. If there is also an OFFSET clause
|
|
** with a positive value, then the first OFFSET outputs are discarded rather
|
|
** than being sent to pDest. The LIMIT count does not begin until after OFFSET
|
|
** rows have been skipped.
|
|
*/
|
|
static void generateWithRecursiveQuery(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The recursive SELECT to be coded */
|
|
SelectDest *pDest /* What to do with query results */
|
|
){
|
|
SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
|
|
int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
|
|
Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
|
|
Select *pSetup = p->pPrior; /* The setup query */
|
|
int addrTop; /* Top of the loop */
|
|
int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
|
|
int iCurrent = 0; /* The Current table */
|
|
int regCurrent; /* Register holding Current table */
|
|
int iQueue; /* The Queue table */
|
|
int iDistinct = 0; /* To ensure unique results if UNION */
|
|
int eDest = SRT_Fifo; /* How to write to Queue */
|
|
SelectDest destQueue; /* SelectDest targetting the Queue table */
|
|
int i; /* Loop counter */
|
|
int rc; /* Result code */
|
|
ExprList *pOrderBy; /* The ORDER BY clause */
|
|
Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
|
|
int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
|
|
|
|
/* Obtain authorization to do a recursive query */
|
|
if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
|
|
|
|
/* Process the LIMIT and OFFSET clauses, if they exist */
|
|
addrBreak = sqlite3VdbeMakeLabel(v);
|
|
computeLimitRegisters(pParse, p, addrBreak);
|
|
pLimit = p->pLimit;
|
|
pOffset = p->pOffset;
|
|
regLimit = p->iLimit;
|
|
regOffset = p->iOffset;
|
|
p->pLimit = p->pOffset = 0;
|
|
p->iLimit = p->iOffset = 0;
|
|
pOrderBy = p->pOrderBy;
|
|
|
|
/* Locate the cursor number of the Current table */
|
|
for(i=0; ALWAYS(i<pSrc->nSrc); i++){
|
|
if( pSrc->a[i].fg.isRecursive ){
|
|
iCurrent = pSrc->a[i].iCursor;
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* Allocate cursors numbers for Queue and Distinct. The cursor number for
|
|
** the Distinct table must be exactly one greater than Queue in order
|
|
** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
|
|
iQueue = pParse->nTab++;
|
|
if( p->op==TK_UNION ){
|
|
eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
|
|
iDistinct = pParse->nTab++;
|
|
}else{
|
|
eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
|
|
}
|
|
sqlite3SelectDestInit(&destQueue, eDest, iQueue);
|
|
|
|
/* Allocate cursors for Current, Queue, and Distinct. */
|
|
regCurrent = ++pParse->nMem;
|
|
sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
|
|
if( pOrderBy ){
|
|
KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
|
|
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
|
|
(char*)pKeyInfo, P4_KEYINFO);
|
|
destQueue.pOrderBy = pOrderBy;
|
|
}else{
|
|
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
|
|
}
|
|
VdbeComment((v, "Queue table"));
|
|
if( iDistinct ){
|
|
p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
|
|
p->selFlags |= SF_UsesEphemeral;
|
|
}
|
|
|
|
/* Detach the ORDER BY clause from the compound SELECT */
|
|
p->pOrderBy = 0;
|
|
|
|
/* Store the results of the setup-query in Queue. */
|
|
pSetup->pNext = 0;
|
|
rc = sqlite3Select(pParse, pSetup, &destQueue);
|
|
pSetup->pNext = p;
|
|
if( rc ) goto end_of_recursive_query;
|
|
|
|
/* Find the next row in the Queue and output that row */
|
|
addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
|
|
|
|
/* Transfer the next row in Queue over to Current */
|
|
sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
|
|
if( pOrderBy ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
|
|
}else{
|
|
sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
|
|
}
|
|
sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
|
|
|
|
/* Output the single row in Current */
|
|
addrCont = sqlite3VdbeMakeLabel(v);
|
|
codeOffset(v, regOffset, addrCont);
|
|
selectInnerLoop(pParse, p, p->pEList, iCurrent,
|
|
0, 0, pDest, addrCont, addrBreak);
|
|
if( regLimit ){
|
|
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
|
|
VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeResolveLabel(v, addrCont);
|
|
|
|
/* Execute the recursive SELECT taking the single row in Current as
|
|
** the value for the recursive-table. Store the results in the Queue.
|
|
*/
|
|
if( p->selFlags & SF_Aggregate ){
|
|
sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
|
|
}else{
|
|
p->pPrior = 0;
|
|
sqlite3Select(pParse, p, &destQueue);
|
|
assert( p->pPrior==0 );
|
|
p->pPrior = pSetup;
|
|
}
|
|
|
|
/* Keep running the loop until the Queue is empty */
|
|
sqlite3VdbeGoto(v, addrTop);
|
|
sqlite3VdbeResolveLabel(v, addrBreak);
|
|
|
|
end_of_recursive_query:
|
|
sqlite3ExprListDelete(pParse->db, p->pOrderBy);
|
|
p->pOrderBy = pOrderBy;
|
|
p->pLimit = pLimit;
|
|
p->pOffset = pOffset;
|
|
return;
|
|
}
|
|
#endif /* SQLITE_OMIT_CTE */
|
|
|
|
/* Forward references */
|
|
static int multiSelectOrderBy(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The right-most of SELECTs to be coded */
|
|
SelectDest *pDest /* What to do with query results */
|
|
);
|
|
|
|
/*
|
|
** Handle the special case of a compound-select that originates from a
|
|
** VALUES clause. By handling this as a special case, we avoid deep
|
|
** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
|
|
** on a VALUES clause.
|
|
**
|
|
** Because the Select object originates from a VALUES clause:
|
|
** (1) It has no LIMIT or OFFSET
|
|
** (2) All terms are UNION ALL
|
|
** (3) There is no ORDER BY clause
|
|
*/
|
|
static int multiSelectValues(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The right-most of SELECTs to be coded */
|
|
SelectDest *pDest /* What to do with query results */
|
|
){
|
|
Select *pPrior;
|
|
int nRow = 1;
|
|
int rc = 0;
|
|
assert( p->selFlags & SF_MultiValue );
|
|
do{
|
|
assert( p->selFlags & SF_Values );
|
|
assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
|
|
assert( p->pLimit==0 );
|
|
assert( p->pOffset==0 );
|
|
assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
|
|
if( p->pPrior==0 ) break;
|
|
assert( p->pPrior->pNext==p );
|
|
p = p->pPrior;
|
|
nRow++;
|
|
}while(1);
|
|
while( p ){
|
|
pPrior = p->pPrior;
|
|
p->pPrior = 0;
|
|
rc = sqlite3Select(pParse, p, pDest);
|
|
p->pPrior = pPrior;
|
|
if( rc ) break;
|
|
p->nSelectRow = nRow;
|
|
p = p->pNext;
|
|
}
|
|
return rc;
|
|
}
|
|
|
|
/*
|
|
** This routine is called to process a compound query form from
|
|
** two or more separate queries using UNION, UNION ALL, EXCEPT, or
|
|
** INTERSECT
|
|
**
|
|
** "p" points to the right-most of the two queries. the query on the
|
|
** left is p->pPrior. The left query could also be a compound query
|
|
** in which case this routine will be called recursively.
|
|
**
|
|
** The results of the total query are to be written into a destination
|
|
** of type eDest with parameter iParm.
|
|
**
|
|
** Example 1: Consider a three-way compound SQL statement.
|
|
**
|
|
** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
|
|
**
|
|
** This statement is parsed up as follows:
|
|
**
|
|
** SELECT c FROM t3
|
|
** |
|
|
** `-----> SELECT b FROM t2
|
|
** |
|
|
** `------> SELECT a FROM t1
|
|
**
|
|
** The arrows in the diagram above represent the Select.pPrior pointer.
|
|
** So if this routine is called with p equal to the t3 query, then
|
|
** pPrior will be the t2 query. p->op will be TK_UNION in this case.
|
|
**
|
|
** Notice that because of the way SQLite parses compound SELECTs, the
|
|
** individual selects always group from left to right.
|
|
*/
|
|
static int multiSelect(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The right-most of SELECTs to be coded */
|
|
SelectDest *pDest /* What to do with query results */
|
|
){
|
|
int rc = SQLITE_OK; /* Success code from a subroutine */
|
|
Select *pPrior; /* Another SELECT immediately to our left */
|
|
Vdbe *v; /* Generate code to this VDBE */
|
|
SelectDest dest; /* Alternative data destination */
|
|
Select *pDelete = 0; /* Chain of simple selects to delete */
|
|
sqlite3 *db; /* Database connection */
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
int iSub1 = 0; /* EQP id of left-hand query */
|
|
int iSub2 = 0; /* EQP id of right-hand query */
|
|
#endif
|
|
|
|
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
|
|
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
|
|
*/
|
|
assert( p && p->pPrior ); /* Calling function guarantees this much */
|
|
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
|
|
db = pParse->db;
|
|
pPrior = p->pPrior;
|
|
dest = *pDest;
|
|
if( pPrior->pOrderBy ){
|
|
sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
|
|
selectOpName(p->op));
|
|
rc = 1;
|
|
goto multi_select_end;
|
|
}
|
|
if( pPrior->pLimit ){
|
|
sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
|
|
selectOpName(p->op));
|
|
rc = 1;
|
|
goto multi_select_end;
|
|
}
|
|
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( v!=0 ); /* The VDBE already created by calling function */
|
|
|
|
/* Create the destination temporary table if necessary
|
|
*/
|
|
if( dest.eDest==SRT_EphemTab ){
|
|
assert( p->pEList );
|
|
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
|
|
sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
|
|
dest.eDest = SRT_Table;
|
|
}
|
|
|
|
/* Special handling for a compound-select that originates as a VALUES clause.
|
|
*/
|
|
if( p->selFlags & SF_MultiValue ){
|
|
rc = multiSelectValues(pParse, p, &dest);
|
|
goto multi_select_end;
|
|
}
|
|
|
|
/* Make sure all SELECTs in the statement have the same number of elements
|
|
** in their result sets.
|
|
*/
|
|
assert( p->pEList && pPrior->pEList );
|
|
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
|
|
|
|
#ifndef SQLITE_OMIT_CTE
|
|
if( p->selFlags & SF_Recursive ){
|
|
generateWithRecursiveQuery(pParse, p, &dest);
|
|
}else
|
|
#endif
|
|
|
|
/* Compound SELECTs that have an ORDER BY clause are handled separately.
|
|
*/
|
|
if( p->pOrderBy ){
|
|
return multiSelectOrderBy(pParse, p, pDest);
|
|
}else
|
|
|
|
/* Generate code for the left and right SELECT statements.
|
|
*/
|
|
switch( p->op ){
|
|
case TK_ALL: {
|
|
int addr = 0;
|
|
int nLimit;
|
|
assert( !pPrior->pLimit );
|
|
pPrior->iLimit = p->iLimit;
|
|
pPrior->iOffset = p->iOffset;
|
|
pPrior->pLimit = p->pLimit;
|
|
pPrior->pOffset = p->pOffset;
|
|
explainSetInteger(iSub1, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, pPrior, &dest);
|
|
p->pLimit = 0;
|
|
p->pOffset = 0;
|
|
if( rc ){
|
|
goto multi_select_end;
|
|
}
|
|
p->pPrior = 0;
|
|
p->iLimit = pPrior->iLimit;
|
|
p->iOffset = pPrior->iOffset;
|
|
if( p->iLimit ){
|
|
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
|
|
VdbeComment((v, "Jump ahead if LIMIT reached"));
|
|
if( p->iOffset ){
|
|
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
|
|
p->iLimit, p->iOffset+1, p->iOffset);
|
|
}
|
|
}
|
|
explainSetInteger(iSub2, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, p, &dest);
|
|
testcase( rc!=SQLITE_OK );
|
|
pDelete = p->pPrior;
|
|
p->pPrior = pPrior;
|
|
p->nSelectRow += pPrior->nSelectRow;
|
|
if( pPrior->pLimit
|
|
&& sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
|
|
&& nLimit>0 && p->nSelectRow > (u64)nLimit
|
|
){
|
|
p->nSelectRow = nLimit;
|
|
}
|
|
if( addr ){
|
|
sqlite3VdbeJumpHere(v, addr);
|
|
}
|
|
break;
|
|
}
|
|
case TK_EXCEPT:
|
|
case TK_UNION: {
|
|
int unionTab; /* Cursor number of the temporary table holding result */
|
|
u8 op = 0; /* One of the SRT_ operations to apply to self */
|
|
int priorOp; /* The SRT_ operation to apply to prior selects */
|
|
Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
|
|
int addr;
|
|
SelectDest uniondest;
|
|
|
|
testcase( p->op==TK_EXCEPT );
|
|
testcase( p->op==TK_UNION );
|
|
priorOp = SRT_Union;
|
|
if( dest.eDest==priorOp ){
|
|
/* We can reuse a temporary table generated by a SELECT to our
|
|
** right.
|
|
*/
|
|
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
|
|
assert( p->pOffset==0 ); /* Not allowed on leftward elements */
|
|
unionTab = dest.iSDParm;
|
|
}else{
|
|
/* We will need to create our own temporary table to hold the
|
|
** intermediate results.
|
|
*/
|
|
unionTab = pParse->nTab++;
|
|
assert( p->pOrderBy==0 );
|
|
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
|
|
assert( p->addrOpenEphm[0] == -1 );
|
|
p->addrOpenEphm[0] = addr;
|
|
findRightmost(p)->selFlags |= SF_UsesEphemeral;
|
|
assert( p->pEList );
|
|
}
|
|
|
|
/* Code the SELECT statements to our left
|
|
*/
|
|
assert( !pPrior->pOrderBy );
|
|
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
|
|
explainSetInteger(iSub1, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, pPrior, &uniondest);
|
|
if( rc ){
|
|
goto multi_select_end;
|
|
}
|
|
|
|
/* Code the current SELECT statement
|
|
*/
|
|
if( p->op==TK_EXCEPT ){
|
|
op = SRT_Except;
|
|
}else{
|
|
assert( p->op==TK_UNION );
|
|
op = SRT_Union;
|
|
}
|
|
p->pPrior = 0;
|
|
pLimit = p->pLimit;
|
|
p->pLimit = 0;
|
|
pOffset = p->pOffset;
|
|
p->pOffset = 0;
|
|
uniondest.eDest = op;
|
|
explainSetInteger(iSub2, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, p, &uniondest);
|
|
testcase( rc!=SQLITE_OK );
|
|
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
|
|
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
|
|
sqlite3ExprListDelete(db, p->pOrderBy);
|
|
pDelete = p->pPrior;
|
|
p->pPrior = pPrior;
|
|
p->pOrderBy = 0;
|
|
if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
|
|
sqlite3ExprDelete(db, p->pLimit);
|
|
p->pLimit = pLimit;
|
|
p->pOffset = pOffset;
|
|
p->iLimit = 0;
|
|
p->iOffset = 0;
|
|
|
|
/* Convert the data in the temporary table into whatever form
|
|
** it is that we currently need.
|
|
*/
|
|
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
|
|
if( dest.eDest!=priorOp ){
|
|
int iCont, iBreak, iStart;
|
|
assert( p->pEList );
|
|
if( dest.eDest==SRT_Output ){
|
|
Select *pFirst = p;
|
|
while( pFirst->pPrior ) pFirst = pFirst->pPrior;
|
|
generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
|
|
}
|
|
iBreak = sqlite3VdbeMakeLabel(v);
|
|
iCont = sqlite3VdbeMakeLabel(v);
|
|
computeLimitRegisters(pParse, p, iBreak);
|
|
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
|
|
iStart = sqlite3VdbeCurrentAddr(v);
|
|
selectInnerLoop(pParse, p, p->pEList, unionTab,
|
|
0, 0, &dest, iCont, iBreak);
|
|
sqlite3VdbeResolveLabel(v, iCont);
|
|
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
|
|
sqlite3VdbeResolveLabel(v, iBreak);
|
|
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
|
|
}
|
|
break;
|
|
}
|
|
default: assert( p->op==TK_INTERSECT ); {
|
|
int tab1, tab2;
|
|
int iCont, iBreak, iStart;
|
|
Expr *pLimit, *pOffset;
|
|
int addr;
|
|
SelectDest intersectdest;
|
|
int r1;
|
|
|
|
/* INTERSECT is different from the others since it requires
|
|
** two temporary tables. Hence it has its own case. Begin
|
|
** by allocating the tables we will need.
|
|
*/
|
|
tab1 = pParse->nTab++;
|
|
tab2 = pParse->nTab++;
|
|
assert( p->pOrderBy==0 );
|
|
|
|
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
|
|
assert( p->addrOpenEphm[0] == -1 );
|
|
p->addrOpenEphm[0] = addr;
|
|
findRightmost(p)->selFlags |= SF_UsesEphemeral;
|
|
assert( p->pEList );
|
|
|
|
/* Code the SELECTs to our left into temporary table "tab1".
|
|
*/
|
|
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
|
|
explainSetInteger(iSub1, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, pPrior, &intersectdest);
|
|
if( rc ){
|
|
goto multi_select_end;
|
|
}
|
|
|
|
/* Code the current SELECT into temporary table "tab2"
|
|
*/
|
|
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
|
|
assert( p->addrOpenEphm[1] == -1 );
|
|
p->addrOpenEphm[1] = addr;
|
|
p->pPrior = 0;
|
|
pLimit = p->pLimit;
|
|
p->pLimit = 0;
|
|
pOffset = p->pOffset;
|
|
p->pOffset = 0;
|
|
intersectdest.iSDParm = tab2;
|
|
explainSetInteger(iSub2, pParse->iNextSelectId);
|
|
rc = sqlite3Select(pParse, p, &intersectdest);
|
|
testcase( rc!=SQLITE_OK );
|
|
pDelete = p->pPrior;
|
|
p->pPrior = pPrior;
|
|
if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
|
|
sqlite3ExprDelete(db, p->pLimit);
|
|
p->pLimit = pLimit;
|
|
p->pOffset = pOffset;
|
|
|
|
/* Generate code to take the intersection of the two temporary
|
|
** tables.
|
|
*/
|
|
assert( p->pEList );
|
|
if( dest.eDest==SRT_Output ){
|
|
Select *pFirst = p;
|
|
while( pFirst->pPrior ) pFirst = pFirst->pPrior;
|
|
generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
|
|
}
|
|
iBreak = sqlite3VdbeMakeLabel(v);
|
|
iCont = sqlite3VdbeMakeLabel(v);
|
|
computeLimitRegisters(pParse, p, iBreak);
|
|
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
|
|
r1 = sqlite3GetTempReg(pParse);
|
|
iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
|
|
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
selectInnerLoop(pParse, p, p->pEList, tab1,
|
|
0, 0, &dest, iCont, iBreak);
|
|
sqlite3VdbeResolveLabel(v, iCont);
|
|
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
|
|
sqlite3VdbeResolveLabel(v, iBreak);
|
|
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
|
|
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
|
|
break;
|
|
}
|
|
}
|
|
|
|
explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
|
|
|
|
/* Compute collating sequences used by
|
|
** temporary tables needed to implement the compound select.
|
|
** Attach the KeyInfo structure to all temporary tables.
|
|
**
|
|
** This section is run by the right-most SELECT statement only.
|
|
** SELECT statements to the left always skip this part. The right-most
|
|
** SELECT might also skip this part if it has no ORDER BY clause and
|
|
** no temp tables are required.
|
|
*/
|
|
if( p->selFlags & SF_UsesEphemeral ){
|
|
int i; /* Loop counter */
|
|
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
|
|
Select *pLoop; /* For looping through SELECT statements */
|
|
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
|
|
int nCol; /* Number of columns in result set */
|
|
|
|
assert( p->pNext==0 );
|
|
nCol = p->pEList->nExpr;
|
|
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
|
|
if( !pKeyInfo ){
|
|
rc = SQLITE_NOMEM;
|
|
goto multi_select_end;
|
|
}
|
|
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
|
|
*apColl = multiSelectCollSeq(pParse, p, i);
|
|
if( 0==*apColl ){
|
|
*apColl = db->pDfltColl;
|
|
}
|
|
}
|
|
|
|
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
|
|
for(i=0; i<2; i++){
|
|
int addr = pLoop->addrOpenEphm[i];
|
|
if( addr<0 ){
|
|
/* If [0] is unused then [1] is also unused. So we can
|
|
** always safely abort as soon as the first unused slot is found */
|
|
assert( pLoop->addrOpenEphm[1]<0 );
|
|
break;
|
|
}
|
|
sqlite3VdbeChangeP2(v, addr, nCol);
|
|
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
|
|
P4_KEYINFO);
|
|
pLoop->addrOpenEphm[i] = -1;
|
|
}
|
|
}
|
|
sqlite3KeyInfoUnref(pKeyInfo);
|
|
}
|
|
|
|
multi_select_end:
|
|
pDest->iSdst = dest.iSdst;
|
|
pDest->nSdst = dest.nSdst;
|
|
sqlite3SelectDelete(db, pDelete);
|
|
return rc;
|
|
}
|
|
#endif /* SQLITE_OMIT_COMPOUND_SELECT */
|
|
|
|
/*
|
|
** Error message for when two or more terms of a compound select have different
|
|
** size result sets.
|
|
*/
|
|
void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
|
|
if( p->selFlags & SF_Values ){
|
|
sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
|
|
}else{
|
|
sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
|
|
" do not have the same number of result columns", selectOpName(p->op));
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Code an output subroutine for a coroutine implementation of a
|
|
** SELECT statment.
|
|
**
|
|
** The data to be output is contained in pIn->iSdst. There are
|
|
** pIn->nSdst columns to be output. pDest is where the output should
|
|
** be sent.
|
|
**
|
|
** regReturn is the number of the register holding the subroutine
|
|
** return address.
|
|
**
|
|
** If regPrev>0 then it is the first register in a vector that
|
|
** records the previous output. mem[regPrev] is a flag that is false
|
|
** if there has been no previous output. If regPrev>0 then code is
|
|
** generated to suppress duplicates. pKeyInfo is used for comparing
|
|
** keys.
|
|
**
|
|
** If the LIMIT found in p->iLimit is reached, jump immediately to
|
|
** iBreak.
|
|
*/
|
|
static int generateOutputSubroutine(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The SELECT statement */
|
|
SelectDest *pIn, /* Coroutine supplying data */
|
|
SelectDest *pDest, /* Where to send the data */
|
|
int regReturn, /* The return address register */
|
|
int regPrev, /* Previous result register. No uniqueness if 0 */
|
|
KeyInfo *pKeyInfo, /* For comparing with previous entry */
|
|
int iBreak /* Jump here if we hit the LIMIT */
|
|
){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int iContinue;
|
|
int addr;
|
|
|
|
addr = sqlite3VdbeCurrentAddr(v);
|
|
iContinue = sqlite3VdbeMakeLabel(v);
|
|
|
|
/* Suppress duplicates for UNION, EXCEPT, and INTERSECT
|
|
*/
|
|
if( regPrev ){
|
|
int addr1, addr2;
|
|
addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
|
|
addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
|
|
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
|
|
sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
|
|
}
|
|
if( pParse->db->mallocFailed ) return 0;
|
|
|
|
/* Suppress the first OFFSET entries if there is an OFFSET clause
|
|
*/
|
|
codeOffset(v, p->iOffset, iContinue);
|
|
|
|
assert( pDest->eDest!=SRT_Exists );
|
|
assert( pDest->eDest!=SRT_Table );
|
|
switch( pDest->eDest ){
|
|
/* Store the result as data using a unique key.
|
|
*/
|
|
case SRT_EphemTab: {
|
|
int r1 = sqlite3GetTempReg(pParse);
|
|
int r2 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
|
|
sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
|
|
sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
|
|
sqlite3ReleaseTempReg(pParse, r2);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
break;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
/* If we are creating a set for an "expr IN (SELECT ...)" construct,
|
|
** then there should be a single item on the stack. Write this
|
|
** item into the set table with bogus data.
|
|
*/
|
|
case SRT_Set: {
|
|
int r1;
|
|
assert( pIn->nSdst==1 || pParse->nErr>0 );
|
|
pDest->affSdst =
|
|
sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
|
|
r1 = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
|
|
sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
|
|
sqlite3ReleaseTempReg(pParse, r1);
|
|
break;
|
|
}
|
|
|
|
/* If this is a scalar select that is part of an expression, then
|
|
** store the results in the appropriate memory cell and break out
|
|
** of the scan loop.
|
|
*/
|
|
case SRT_Mem: {
|
|
assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
|
|
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
|
|
/* The LIMIT clause will jump out of the loop for us */
|
|
break;
|
|
}
|
|
#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
|
|
|
|
/* The results are stored in a sequence of registers
|
|
** starting at pDest->iSdst. Then the co-routine yields.
|
|
*/
|
|
case SRT_Coroutine: {
|
|
if( pDest->iSdst==0 ){
|
|
pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
|
|
pDest->nSdst = pIn->nSdst;
|
|
}
|
|
sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
|
|
sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
|
|
break;
|
|
}
|
|
|
|
/* If none of the above, then the result destination must be
|
|
** SRT_Output. This routine is never called with any other
|
|
** destination other than the ones handled above or SRT_Output.
|
|
**
|
|
** For SRT_Output, results are stored in a sequence of registers.
|
|
** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
|
|
** return the next row of result.
|
|
*/
|
|
default: {
|
|
assert( pDest->eDest==SRT_Output );
|
|
sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
|
|
sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* Jump to the end of the loop if the LIMIT is reached.
|
|
*/
|
|
if( p->iLimit ){
|
|
sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
|
|
}
|
|
|
|
/* Generate the subroutine return
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, iContinue);
|
|
sqlite3VdbeAddOp1(v, OP_Return, regReturn);
|
|
|
|
return addr;
|
|
}
|
|
|
|
/*
|
|
** Alternative compound select code generator for cases when there
|
|
** is an ORDER BY clause.
|
|
**
|
|
** We assume a query of the following form:
|
|
**
|
|
** <selectA> <operator> <selectB> ORDER BY <orderbylist>
|
|
**
|
|
** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
|
|
** is to code both <selectA> and <selectB> with the ORDER BY clause as
|
|
** co-routines. Then run the co-routines in parallel and merge the results
|
|
** into the output. In addition to the two coroutines (called selectA and
|
|
** selectB) there are 7 subroutines:
|
|
**
|
|
** outA: Move the output of the selectA coroutine into the output
|
|
** of the compound query.
|
|
**
|
|
** outB: Move the output of the selectB coroutine into the output
|
|
** of the compound query. (Only generated for UNION and
|
|
** UNION ALL. EXCEPT and INSERTSECT never output a row that
|
|
** appears only in B.)
|
|
**
|
|
** AltB: Called when there is data from both coroutines and A<B.
|
|
**
|
|
** AeqB: Called when there is data from both coroutines and A==B.
|
|
**
|
|
** AgtB: Called when there is data from both coroutines and A>B.
|
|
**
|
|
** EofA: Called when data is exhausted from selectA.
|
|
**
|
|
** EofB: Called when data is exhausted from selectB.
|
|
**
|
|
** The implementation of the latter five subroutines depend on which
|
|
** <operator> is used:
|
|
**
|
|
**
|
|
** UNION ALL UNION EXCEPT INTERSECT
|
|
** ------------- ----------------- -------------- -----------------
|
|
** AltB: outA, nextA outA, nextA outA, nextA nextA
|
|
**
|
|
** AeqB: outA, nextA nextA nextA outA, nextA
|
|
**
|
|
** AgtB: outB, nextB outB, nextB nextB nextB
|
|
**
|
|
** EofA: outB, nextB outB, nextB halt halt
|
|
**
|
|
** EofB: outA, nextA outA, nextA outA, nextA halt
|
|
**
|
|
** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
|
|
** causes an immediate jump to EofA and an EOF on B following nextB causes
|
|
** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
|
|
** following nextX causes a jump to the end of the select processing.
|
|
**
|
|
** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
|
|
** within the output subroutine. The regPrev register set holds the previously
|
|
** output value. A comparison is made against this value and the output
|
|
** is skipped if the next results would be the same as the previous.
|
|
**
|
|
** The implementation plan is to implement the two coroutines and seven
|
|
** subroutines first, then put the control logic at the bottom. Like this:
|
|
**
|
|
** goto Init
|
|
** coA: coroutine for left query (A)
|
|
** coB: coroutine for right query (B)
|
|
** outA: output one row of A
|
|
** outB: output one row of B (UNION and UNION ALL only)
|
|
** EofA: ...
|
|
** EofB: ...
|
|
** AltB: ...
|
|
** AeqB: ...
|
|
** AgtB: ...
|
|
** Init: initialize coroutine registers
|
|
** yield coA
|
|
** if eof(A) goto EofA
|
|
** yield coB
|
|
** if eof(B) goto EofB
|
|
** Cmpr: Compare A, B
|
|
** Jump AltB, AeqB, AgtB
|
|
** End: ...
|
|
**
|
|
** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
|
|
** actually called using Gosub and they do not Return. EofA and EofB loop
|
|
** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
|
|
** and AgtB jump to either L2 or to one of EofA or EofB.
|
|
*/
|
|
#ifndef SQLITE_OMIT_COMPOUND_SELECT
|
|
static int multiSelectOrderBy(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The right-most of SELECTs to be coded */
|
|
SelectDest *pDest /* What to do with query results */
|
|
){
|
|
int i, j; /* Loop counters */
|
|
Select *pPrior; /* Another SELECT immediately to our left */
|
|
Vdbe *v; /* Generate code to this VDBE */
|
|
SelectDest destA; /* Destination for coroutine A */
|
|
SelectDest destB; /* Destination for coroutine B */
|
|
int regAddrA; /* Address register for select-A coroutine */
|
|
int regAddrB; /* Address register for select-B coroutine */
|
|
int addrSelectA; /* Address of the select-A coroutine */
|
|
int addrSelectB; /* Address of the select-B coroutine */
|
|
int regOutA; /* Address register for the output-A subroutine */
|
|
int regOutB; /* Address register for the output-B subroutine */
|
|
int addrOutA; /* Address of the output-A subroutine */
|
|
int addrOutB = 0; /* Address of the output-B subroutine */
|
|
int addrEofA; /* Address of the select-A-exhausted subroutine */
|
|
int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
|
|
int addrEofB; /* Address of the select-B-exhausted subroutine */
|
|
int addrAltB; /* Address of the A<B subroutine */
|
|
int addrAeqB; /* Address of the A==B subroutine */
|
|
int addrAgtB; /* Address of the A>B subroutine */
|
|
int regLimitA; /* Limit register for select-A */
|
|
int regLimitB; /* Limit register for select-A */
|
|
int regPrev; /* A range of registers to hold previous output */
|
|
int savedLimit; /* Saved value of p->iLimit */
|
|
int savedOffset; /* Saved value of p->iOffset */
|
|
int labelCmpr; /* Label for the start of the merge algorithm */
|
|
int labelEnd; /* Label for the end of the overall SELECT stmt */
|
|
int addr1; /* Jump instructions that get retargetted */
|
|
int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
|
|
KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
|
|
KeyInfo *pKeyMerge; /* Comparison information for merging rows */
|
|
sqlite3 *db; /* Database connection */
|
|
ExprList *pOrderBy; /* The ORDER BY clause */
|
|
int nOrderBy; /* Number of terms in the ORDER BY clause */
|
|
int *aPermute; /* Mapping from ORDER BY terms to result set columns */
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
int iSub1; /* EQP id of left-hand query */
|
|
int iSub2; /* EQP id of right-hand query */
|
|
#endif
|
|
|
|
assert( p->pOrderBy!=0 );
|
|
assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
|
|
db = pParse->db;
|
|
v = pParse->pVdbe;
|
|
assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
|
|
labelEnd = sqlite3VdbeMakeLabel(v);
|
|
labelCmpr = sqlite3VdbeMakeLabel(v);
|
|
|
|
|
|
/* Patch up the ORDER BY clause
|
|
*/
|
|
op = p->op;
|
|
pPrior = p->pPrior;
|
|
assert( pPrior->pOrderBy==0 );
|
|
pOrderBy = p->pOrderBy;
|
|
assert( pOrderBy );
|
|
nOrderBy = pOrderBy->nExpr;
|
|
|
|
/* For operators other than UNION ALL we have to make sure that
|
|
** the ORDER BY clause covers every term of the result set. Add
|
|
** terms to the ORDER BY clause as necessary.
|
|
*/
|
|
if( op!=TK_ALL ){
|
|
for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
|
|
struct ExprList_item *pItem;
|
|
for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
|
|
assert( pItem->u.x.iOrderByCol>0 );
|
|
if( pItem->u.x.iOrderByCol==i ) break;
|
|
}
|
|
if( j==nOrderBy ){
|
|
Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
|
|
if( pNew==0 ) return SQLITE_NOMEM;
|
|
pNew->flags |= EP_IntValue;
|
|
pNew->u.iValue = i;
|
|
pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
|
|
if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Compute the comparison permutation and keyinfo that is used with
|
|
** the permutation used to determine if the next
|
|
** row of results comes from selectA or selectB. Also add explicit
|
|
** collations to the ORDER BY clause terms so that when the subqueries
|
|
** to the right and the left are evaluated, they use the correct
|
|
** collation.
|
|
*/
|
|
aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
|
|
if( aPermute ){
|
|
struct ExprList_item *pItem;
|
|
aPermute[0] = nOrderBy;
|
|
for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
|
|
assert( pItem->u.x.iOrderByCol>0 );
|
|
assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
|
|
aPermute[i] = pItem->u.x.iOrderByCol - 1;
|
|
}
|
|
pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
|
|
}else{
|
|
pKeyMerge = 0;
|
|
}
|
|
|
|
/* Reattach the ORDER BY clause to the query.
|
|
*/
|
|
p->pOrderBy = pOrderBy;
|
|
pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
|
|
|
|
/* Allocate a range of temporary registers and the KeyInfo needed
|
|
** for the logic that removes duplicate result rows when the
|
|
** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
|
|
*/
|
|
if( op==TK_ALL ){
|
|
regPrev = 0;
|
|
}else{
|
|
int nExpr = p->pEList->nExpr;
|
|
assert( nOrderBy>=nExpr || db->mallocFailed );
|
|
regPrev = pParse->nMem+1;
|
|
pParse->nMem += nExpr+1;
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
|
|
pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
|
|
if( pKeyDup ){
|
|
assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
|
|
for(i=0; i<nExpr; i++){
|
|
pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
|
|
pKeyDup->aSortOrder[i] = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Separate the left and the right query from one another
|
|
*/
|
|
p->pPrior = 0;
|
|
pPrior->pNext = 0;
|
|
sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
|
|
if( pPrior->pPrior==0 ){
|
|
sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
|
|
}
|
|
|
|
/* Compute the limit registers */
|
|
computeLimitRegisters(pParse, p, labelEnd);
|
|
if( p->iLimit && op==TK_ALL ){
|
|
regLimitA = ++pParse->nMem;
|
|
regLimitB = ++pParse->nMem;
|
|
sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
|
|
regLimitA);
|
|
sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
|
|
}else{
|
|
regLimitA = regLimitB = 0;
|
|
}
|
|
sqlite3ExprDelete(db, p->pLimit);
|
|
p->pLimit = 0;
|
|
sqlite3ExprDelete(db, p->pOffset);
|
|
p->pOffset = 0;
|
|
|
|
regAddrA = ++pParse->nMem;
|
|
regAddrB = ++pParse->nMem;
|
|
regOutA = ++pParse->nMem;
|
|
regOutB = ++pParse->nMem;
|
|
sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
|
|
sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
|
|
|
|
/* Generate a coroutine to evaluate the SELECT statement to the
|
|
** left of the compound operator - the "A" select.
|
|
*/
|
|
addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
|
|
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
|
|
VdbeComment((v, "left SELECT"));
|
|
pPrior->iLimit = regLimitA;
|
|
explainSetInteger(iSub1, pParse->iNextSelectId);
|
|
sqlite3Select(pParse, pPrior, &destA);
|
|
sqlite3VdbeEndCoroutine(v, regAddrA);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
|
|
/* Generate a coroutine to evaluate the SELECT statement on
|
|
** the right - the "B" select
|
|
*/
|
|
addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
|
|
addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
|
|
VdbeComment((v, "right SELECT"));
|
|
savedLimit = p->iLimit;
|
|
savedOffset = p->iOffset;
|
|
p->iLimit = regLimitB;
|
|
p->iOffset = 0;
|
|
explainSetInteger(iSub2, pParse->iNextSelectId);
|
|
sqlite3Select(pParse, p, &destB);
|
|
p->iLimit = savedLimit;
|
|
p->iOffset = savedOffset;
|
|
sqlite3VdbeEndCoroutine(v, regAddrB);
|
|
|
|
/* Generate a subroutine that outputs the current row of the A
|
|
** select as the next output row of the compound select.
|
|
*/
|
|
VdbeNoopComment((v, "Output routine for A"));
|
|
addrOutA = generateOutputSubroutine(pParse,
|
|
p, &destA, pDest, regOutA,
|
|
regPrev, pKeyDup, labelEnd);
|
|
|
|
/* Generate a subroutine that outputs the current row of the B
|
|
** select as the next output row of the compound select.
|
|
*/
|
|
if( op==TK_ALL || op==TK_UNION ){
|
|
VdbeNoopComment((v, "Output routine for B"));
|
|
addrOutB = generateOutputSubroutine(pParse,
|
|
p, &destB, pDest, regOutB,
|
|
regPrev, pKeyDup, labelEnd);
|
|
}
|
|
sqlite3KeyInfoUnref(pKeyDup);
|
|
|
|
/* Generate a subroutine to run when the results from select A
|
|
** are exhausted and only data in select B remains.
|
|
*/
|
|
if( op==TK_EXCEPT || op==TK_INTERSECT ){
|
|
addrEofA_noB = addrEofA = labelEnd;
|
|
}else{
|
|
VdbeNoopComment((v, "eof-A subroutine"));
|
|
addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
|
|
addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
|
|
VdbeCoverage(v);
|
|
sqlite3VdbeGoto(v, addrEofA);
|
|
p->nSelectRow += pPrior->nSelectRow;
|
|
}
|
|
|
|
/* Generate a subroutine to run when the results from select B
|
|
** are exhausted and only data in select A remains.
|
|
*/
|
|
if( op==TK_INTERSECT ){
|
|
addrEofB = addrEofA;
|
|
if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
|
|
}else{
|
|
VdbeNoopComment((v, "eof-B subroutine"));
|
|
addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
|
|
sqlite3VdbeGoto(v, addrEofB);
|
|
}
|
|
|
|
/* Generate code to handle the case of A<B
|
|
*/
|
|
VdbeNoopComment((v, "A-lt-B subroutine"));
|
|
addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
|
|
sqlite3VdbeGoto(v, labelCmpr);
|
|
|
|
/* Generate code to handle the case of A==B
|
|
*/
|
|
if( op==TK_ALL ){
|
|
addrAeqB = addrAltB;
|
|
}else if( op==TK_INTERSECT ){
|
|
addrAeqB = addrAltB;
|
|
addrAltB++;
|
|
}else{
|
|
VdbeNoopComment((v, "A-eq-B subroutine"));
|
|
addrAeqB =
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
|
|
sqlite3VdbeGoto(v, labelCmpr);
|
|
}
|
|
|
|
/* Generate code to handle the case of A>B
|
|
*/
|
|
VdbeNoopComment((v, "A-gt-B subroutine"));
|
|
addrAgtB = sqlite3VdbeCurrentAddr(v);
|
|
if( op==TK_ALL || op==TK_UNION ){
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
|
|
}
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
|
|
sqlite3VdbeGoto(v, labelCmpr);
|
|
|
|
/* This code runs once to initialize everything.
|
|
*/
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
|
|
|
|
/* Implement the main merge loop
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, labelCmpr);
|
|
sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
|
|
sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
|
|
(char*)pKeyMerge, P4_KEYINFO);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
|
|
sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
|
|
|
|
/* Jump to the this point in order to terminate the query.
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, labelEnd);
|
|
|
|
/* Set the number of output columns
|
|
*/
|
|
if( pDest->eDest==SRT_Output ){
|
|
Select *pFirst = pPrior;
|
|
while( pFirst->pPrior ) pFirst = pFirst->pPrior;
|
|
generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
|
|
}
|
|
|
|
/* Reassembly the compound query so that it will be freed correctly
|
|
** by the calling function */
|
|
if( p->pPrior ){
|
|
sqlite3SelectDelete(db, p->pPrior);
|
|
}
|
|
p->pPrior = pPrior;
|
|
pPrior->pNext = p;
|
|
|
|
/*** TBD: Insert subroutine calls to close cursors on incomplete
|
|
**** subqueries ****/
|
|
explainComposite(pParse, p->op, iSub1, iSub2, 0);
|
|
return pParse->nErr!=0;
|
|
}
|
|
#endif
|
|
|
|
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
|
|
/* Forward Declarations */
|
|
static void substExprList(sqlite3*, ExprList*, int, ExprList*);
|
|
static void substSelect(sqlite3*, Select *, int, ExprList*, int);
|
|
|
|
/*
|
|
** Scan through the expression pExpr. Replace every reference to
|
|
** a column in table number iTable with a copy of the iColumn-th
|
|
** entry in pEList. (But leave references to the ROWID column
|
|
** unchanged.)
|
|
**
|
|
** This routine is part of the flattening procedure. A subquery
|
|
** whose result set is defined by pEList appears as entry in the
|
|
** FROM clause of a SELECT such that the VDBE cursor assigned to that
|
|
** FORM clause entry is iTable. This routine make the necessary
|
|
** changes to pExpr so that it refers directly to the source table
|
|
** of the subquery rather the result set of the subquery.
|
|
*/
|
|
static Expr *substExpr(
|
|
sqlite3 *db, /* Report malloc errors to this connection */
|
|
Expr *pExpr, /* Expr in which substitution occurs */
|
|
int iTable, /* Table to be substituted */
|
|
ExprList *pEList /* Substitute expressions */
|
|
){
|
|
if( pExpr==0 ) return 0;
|
|
if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
|
|
if( pExpr->iColumn<0 ){
|
|
pExpr->op = TK_NULL;
|
|
}else{
|
|
Expr *pNew;
|
|
assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
|
|
assert( pExpr->pLeft==0 && pExpr->pRight==0 );
|
|
pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
|
|
sqlite3ExprDelete(db, pExpr);
|
|
pExpr = pNew;
|
|
}
|
|
}else{
|
|
pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
|
|
pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
|
|
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
|
|
substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
|
|
}else{
|
|
substExprList(db, pExpr->x.pList, iTable, pEList);
|
|
}
|
|
}
|
|
return pExpr;
|
|
}
|
|
static void substExprList(
|
|
sqlite3 *db, /* Report malloc errors here */
|
|
ExprList *pList, /* List to scan and in which to make substitutes */
|
|
int iTable, /* Table to be substituted */
|
|
ExprList *pEList /* Substitute values */
|
|
){
|
|
int i;
|
|
if( pList==0 ) return;
|
|
for(i=0; i<pList->nExpr; i++){
|
|
pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
|
|
}
|
|
}
|
|
static void substSelect(
|
|
sqlite3 *db, /* Report malloc errors here */
|
|
Select *p, /* SELECT statement in which to make substitutions */
|
|
int iTable, /* Table to be replaced */
|
|
ExprList *pEList, /* Substitute values */
|
|
int doPrior /* Do substitutes on p->pPrior too */
|
|
){
|
|
SrcList *pSrc;
|
|
struct SrcList_item *pItem;
|
|
int i;
|
|
if( !p ) return;
|
|
do{
|
|
substExprList(db, p->pEList, iTable, pEList);
|
|
substExprList(db, p->pGroupBy, iTable, pEList);
|
|
substExprList(db, p->pOrderBy, iTable, pEList);
|
|
p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
|
|
p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
|
|
pSrc = p->pSrc;
|
|
assert( pSrc!=0 );
|
|
for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
|
|
substSelect(db, pItem->pSelect, iTable, pEList, 1);
|
|
if( pItem->fg.isTabFunc ){
|
|
substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
|
|
}
|
|
}
|
|
}while( doPrior && (p = p->pPrior)!=0 );
|
|
}
|
|
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
|
|
|
|
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
|
|
/*
|
|
** This routine attempts to flatten subqueries as a performance optimization.
|
|
** This routine returns 1 if it makes changes and 0 if no flattening occurs.
|
|
**
|
|
** To understand the concept of flattening, consider the following
|
|
** query:
|
|
**
|
|
** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
|
|
**
|
|
** The default way of implementing this query is to execute the
|
|
** subquery first and store the results in a temporary table, then
|
|
** run the outer query on that temporary table. This requires two
|
|
** passes over the data. Furthermore, because the temporary table
|
|
** has no indices, the WHERE clause on the outer query cannot be
|
|
** optimized.
|
|
**
|
|
** This routine attempts to rewrite queries such as the above into
|
|
** a single flat select, like this:
|
|
**
|
|
** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
|
|
**
|
|
** The code generated for this simplification gives the same result
|
|
** but only has to scan the data once. And because indices might
|
|
** exist on the table t1, a complete scan of the data might be
|
|
** avoided.
|
|
**
|
|
** Flattening is only attempted if all of the following are true:
|
|
**
|
|
** (1) The subquery and the outer query do not both use aggregates.
|
|
**
|
|
** (2) The subquery is not an aggregate or (2a) the outer query is not a join
|
|
** and (2b) the outer query does not use subqueries other than the one
|
|
** FROM-clause subquery that is a candidate for flattening. (2b is
|
|
** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
|
|
**
|
|
** (3) The subquery is not the right operand of a left outer join
|
|
** (Originally ticket #306. Strengthened by ticket #3300)
|
|
**
|
|
** (4) The subquery is not DISTINCT.
|
|
**
|
|
** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
|
|
** sub-queries that were excluded from this optimization. Restriction
|
|
** (4) has since been expanded to exclude all DISTINCT subqueries.
|
|
**
|
|
** (6) The subquery does not use aggregates or the outer query is not
|
|
** DISTINCT.
|
|
**
|
|
** (7) The subquery has a FROM clause. TODO: For subqueries without
|
|
** A FROM clause, consider adding a FROM close with the special
|
|
** table sqlite_once that consists of a single row containing a
|
|
** single NULL.
|
|
**
|
|
** (8) The subquery does not use LIMIT or the outer query is not a join.
|
|
**
|
|
** (9) The subquery does not use LIMIT or the outer query does not use
|
|
** aggregates.
|
|
**
|
|
** (**) Restriction (10) was removed from the code on 2005-02-05 but we
|
|
** accidently carried the comment forward until 2014-09-15. Original
|
|
** text: "The subquery does not use aggregates or the outer query
|
|
** does not use LIMIT."
|
|
**
|
|
** (11) The subquery and the outer query do not both have ORDER BY clauses.
|
|
**
|
|
** (**) Not implemented. Subsumed into restriction (3). Was previously
|
|
** a separate restriction deriving from ticket #350.
|
|
**
|
|
** (13) The subquery and outer query do not both use LIMIT.
|
|
**
|
|
** (14) The subquery does not use OFFSET.
|
|
**
|
|
** (15) The outer query is not part of a compound select or the
|
|
** subquery does not have a LIMIT clause.
|
|
** (See ticket #2339 and ticket [02a8e81d44]).
|
|
**
|
|
** (16) The outer query is not an aggregate or the subquery does
|
|
** not contain ORDER BY. (Ticket #2942) This used to not matter
|
|
** until we introduced the group_concat() function.
|
|
**
|
|
** (17) The sub-query is not a compound select, or it is a UNION ALL
|
|
** compound clause made up entirely of non-aggregate queries, and
|
|
** the parent query:
|
|
**
|
|
** * is not itself part of a compound select,
|
|
** * is not an aggregate or DISTINCT query, and
|
|
** * is not a join
|
|
**
|
|
** The parent and sub-query may contain WHERE clauses. Subject to
|
|
** rules (11), (13) and (14), they may also contain ORDER BY,
|
|
** LIMIT and OFFSET clauses. The subquery cannot use any compound
|
|
** operator other than UNION ALL because all the other compound
|
|
** operators have an implied DISTINCT which is disallowed by
|
|
** restriction (4).
|
|
**
|
|
** Also, each component of the sub-query must return the same number
|
|
** of result columns. This is actually a requirement for any compound
|
|
** SELECT statement, but all the code here does is make sure that no
|
|
** such (illegal) sub-query is flattened. The caller will detect the
|
|
** syntax error and return a detailed message.
|
|
**
|
|
** (18) If the sub-query is a compound select, then all terms of the
|
|
** ORDER by clause of the parent must be simple references to
|
|
** columns of the sub-query.
|
|
**
|
|
** (19) The subquery does not use LIMIT or the outer query does not
|
|
** have a WHERE clause.
|
|
**
|
|
** (20) If the sub-query is a compound select, then it must not use
|
|
** an ORDER BY clause. Ticket #3773. We could relax this constraint
|
|
** somewhat by saying that the terms of the ORDER BY clause must
|
|
** appear as unmodified result columns in the outer query. But we
|
|
** have other optimizations in mind to deal with that case.
|
|
**
|
|
** (21) The subquery does not use LIMIT or the outer query is not
|
|
** DISTINCT. (See ticket [752e1646fc]).
|
|
**
|
|
** (22) The subquery is not a recursive CTE.
|
|
**
|
|
** (23) The parent is not a recursive CTE, or the sub-query is not a
|
|
** compound query. This restriction is because transforming the
|
|
** parent to a compound query confuses the code that handles
|
|
** recursive queries in multiSelect().
|
|
**
|
|
** (24) The subquery is not an aggregate that uses the built-in min() or
|
|
** or max() functions. (Without this restriction, a query like:
|
|
** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
|
|
** return the value X for which Y was maximal.)
|
|
**
|
|
**
|
|
** In this routine, the "p" parameter is a pointer to the outer query.
|
|
** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
|
|
** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
|
|
**
|
|
** If flattening is not attempted, this routine is a no-op and returns 0.
|
|
** If flattening is attempted this routine returns 1.
|
|
**
|
|
** All of the expression analysis must occur on both the outer query and
|
|
** the subquery before this routine runs.
|
|
*/
|
|
static int flattenSubquery(
|
|
Parse *pParse, /* Parsing context */
|
|
Select *p, /* The parent or outer SELECT statement */
|
|
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
|
|
int isAgg, /* True if outer SELECT uses aggregate functions */
|
|
int subqueryIsAgg /* True if the subquery uses aggregate functions */
|
|
){
|
|
const char *zSavedAuthContext = pParse->zAuthContext;
|
|
Select *pParent; /* Current UNION ALL term of the other query */
|
|
Select *pSub; /* The inner query or "subquery" */
|
|
Select *pSub1; /* Pointer to the rightmost select in sub-query */
|
|
SrcList *pSrc; /* The FROM clause of the outer query */
|
|
SrcList *pSubSrc; /* The FROM clause of the subquery */
|
|
ExprList *pList; /* The result set of the outer query */
|
|
int iParent; /* VDBE cursor number of the pSub result set temp table */
|
|
int i; /* Loop counter */
|
|
Expr *pWhere; /* The WHERE clause */
|
|
struct SrcList_item *pSubitem; /* The subquery */
|
|
sqlite3 *db = pParse->db;
|
|
|
|
/* Check to see if flattening is permitted. Return 0 if not.
|
|
*/
|
|
assert( p!=0 );
|
|
assert( p->pPrior==0 ); /* Unable to flatten compound queries */
|
|
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
|
|
pSrc = p->pSrc;
|
|
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
|
|
pSubitem = &pSrc->a[iFrom];
|
|
iParent = pSubitem->iCursor;
|
|
pSub = pSubitem->pSelect;
|
|
assert( pSub!=0 );
|
|
if( subqueryIsAgg ){
|
|
if( isAgg ) return 0; /* Restriction (1) */
|
|
if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
|
|
if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
|
|
|| (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
|
|
|| (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
|
|
){
|
|
return 0; /* Restriction (2b) */
|
|
}
|
|
}
|
|
|
|
pSubSrc = pSub->pSrc;
|
|
assert( pSubSrc );
|
|
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
|
|
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
|
|
** because they could be computed at compile-time. But when LIMIT and OFFSET
|
|
** became arbitrary expressions, we were forced to add restrictions (13)
|
|
** and (14). */
|
|
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
|
|
if( pSub->pOffset ) return 0; /* Restriction (14) */
|
|
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
|
|
return 0; /* Restriction (15) */
|
|
}
|
|
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
|
|
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
|
|
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
|
|
return 0; /* Restrictions (8)(9) */
|
|
}
|
|
if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
|
|
return 0; /* Restriction (6) */
|
|
}
|
|
if( p->pOrderBy && pSub->pOrderBy ){
|
|
return 0; /* Restriction (11) */
|
|
}
|
|
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
|
|
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
|
|
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
|
|
return 0; /* Restriction (21) */
|
|
}
|
|
testcase( pSub->selFlags & SF_Recursive );
|
|
testcase( pSub->selFlags & SF_MinMaxAgg );
|
|
if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
|
|
return 0; /* Restrictions (22) and (24) */
|
|
}
|
|
if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
|
|
return 0; /* Restriction (23) */
|
|
}
|
|
|
|
/* OBSOLETE COMMENT 1:
|
|
** Restriction 3: If the subquery is a join, make sure the subquery is
|
|
** not used as the right operand of an outer join. Examples of why this
|
|
** is not allowed:
|
|
**
|
|
** t1 LEFT OUTER JOIN (t2 JOIN t3)
|
|
**
|
|
** If we flatten the above, we would get
|
|
**
|
|
** (t1 LEFT OUTER JOIN t2) JOIN t3
|
|
**
|
|
** which is not at all the same thing.
|
|
**
|
|
** OBSOLETE COMMENT 2:
|
|
** Restriction 12: If the subquery is the right operand of a left outer
|
|
** join, make sure the subquery has no WHERE clause.
|
|
** An examples of why this is not allowed:
|
|
**
|
|
** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
|
|
**
|
|
** If we flatten the above, we would get
|
|
**
|
|
** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
|
|
**
|
|
** But the t2.x>0 test will always fail on a NULL row of t2, which
|
|
** effectively converts the OUTER JOIN into an INNER JOIN.
|
|
**
|
|
** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
|
|
** Ticket #3300 shows that flattening the right term of a LEFT JOIN
|
|
** is fraught with danger. Best to avoid the whole thing. If the
|
|
** subquery is the right term of a LEFT JOIN, then do not flatten.
|
|
*/
|
|
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
|
|
return 0;
|
|
}
|
|
|
|
/* Restriction 17: If the sub-query is a compound SELECT, then it must
|
|
** use only the UNION ALL operator. And none of the simple select queries
|
|
** that make up the compound SELECT are allowed to be aggregate or distinct
|
|
** queries.
|
|
*/
|
|
if( pSub->pPrior ){
|
|
if( pSub->pOrderBy ){
|
|
return 0; /* Restriction 20 */
|
|
}
|
|
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
|
|
return 0;
|
|
}
|
|
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
|
|
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
|
|
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
|
|
assert( pSub->pSrc!=0 );
|
|
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
|
|
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
|
|
|| (pSub1->pPrior && pSub1->op!=TK_ALL)
|
|
|| pSub1->pSrc->nSrc<1
|
|
){
|
|
return 0;
|
|
}
|
|
testcase( pSub1->pSrc->nSrc>1 );
|
|
}
|
|
|
|
/* Restriction 18. */
|
|
if( p->pOrderBy ){
|
|
int ii;
|
|
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
|
|
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
/***** If we reach this point, flattening is permitted. *****/
|
|
SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
|
|
pSub->zSelName, pSub, iFrom));
|
|
|
|
/* Authorize the subquery */
|
|
pParse->zAuthContext = pSubitem->zName;
|
|
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
|
|
testcase( i==SQLITE_DENY );
|
|
pParse->zAuthContext = zSavedAuthContext;
|
|
|
|
/* If the sub-query is a compound SELECT statement, then (by restrictions
|
|
** 17 and 18 above) it must be a UNION ALL and the parent query must
|
|
** be of the form:
|
|
**
|
|
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
|
|
**
|
|
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
|
|
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
|
|
** OFFSET clauses and joins them to the left-hand-side of the original
|
|
** using UNION ALL operators. In this case N is the number of simple
|
|
** select statements in the compound sub-query.
|
|
**
|
|
** Example:
|
|
**
|
|
** SELECT a+1 FROM (
|
|
** SELECT x FROM tab
|
|
** UNION ALL
|
|
** SELECT y FROM tab
|
|
** UNION ALL
|
|
** SELECT abs(z*2) FROM tab2
|
|
** ) WHERE a!=5 ORDER BY 1
|
|
**
|
|
** Transformed into:
|
|
**
|
|
** SELECT x+1 FROM tab WHERE x+1!=5
|
|
** UNION ALL
|
|
** SELECT y+1 FROM tab WHERE y+1!=5
|
|
** UNION ALL
|
|
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
|
|
** ORDER BY 1
|
|
**
|
|
** We call this the "compound-subquery flattening".
|
|
*/
|
|
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
|
|
Select *pNew;
|
|
ExprList *pOrderBy = p->pOrderBy;
|
|
Expr *pLimit = p->pLimit;
|
|
Expr *pOffset = p->pOffset;
|
|
Select *pPrior = p->pPrior;
|
|
p->pOrderBy = 0;
|
|
p->pSrc = 0;
|
|
p->pPrior = 0;
|
|
p->pLimit = 0;
|
|
p->pOffset = 0;
|
|
pNew = sqlite3SelectDup(db, p, 0);
|
|
sqlite3SelectSetName(pNew, pSub->zSelName);
|
|
p->pOffset = pOffset;
|
|
p->pLimit = pLimit;
|
|
p->pOrderBy = pOrderBy;
|
|
p->pSrc = pSrc;
|
|
p->op = TK_ALL;
|
|
if( pNew==0 ){
|
|
p->pPrior = pPrior;
|
|
}else{
|
|
pNew->pPrior = pPrior;
|
|
if( pPrior ) pPrior->pNext = pNew;
|
|
pNew->pNext = p;
|
|
p->pPrior = pNew;
|
|
SELECTTRACE(2,pParse,p,
|
|
("compound-subquery flattener creates %s.%p as peer\n",
|
|
pNew->zSelName, pNew));
|
|
}
|
|
if( db->mallocFailed ) return 1;
|
|
}
|
|
|
|
/* Begin flattening the iFrom-th entry of the FROM clause
|
|
** in the outer query.
|
|
*/
|
|
pSub = pSub1 = pSubitem->pSelect;
|
|
|
|
/* Delete the transient table structure associated with the
|
|
** subquery
|
|
*/
|
|
sqlite3DbFree(db, pSubitem->zDatabase);
|
|
sqlite3DbFree(db, pSubitem->zName);
|
|
sqlite3DbFree(db, pSubitem->zAlias);
|
|
pSubitem->zDatabase = 0;
|
|
pSubitem->zName = 0;
|
|
pSubitem->zAlias = 0;
|
|
pSubitem->pSelect = 0;
|
|
|
|
/* Defer deleting the Table object associated with the
|
|
** subquery until code generation is
|
|
** complete, since there may still exist Expr.pTab entries that
|
|
** refer to the subquery even after flattening. Ticket #3346.
|
|
**
|
|
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
|
|
*/
|
|
if( ALWAYS(pSubitem->pTab!=0) ){
|
|
Table *pTabToDel = pSubitem->pTab;
|
|
if( pTabToDel->nRef==1 ){
|
|
Parse *pToplevel = sqlite3ParseToplevel(pParse);
|
|
pTabToDel->pNextZombie = pToplevel->pZombieTab;
|
|
pToplevel->pZombieTab = pTabToDel;
|
|
}else{
|
|
pTabToDel->nRef--;
|
|
}
|
|
pSubitem->pTab = 0;
|
|
}
|
|
|
|
/* The following loop runs once for each term in a compound-subquery
|
|
** flattening (as described above). If we are doing a different kind
|
|
** of flattening - a flattening other than a compound-subquery flattening -
|
|
** then this loop only runs once.
|
|
**
|
|
** This loop moves all of the FROM elements of the subquery into the
|
|
** the FROM clause of the outer query. Before doing this, remember
|
|
** the cursor number for the original outer query FROM element in
|
|
** iParent. The iParent cursor will never be used. Subsequent code
|
|
** will scan expressions looking for iParent references and replace
|
|
** those references with expressions that resolve to the subquery FROM
|
|
** elements we are now copying in.
|
|
*/
|
|
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
|
|
int nSubSrc;
|
|
u8 jointype = 0;
|
|
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
|
|
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
|
|
pSrc = pParent->pSrc; /* FROM clause of the outer query */
|
|
|
|
if( pSrc ){
|
|
assert( pParent==p ); /* First time through the loop */
|
|
jointype = pSubitem->fg.jointype;
|
|
}else{
|
|
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
|
|
pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
|
|
if( pSrc==0 ){
|
|
assert( db->mallocFailed );
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* The subquery uses a single slot of the FROM clause of the outer
|
|
** query. If the subquery has more than one element in its FROM clause,
|
|
** then expand the outer query to make space for it to hold all elements
|
|
** of the subquery.
|
|
**
|
|
** Example:
|
|
**
|
|
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
|
|
**
|
|
** The outer query has 3 slots in its FROM clause. One slot of the
|
|
** outer query (the middle slot) is used by the subquery. The next
|
|
** block of code will expand the outer query FROM clause to 4 slots.
|
|
** The middle slot is expanded to two slots in order to make space
|
|
** for the two elements in the FROM clause of the subquery.
|
|
*/
|
|
if( nSubSrc>1 ){
|
|
pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
|
|
if( db->mallocFailed ){
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* Transfer the FROM clause terms from the subquery into the
|
|
** outer query.
|
|
*/
|
|
for(i=0; i<nSubSrc; i++){
|
|
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
|
|
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
|
|
pSrc->a[i+iFrom] = pSubSrc->a[i];
|
|
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
|
|
}
|
|
pSrc->a[iFrom].fg.jointype = jointype;
|
|
|
|
/* Now begin substituting subquery result set expressions for
|
|
** references to the iParent in the outer query.
|
|
**
|
|
** Example:
|
|
**
|
|
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
|
|
** \ \_____________ subquery __________/ /
|
|
** \_____________________ outer query ______________________________/
|
|
**
|
|
** We look at every expression in the outer query and every place we see
|
|
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
|
|
*/
|
|
pList = pParent->pEList;
|
|
for(i=0; i<pList->nExpr; i++){
|
|
if( pList->a[i].zName==0 ){
|
|
char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
|
|
sqlite3Dequote(zName);
|
|
pList->a[i].zName = zName;
|
|
}
|
|
}
|
|
if( pSub->pOrderBy ){
|
|
/* At this point, any non-zero iOrderByCol values indicate that the
|
|
** ORDER BY column expression is identical to the iOrderByCol'th
|
|
** expression returned by SELECT statement pSub. Since these values
|
|
** do not necessarily correspond to columns in SELECT statement pParent,
|
|
** zero them before transfering the ORDER BY clause.
|
|
**
|
|
** Not doing this may cause an error if a subsequent call to this
|
|
** function attempts to flatten a compound sub-query into pParent
|
|
** (the only way this can happen is if the compound sub-query is
|
|
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
|
|
ExprList *pOrderBy = pSub->pOrderBy;
|
|
for(i=0; i<pOrderBy->nExpr; i++){
|
|
pOrderBy->a[i].u.x.iOrderByCol = 0;
|
|
}
|
|
assert( pParent->pOrderBy==0 );
|
|
assert( pSub->pPrior==0 );
|
|
pParent->pOrderBy = pOrderBy;
|
|
pSub->pOrderBy = 0;
|
|
}
|
|
pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
|
|
if( subqueryIsAgg ){
|
|
assert( pParent->pHaving==0 );
|
|
pParent->pHaving = pParent->pWhere;
|
|
pParent->pWhere = pWhere;
|
|
pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
|
|
sqlite3ExprDup(db, pSub->pHaving, 0));
|
|
assert( pParent->pGroupBy==0 );
|
|
pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
|
|
}else{
|
|
pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
|
|
}
|
|
substSelect(db, pParent, iParent, pSub->pEList, 0);
|
|
|
|
/* The flattened query is distinct if either the inner or the
|
|
** outer query is distinct.
|
|
*/
|
|
pParent->selFlags |= pSub->selFlags & SF_Distinct;
|
|
|
|
/*
|
|
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
|
|
**
|
|
** One is tempted to try to add a and b to combine the limits. But this
|
|
** does not work if either limit is negative.
|
|
*/
|
|
if( pSub->pLimit ){
|
|
pParent->pLimit = pSub->pLimit;
|
|
pSub->pLimit = 0;
|
|
}
|
|
}
|
|
|
|
/* Finially, delete what is left of the subquery and return
|
|
** success.
|
|
*/
|
|
sqlite3SelectDelete(db, pSub1);
|
|
|
|
#if SELECTTRACE_ENABLED
|
|
if( sqlite3SelectTrace & 0x100 ){
|
|
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
|
|
sqlite3TreeViewSelect(0, p, 0);
|
|
}
|
|
#endif
|
|
|
|
return 1;
|
|
}
|
|
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
|
|
|
|
|
|
|
|
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
|
|
/*
|
|
** Make copies of relevant WHERE clause terms of the outer query into
|
|
** the WHERE clause of subquery. Example:
|
|
**
|
|
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
|
|
**
|
|
** Transformed into:
|
|
**
|
|
** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
|
|
** WHERE x=5 AND y=10;
|
|
**
|
|
** The hope is that the terms added to the inner query will make it more
|
|
** efficient.
|
|
**
|
|
** Do not attempt this optimization if:
|
|
**
|
|
** (1) The inner query is an aggregate. (In that case, we'd really want
|
|
** to copy the outer WHERE-clause terms onto the HAVING clause of the
|
|
** inner query. But they probably won't help there so do not bother.)
|
|
**
|
|
** (2) The inner query is the recursive part of a common table expression.
|
|
**
|
|
** (3) The inner query has a LIMIT clause (since the changes to the WHERE
|
|
** close would change the meaning of the LIMIT).
|
|
**
|
|
** (4) The inner query is the right operand of a LEFT JOIN. (The caller
|
|
** enforces this restriction since this routine does not have enough
|
|
** information to know.)
|
|
**
|
|
** (5) The WHERE clause expression originates in the ON or USING clause
|
|
** of a LEFT JOIN.
|
|
**
|
|
** Return 0 if no changes are made and non-zero if one or more WHERE clause
|
|
** terms are duplicated into the subquery.
|
|
*/
|
|
static int pushDownWhereTerms(
|
|
sqlite3 *db, /* The database connection (for malloc()) */
|
|
Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
|
|
Expr *pWhere, /* The WHERE clause of the outer query */
|
|
int iCursor /* Cursor number of the subquery */
|
|
){
|
|
Expr *pNew;
|
|
int nChng = 0;
|
|
if( pWhere==0 ) return 0;
|
|
if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
|
|
return 0; /* restrictions (1) and (2) */
|
|
}
|
|
if( pSubq->pLimit!=0 ){
|
|
return 0; /* restriction (3) */
|
|
}
|
|
while( pWhere->op==TK_AND ){
|
|
nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
|
|
pWhere = pWhere->pLeft;
|
|
}
|
|
if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
|
|
if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
|
|
nChng++;
|
|
while( pSubq ){
|
|
pNew = sqlite3ExprDup(db, pWhere, 0);
|
|
pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
|
|
pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
|
|
pSubq = pSubq->pPrior;
|
|
}
|
|
}
|
|
return nChng;
|
|
}
|
|
#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
|
|
|
|
/*
|
|
** Based on the contents of the AggInfo structure indicated by the first
|
|
** argument, this function checks if the following are true:
|
|
**
|
|
** * the query contains just a single aggregate function,
|
|
** * the aggregate function is either min() or max(), and
|
|
** * the argument to the aggregate function is a column value.
|
|
**
|
|
** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
|
|
** is returned as appropriate. Also, *ppMinMax is set to point to the
|
|
** list of arguments passed to the aggregate before returning.
|
|
**
|
|
** Or, if the conditions above are not met, *ppMinMax is set to 0 and
|
|
** WHERE_ORDERBY_NORMAL is returned.
|
|
*/
|
|
static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
|
|
int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
|
|
|
|
*ppMinMax = 0;
|
|
if( pAggInfo->nFunc==1 ){
|
|
Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
|
|
ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
|
|
|
|
assert( pExpr->op==TK_AGG_FUNCTION );
|
|
if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
|
|
const char *zFunc = pExpr->u.zToken;
|
|
if( sqlite3StrICmp(zFunc, "min")==0 ){
|
|
eRet = WHERE_ORDERBY_MIN;
|
|
*ppMinMax = pEList;
|
|
}else if( sqlite3StrICmp(zFunc, "max")==0 ){
|
|
eRet = WHERE_ORDERBY_MAX;
|
|
*ppMinMax = pEList;
|
|
}
|
|
}
|
|
}
|
|
|
|
assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
|
|
return eRet;
|
|
}
|
|
|
|
/*
|
|
** The select statement passed as the first argument is an aggregate query.
|
|
** The second argument is the associated aggregate-info object. This
|
|
** function tests if the SELECT is of the form:
|
|
**
|
|
** SELECT count(*) FROM <tbl>
|
|
**
|
|
** where table is a database table, not a sub-select or view. If the query
|
|
** does match this pattern, then a pointer to the Table object representing
|
|
** <tbl> is returned. Otherwise, 0 is returned.
|
|
*/
|
|
static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
|
|
Table *pTab;
|
|
Expr *pExpr;
|
|
|
|
assert( !p->pGroupBy );
|
|
|
|
if( p->pWhere || p->pEList->nExpr!=1
|
|
|| p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
|
|
){
|
|
return 0;
|
|
}
|
|
pTab = p->pSrc->a[0].pTab;
|
|
pExpr = p->pEList->a[0].pExpr;
|
|
assert( pTab && !pTab->pSelect && pExpr );
|
|
|
|
if( IsVirtual(pTab) ) return 0;
|
|
if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
|
|
if( NEVER(pAggInfo->nFunc==0) ) return 0;
|
|
if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
|
|
if( pExpr->flags&EP_Distinct ) return 0;
|
|
|
|
return pTab;
|
|
}
|
|
|
|
/*
|
|
** If the source-list item passed as an argument was augmented with an
|
|
** INDEXED BY clause, then try to locate the specified index. If there
|
|
** was such a clause and the named index cannot be found, return
|
|
** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
|
|
** pFrom->pIndex and return SQLITE_OK.
|
|
*/
|
|
int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
|
|
if( pFrom->pTab && pFrom->fg.isIndexedBy ){
|
|
Table *pTab = pFrom->pTab;
|
|
char *zIndexedBy = pFrom->u1.zIndexedBy;
|
|
Index *pIdx;
|
|
for(pIdx=pTab->pIndex;
|
|
pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
|
|
pIdx=pIdx->pNext
|
|
);
|
|
if( !pIdx ){
|
|
sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
|
|
pParse->checkSchema = 1;
|
|
return SQLITE_ERROR;
|
|
}
|
|
pFrom->pIBIndex = pIdx;
|
|
}
|
|
return SQLITE_OK;
|
|
}
|
|
/*
|
|
** Detect compound SELECT statements that use an ORDER BY clause with
|
|
** an alternative collating sequence.
|
|
**
|
|
** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
|
|
**
|
|
** These are rewritten as a subquery:
|
|
**
|
|
** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
|
|
** ORDER BY ... COLLATE ...
|
|
**
|
|
** This transformation is necessary because the multiSelectOrderBy() routine
|
|
** above that generates the code for a compound SELECT with an ORDER BY clause
|
|
** uses a merge algorithm that requires the same collating sequence on the
|
|
** result columns as on the ORDER BY clause. See ticket
|
|
** http://www.sqlite.org/src/info/6709574d2a
|
|
**
|
|
** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
|
|
** The UNION ALL operator works fine with multiSelectOrderBy() even when
|
|
** there are COLLATE terms in the ORDER BY.
|
|
*/
|
|
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
|
|
int i;
|
|
Select *pNew;
|
|
Select *pX;
|
|
sqlite3 *db;
|
|
struct ExprList_item *a;
|
|
SrcList *pNewSrc;
|
|
Parse *pParse;
|
|
Token dummy;
|
|
|
|
if( p->pPrior==0 ) return WRC_Continue;
|
|
if( p->pOrderBy==0 ) return WRC_Continue;
|
|
for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
|
|
if( pX==0 ) return WRC_Continue;
|
|
a = p->pOrderBy->a;
|
|
for(i=p->pOrderBy->nExpr-1; i>=0; i--){
|
|
if( a[i].pExpr->flags & EP_Collate ) break;
|
|
}
|
|
if( i<0 ) return WRC_Continue;
|
|
|
|
/* If we reach this point, that means the transformation is required. */
|
|
|
|
pParse = pWalker->pParse;
|
|
db = pParse->db;
|
|
pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
|
|
if( pNew==0 ) return WRC_Abort;
|
|
memset(&dummy, 0, sizeof(dummy));
|
|
pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
|
|
if( pNewSrc==0 ) return WRC_Abort;
|
|
*pNew = *p;
|
|
p->pSrc = pNewSrc;
|
|
p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
|
|
p->op = TK_SELECT;
|
|
p->pWhere = 0;
|
|
pNew->pGroupBy = 0;
|
|
pNew->pHaving = 0;
|
|
pNew->pOrderBy = 0;
|
|
p->pPrior = 0;
|
|
p->pNext = 0;
|
|
p->pWith = 0;
|
|
p->selFlags &= ~SF_Compound;
|
|
assert( (p->selFlags & SF_Converted)==0 );
|
|
p->selFlags |= SF_Converted;
|
|
assert( pNew->pPrior!=0 );
|
|
pNew->pPrior->pNext = pNew;
|
|
pNew->pLimit = 0;
|
|
pNew->pOffset = 0;
|
|
return WRC_Continue;
|
|
}
|
|
|
|
/*
|
|
** Check to see if the FROM clause term pFrom has table-valued function
|
|
** arguments. If it does, leave an error message in pParse and return
|
|
** non-zero, since pFrom is not allowed to be a table-valued function.
|
|
*/
|
|
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
|
|
if( pFrom->fg.isTabFunc ){
|
|
sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_CTE
|
|
/*
|
|
** Argument pWith (which may be NULL) points to a linked list of nested
|
|
** WITH contexts, from inner to outermost. If the table identified by
|
|
** FROM clause element pItem is really a common-table-expression (CTE)
|
|
** then return a pointer to the CTE definition for that table. Otherwise
|
|
** return NULL.
|
|
**
|
|
** If a non-NULL value is returned, set *ppContext to point to the With
|
|
** object that the returned CTE belongs to.
|
|
*/
|
|
static struct Cte *searchWith(
|
|
With *pWith, /* Current innermost WITH clause */
|
|
struct SrcList_item *pItem, /* FROM clause element to resolve */
|
|
With **ppContext /* OUT: WITH clause return value belongs to */
|
|
){
|
|
const char *zName;
|
|
if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
|
|
With *p;
|
|
for(p=pWith; p; p=p->pOuter){
|
|
int i;
|
|
for(i=0; i<p->nCte; i++){
|
|
if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
|
|
*ppContext = p;
|
|
return &p->a[i];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/* The code generator maintains a stack of active WITH clauses
|
|
** with the inner-most WITH clause being at the top of the stack.
|
|
**
|
|
** This routine pushes the WITH clause passed as the second argument
|
|
** onto the top of the stack. If argument bFree is true, then this
|
|
** WITH clause will never be popped from the stack. In this case it
|
|
** should be freed along with the Parse object. In other cases, when
|
|
** bFree==0, the With object will be freed along with the SELECT
|
|
** statement with which it is associated.
|
|
*/
|
|
void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
|
|
assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
|
|
if( pWith ){
|
|
assert( pParse->pWith!=pWith );
|
|
pWith->pOuter = pParse->pWith;
|
|
pParse->pWith = pWith;
|
|
if( bFree ) pParse->pWithToFree = pWith;
|
|
}
|
|
}
|
|
|
|
/*
|
|
** This function checks if argument pFrom refers to a CTE declared by
|
|
** a WITH clause on the stack currently maintained by the parser. And,
|
|
** if currently processing a CTE expression, if it is a recursive
|
|
** reference to the current CTE.
|
|
**
|
|
** If pFrom falls into either of the two categories above, pFrom->pTab
|
|
** and other fields are populated accordingly. The caller should check
|
|
** (pFrom->pTab!=0) to determine whether or not a successful match
|
|
** was found.
|
|
**
|
|
** Whether or not a match is found, SQLITE_OK is returned if no error
|
|
** occurs. If an error does occur, an error message is stored in the
|
|
** parser and some error code other than SQLITE_OK returned.
|
|
*/
|
|
static int withExpand(
|
|
Walker *pWalker,
|
|
struct SrcList_item *pFrom
|
|
){
|
|
Parse *pParse = pWalker->pParse;
|
|
sqlite3 *db = pParse->db;
|
|
struct Cte *pCte; /* Matched CTE (or NULL if no match) */
|
|
With *pWith; /* WITH clause that pCte belongs to */
|
|
|
|
assert( pFrom->pTab==0 );
|
|
|
|
pCte = searchWith(pParse->pWith, pFrom, &pWith);
|
|
if( pCte ){
|
|
Table *pTab;
|
|
ExprList *pEList;
|
|
Select *pSel;
|
|
Select *pLeft; /* Left-most SELECT statement */
|
|
int bMayRecursive; /* True if compound joined by UNION [ALL] */
|
|
With *pSavedWith; /* Initial value of pParse->pWith */
|
|
|
|
/* If pCte->zCteErr is non-NULL at this point, then this is an illegal
|
|
** recursive reference to CTE pCte. Leave an error in pParse and return
|
|
** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
|
|
** In this case, proceed. */
|
|
if( pCte->zCteErr ){
|
|
sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
|
|
return SQLITE_ERROR;
|
|
}
|
|
if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
|
|
|
|
assert( pFrom->pTab==0 );
|
|
pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
|
|
if( pTab==0 ) return WRC_Abort;
|
|
pTab->nRef = 1;
|
|
pTab->zName = sqlite3DbStrDup(db, pCte->zName);
|
|
pTab->iPKey = -1;
|
|
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
|
|
pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
|
|
pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
|
|
if( db->mallocFailed ) return SQLITE_NOMEM;
|
|
assert( pFrom->pSelect );
|
|
|
|
/* Check if this is a recursive CTE. */
|
|
pSel = pFrom->pSelect;
|
|
bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
|
|
if( bMayRecursive ){
|
|
int i;
|
|
SrcList *pSrc = pFrom->pSelect->pSrc;
|
|
for(i=0; i<pSrc->nSrc; i++){
|
|
struct SrcList_item *pItem = &pSrc->a[i];
|
|
if( pItem->zDatabase==0
|
|
&& pItem->zName!=0
|
|
&& 0==sqlite3StrICmp(pItem->zName, pCte->zName)
|
|
){
|
|
pItem->pTab = pTab;
|
|
pItem->fg.isRecursive = 1;
|
|
pTab->nRef++;
|
|
pSel->selFlags |= SF_Recursive;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Only one recursive reference is permitted. */
|
|
if( pTab->nRef>2 ){
|
|
sqlite3ErrorMsg(
|
|
pParse, "multiple references to recursive table: %s", pCte->zName
|
|
);
|
|
return SQLITE_ERROR;
|
|
}
|
|
assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
|
|
|
|
pCte->zCteErr = "circular reference: %s";
|
|
pSavedWith = pParse->pWith;
|
|
pParse->pWith = pWith;
|
|
sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
|
|
pParse->pWith = pWith;
|
|
|
|
for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
|
|
pEList = pLeft->pEList;
|
|
if( pCte->pCols ){
|
|
if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
|
|
sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
|
|
pCte->zName, pEList->nExpr, pCte->pCols->nExpr
|
|
);
|
|
pParse->pWith = pSavedWith;
|
|
return SQLITE_ERROR;
|
|
}
|
|
pEList = pCte->pCols;
|
|
}
|
|
|
|
sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
|
|
if( bMayRecursive ){
|
|
if( pSel->selFlags & SF_Recursive ){
|
|
pCte->zCteErr = "multiple recursive references: %s";
|
|
}else{
|
|
pCte->zCteErr = "recursive reference in a subquery: %s";
|
|
}
|
|
sqlite3WalkSelect(pWalker, pSel);
|
|
}
|
|
pCte->zCteErr = 0;
|
|
pParse->pWith = pSavedWith;
|
|
}
|
|
|
|
return SQLITE_OK;
|
|
}
|
|
#endif
|
|
|
|
#ifndef SQLITE_OMIT_CTE
|
|
/*
|
|
** If the SELECT passed as the second argument has an associated WITH
|
|
** clause, pop it from the stack stored as part of the Parse object.
|
|
**
|
|
** This function is used as the xSelectCallback2() callback by
|
|
** sqlite3SelectExpand() when walking a SELECT tree to resolve table
|
|
** names and other FROM clause elements.
|
|
*/
|
|
static void selectPopWith(Walker *pWalker, Select *p){
|
|
Parse *pParse = pWalker->pParse;
|
|
With *pWith = findRightmost(p)->pWith;
|
|
if( pWith!=0 ){
|
|
assert( pParse->pWith==pWith );
|
|
pParse->pWith = pWith->pOuter;
|
|
}
|
|
}
|
|
#else
|
|
#define selectPopWith 0
|
|
#endif
|
|
|
|
/*
|
|
** This routine is a Walker callback for "expanding" a SELECT statement.
|
|
** "Expanding" means to do the following:
|
|
**
|
|
** (1) Make sure VDBE cursor numbers have been assigned to every
|
|
** element of the FROM clause.
|
|
**
|
|
** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
|
|
** defines FROM clause. When views appear in the FROM clause,
|
|
** fill pTabList->a[].pSelect with a copy of the SELECT statement
|
|
** that implements the view. A copy is made of the view's SELECT
|
|
** statement so that we can freely modify or delete that statement
|
|
** without worrying about messing up the persistent representation
|
|
** of the view.
|
|
**
|
|
** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
|
|
** on joins and the ON and USING clause of joins.
|
|
**
|
|
** (4) Scan the list of columns in the result set (pEList) looking
|
|
** for instances of the "*" operator or the TABLE.* operator.
|
|
** If found, expand each "*" to be every column in every table
|
|
** and TABLE.* to be every column in TABLE.
|
|
**
|
|
*/
|
|
static int selectExpander(Walker *pWalker, Select *p){
|
|
Parse *pParse = pWalker->pParse;
|
|
int i, j, k;
|
|
SrcList *pTabList;
|
|
ExprList *pEList;
|
|
struct SrcList_item *pFrom;
|
|
sqlite3 *db = pParse->db;
|
|
Expr *pE, *pRight, *pExpr;
|
|
u16 selFlags = p->selFlags;
|
|
|
|
p->selFlags |= SF_Expanded;
|
|
if( db->mallocFailed ){
|
|
return WRC_Abort;
|
|
}
|
|
if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
|
|
return WRC_Prune;
|
|
}
|
|
pTabList = p->pSrc;
|
|
pEList = p->pEList;
|
|
if( pWalker->xSelectCallback2==selectPopWith ){
|
|
sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
|
|
}
|
|
|
|
/* Make sure cursor numbers have been assigned to all entries in
|
|
** the FROM clause of the SELECT statement.
|
|
*/
|
|
sqlite3SrcListAssignCursors(pParse, pTabList);
|
|
|
|
/* Look up every table named in the FROM clause of the select. If
|
|
** an entry of the FROM clause is a subquery instead of a table or view,
|
|
** then create a transient table structure to describe the subquery.
|
|
*/
|
|
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
|
|
Table *pTab;
|
|
assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
|
|
if( pFrom->fg.isRecursive ) continue;
|
|
assert( pFrom->pTab==0 );
|
|
#ifndef SQLITE_OMIT_CTE
|
|
if( withExpand(pWalker, pFrom) ) return WRC_Abort;
|
|
if( pFrom->pTab ) {} else
|
|
#endif
|
|
if( pFrom->zName==0 ){
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
Select *pSel = pFrom->pSelect;
|
|
/* A sub-query in the FROM clause of a SELECT */
|
|
assert( pSel!=0 );
|
|
assert( pFrom->pTab==0 );
|
|
if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
|
|
pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
|
|
if( pTab==0 ) return WRC_Abort;
|
|
pTab->nRef = 1;
|
|
pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
|
|
while( pSel->pPrior ){ pSel = pSel->pPrior; }
|
|
sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
|
|
pTab->iPKey = -1;
|
|
pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
|
|
pTab->tabFlags |= TF_Ephemeral;
|
|
#endif
|
|
}else{
|
|
/* An ordinary table or view name in the FROM clause */
|
|
assert( pFrom->pTab==0 );
|
|
pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
|
|
if( pTab==0 ) return WRC_Abort;
|
|
if( pTab->nRef==0xffff ){
|
|
sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
|
|
pTab->zName);
|
|
pFrom->pTab = 0;
|
|
return WRC_Abort;
|
|
}
|
|
pTab->nRef++;
|
|
if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
|
|
return WRC_Abort;
|
|
}
|
|
#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
|
|
if( IsVirtual(pTab) || pTab->pSelect ){
|
|
i16 nCol;
|
|
if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
|
|
assert( pFrom->pSelect==0 );
|
|
pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
|
|
sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
|
|
nCol = pTab->nCol;
|
|
pTab->nCol = -1;
|
|
sqlite3WalkSelect(pWalker, pFrom->pSelect);
|
|
pTab->nCol = nCol;
|
|
}
|
|
#endif
|
|
}
|
|
|
|
/* Locate the index named by the INDEXED BY clause, if any. */
|
|
if( sqlite3IndexedByLookup(pParse, pFrom) ){
|
|
return WRC_Abort;
|
|
}
|
|
}
|
|
|
|
/* Process NATURAL keywords, and ON and USING clauses of joins.
|
|
*/
|
|
if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
|
|
return WRC_Abort;
|
|
}
|
|
|
|
/* For every "*" that occurs in the column list, insert the names of
|
|
** all columns in all tables. And for every TABLE.* insert the names
|
|
** of all columns in TABLE. The parser inserted a special expression
|
|
** with the TK_ASTERISK operator for each "*" that it found in the column
|
|
** list. The following code just has to locate the TK_ASTERISK
|
|
** expressions and expand each one to the list of all columns in
|
|
** all tables.
|
|
**
|
|
** The first loop just checks to see if there are any "*" operators
|
|
** that need expanding.
|
|
*/
|
|
for(k=0; k<pEList->nExpr; k++){
|
|
pE = pEList->a[k].pExpr;
|
|
if( pE->op==TK_ASTERISK ) break;
|
|
assert( pE->op!=TK_DOT || pE->pRight!=0 );
|
|
assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
|
|
if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
|
|
}
|
|
if( k<pEList->nExpr ){
|
|
/*
|
|
** If we get here it means the result set contains one or more "*"
|
|
** operators that need to be expanded. Loop through each expression
|
|
** in the result set and expand them one by one.
|
|
*/
|
|
struct ExprList_item *a = pEList->a;
|
|
ExprList *pNew = 0;
|
|
int flags = pParse->db->flags;
|
|
int longNames = (flags & SQLITE_FullColNames)!=0
|
|
&& (flags & SQLITE_ShortColNames)==0;
|
|
|
|
for(k=0; k<pEList->nExpr; k++){
|
|
pE = a[k].pExpr;
|
|
pRight = pE->pRight;
|
|
assert( pE->op!=TK_DOT || pRight!=0 );
|
|
if( pE->op!=TK_ASTERISK
|
|
&& (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
|
|
){
|
|
/* This particular expression does not need to be expanded.
|
|
*/
|
|
pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
|
|
if( pNew ){
|
|
pNew->a[pNew->nExpr-1].zName = a[k].zName;
|
|
pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
|
|
a[k].zName = 0;
|
|
a[k].zSpan = 0;
|
|
}
|
|
a[k].pExpr = 0;
|
|
}else{
|
|
/* This expression is a "*" or a "TABLE.*" and needs to be
|
|
** expanded. */
|
|
int tableSeen = 0; /* Set to 1 when TABLE matches */
|
|
char *zTName = 0; /* text of name of TABLE */
|
|
if( pE->op==TK_DOT ){
|
|
assert( pE->pLeft!=0 );
|
|
assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
|
|
zTName = pE->pLeft->u.zToken;
|
|
}
|
|
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
|
|
Table *pTab = pFrom->pTab;
|
|
Select *pSub = pFrom->pSelect;
|
|
char *zTabName = pFrom->zAlias;
|
|
const char *zSchemaName = 0;
|
|
int iDb;
|
|
if( zTabName==0 ){
|
|
zTabName = pTab->zName;
|
|
}
|
|
if( db->mallocFailed ) break;
|
|
if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
|
|
pSub = 0;
|
|
if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
|
|
continue;
|
|
}
|
|
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
|
zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
|
|
}
|
|
for(j=0; j<pTab->nCol; j++){
|
|
char *zName = pTab->aCol[j].zName;
|
|
char *zColname; /* The computed column name */
|
|
char *zToFree; /* Malloced string that needs to be freed */
|
|
Token sColname; /* Computed column name as a token */
|
|
|
|
assert( zName );
|
|
if( zTName && pSub
|
|
&& sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
|
|
){
|
|
continue;
|
|
}
|
|
|
|
/* If a column is marked as 'hidden', omit it from the expanded
|
|
** result-set list unless the SELECT has the SF_IncludeHidden
|
|
** bit set.
|
|
*/
|
|
if( (p->selFlags & SF_IncludeHidden)==0
|
|
&& IsHiddenColumn(&pTab->aCol[j])
|
|
){
|
|
continue;
|
|
}
|
|
tableSeen = 1;
|
|
|
|
if( i>0 && zTName==0 ){
|
|
if( (pFrom->fg.jointype & JT_NATURAL)!=0
|
|
&& tableAndColumnIndex(pTabList, i, zName, 0, 0)
|
|
){
|
|
/* In a NATURAL join, omit the join columns from the
|
|
** table to the right of the join */
|
|
continue;
|
|
}
|
|
if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
|
|
/* In a join with a USING clause, omit columns in the
|
|
** using clause from the table on the right. */
|
|
continue;
|
|
}
|
|
}
|
|
pRight = sqlite3Expr(db, TK_ID, zName);
|
|
zColname = zName;
|
|
zToFree = 0;
|
|
if( longNames || pTabList->nSrc>1 ){
|
|
Expr *pLeft;
|
|
pLeft = sqlite3Expr(db, TK_ID, zTabName);
|
|
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
|
|
if( zSchemaName ){
|
|
pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
|
|
pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
|
|
}
|
|
if( longNames ){
|
|
zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
|
|
zToFree = zColname;
|
|
}
|
|
}else{
|
|
pExpr = pRight;
|
|
}
|
|
pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
|
|
sqlite3TokenInit(&sColname, zColname);
|
|
sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
|
|
if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
|
|
struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
|
|
if( pSub ){
|
|
pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
|
|
testcase( pX->zSpan==0 );
|
|
}else{
|
|
pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
|
|
zSchemaName, zTabName, zColname);
|
|
testcase( pX->zSpan==0 );
|
|
}
|
|
pX->bSpanIsTab = 1;
|
|
}
|
|
sqlite3DbFree(db, zToFree);
|
|
}
|
|
}
|
|
if( !tableSeen ){
|
|
if( zTName ){
|
|
sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
|
|
}else{
|
|
sqlite3ErrorMsg(pParse, "no tables specified");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
sqlite3ExprListDelete(db, pEList);
|
|
p->pEList = pNew;
|
|
}
|
|
#if SQLITE_MAX_COLUMN
|
|
if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
|
|
sqlite3ErrorMsg(pParse, "too many columns in result set");
|
|
return WRC_Abort;
|
|
}
|
|
#endif
|
|
return WRC_Continue;
|
|
}
|
|
|
|
/*
|
|
** No-op routine for the parse-tree walker.
|
|
**
|
|
** When this routine is the Walker.xExprCallback then expression trees
|
|
** are walked without any actions being taken at each node. Presumably,
|
|
** when this routine is used for Walker.xExprCallback then
|
|
** Walker.xSelectCallback is set to do something useful for every
|
|
** subquery in the parser tree.
|
|
*/
|
|
int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
|
|
UNUSED_PARAMETER2(NotUsed, NotUsed2);
|
|
return WRC_Continue;
|
|
}
|
|
|
|
/*
|
|
** This routine "expands" a SELECT statement and all of its subqueries.
|
|
** For additional information on what it means to "expand" a SELECT
|
|
** statement, see the comment on the selectExpand worker callback above.
|
|
**
|
|
** Expanding a SELECT statement is the first step in processing a
|
|
** SELECT statement. The SELECT statement must be expanded before
|
|
** name resolution is performed.
|
|
**
|
|
** If anything goes wrong, an error message is written into pParse.
|
|
** The calling function can detect the problem by looking at pParse->nErr
|
|
** and/or pParse->db->mallocFailed.
|
|
*/
|
|
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
|
|
Walker w;
|
|
memset(&w, 0, sizeof(w));
|
|
w.xExprCallback = sqlite3ExprWalkNoop;
|
|
w.pParse = pParse;
|
|
if( pParse->hasCompound ){
|
|
w.xSelectCallback = convertCompoundSelectToSubquery;
|
|
sqlite3WalkSelect(&w, pSelect);
|
|
}
|
|
w.xSelectCallback = selectExpander;
|
|
if( (pSelect->selFlags & SF_MultiValue)==0 ){
|
|
w.xSelectCallback2 = selectPopWith;
|
|
}
|
|
sqlite3WalkSelect(&w, pSelect);
|
|
}
|
|
|
|
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
/*
|
|
** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
|
|
** interface.
|
|
**
|
|
** For each FROM-clause subquery, add Column.zType and Column.zColl
|
|
** information to the Table structure that represents the result set
|
|
** of that subquery.
|
|
**
|
|
** The Table structure that represents the result set was constructed
|
|
** by selectExpander() but the type and collation information was omitted
|
|
** at that point because identifiers had not yet been resolved. This
|
|
** routine is called after identifier resolution.
|
|
*/
|
|
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
|
|
Parse *pParse;
|
|
int i;
|
|
SrcList *pTabList;
|
|
struct SrcList_item *pFrom;
|
|
|
|
assert( p->selFlags & SF_Resolved );
|
|
assert( (p->selFlags & SF_HasTypeInfo)==0 );
|
|
p->selFlags |= SF_HasTypeInfo;
|
|
pParse = pWalker->pParse;
|
|
pTabList = p->pSrc;
|
|
for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
|
|
Table *pTab = pFrom->pTab;
|
|
assert( pTab!=0 );
|
|
if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
|
|
/* A sub-query in the FROM clause of a SELECT */
|
|
Select *pSel = pFrom->pSelect;
|
|
if( pSel ){
|
|
while( pSel->pPrior ) pSel = pSel->pPrior;
|
|
selectAddColumnTypeAndCollation(pParse, pTab, pSel);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
|
|
|
|
/*
|
|
** This routine adds datatype and collating sequence information to
|
|
** the Table structures of all FROM-clause subqueries in a
|
|
** SELECT statement.
|
|
**
|
|
** Use this routine after name resolution.
|
|
*/
|
|
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
Walker w;
|
|
memset(&w, 0, sizeof(w));
|
|
w.xSelectCallback2 = selectAddSubqueryTypeInfo;
|
|
w.xExprCallback = sqlite3ExprWalkNoop;
|
|
w.pParse = pParse;
|
|
sqlite3WalkSelect(&w, pSelect);
|
|
#endif
|
|
}
|
|
|
|
|
|
/*
|
|
** This routine sets up a SELECT statement for processing. The
|
|
** following is accomplished:
|
|
**
|
|
** * VDBE Cursor numbers are assigned to all FROM-clause terms.
|
|
** * Ephemeral Table objects are created for all FROM-clause subqueries.
|
|
** * ON and USING clauses are shifted into WHERE statements
|
|
** * Wildcards "*" and "TABLE.*" in result sets are expanded.
|
|
** * Identifiers in expression are matched to tables.
|
|
**
|
|
** This routine acts recursively on all subqueries within the SELECT.
|
|
*/
|
|
void sqlite3SelectPrep(
|
|
Parse *pParse, /* The parser context */
|
|
Select *p, /* The SELECT statement being coded. */
|
|
NameContext *pOuterNC /* Name context for container */
|
|
){
|
|
sqlite3 *db;
|
|
if( NEVER(p==0) ) return;
|
|
db = pParse->db;
|
|
if( db->mallocFailed ) return;
|
|
if( p->selFlags & SF_HasTypeInfo ) return;
|
|
sqlite3SelectExpand(pParse, p);
|
|
if( pParse->nErr || db->mallocFailed ) return;
|
|
sqlite3ResolveSelectNames(pParse, p, pOuterNC);
|
|
if( pParse->nErr || db->mallocFailed ) return;
|
|
sqlite3SelectAddTypeInfo(pParse, p);
|
|
}
|
|
|
|
/*
|
|
** Reset the aggregate accumulator.
|
|
**
|
|
** The aggregate accumulator is a set of memory cells that hold
|
|
** intermediate results while calculating an aggregate. This
|
|
** routine generates code that stores NULLs in all of those memory
|
|
** cells.
|
|
*/
|
|
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i;
|
|
struct AggInfo_func *pFunc;
|
|
int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
|
|
if( nReg==0 ) return;
|
|
#ifdef SQLITE_DEBUG
|
|
/* Verify that all AggInfo registers are within the range specified by
|
|
** AggInfo.mnReg..AggInfo.mxReg */
|
|
assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
|
|
for(i=0; i<pAggInfo->nColumn; i++){
|
|
assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
|
|
&& pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
|
|
}
|
|
for(i=0; i<pAggInfo->nFunc; i++){
|
|
assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
|
|
&& pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
|
|
}
|
|
#endif
|
|
sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
|
|
for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
|
|
if( pFunc->iDistinct>=0 ){
|
|
Expr *pE = pFunc->pExpr;
|
|
assert( !ExprHasProperty(pE, EP_xIsSelect) );
|
|
if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
|
|
sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
|
|
"argument");
|
|
pFunc->iDistinct = -1;
|
|
}else{
|
|
KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
|
|
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
|
|
(char*)pKeyInfo, P4_KEYINFO);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Invoke the OP_AggFinalize opcode for every aggregate function
|
|
** in the AggInfo structure.
|
|
*/
|
|
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i;
|
|
struct AggInfo_func *pF;
|
|
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
|
|
ExprList *pList = pF->pExpr->x.pList;
|
|
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
|
|
sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
|
|
(void*)pF->pFunc, P4_FUNCDEF);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Update the accumulator memory cells for an aggregate based on
|
|
** the current cursor position.
|
|
*/
|
|
static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
|
|
Vdbe *v = pParse->pVdbe;
|
|
int i;
|
|
int regHit = 0;
|
|
int addrHitTest = 0;
|
|
struct AggInfo_func *pF;
|
|
struct AggInfo_col *pC;
|
|
|
|
pAggInfo->directMode = 1;
|
|
for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
|
|
int nArg;
|
|
int addrNext = 0;
|
|
int regAgg;
|
|
ExprList *pList = pF->pExpr->x.pList;
|
|
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
|
|
if( pList ){
|
|
nArg = pList->nExpr;
|
|
regAgg = sqlite3GetTempRange(pParse, nArg);
|
|
sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
|
|
}else{
|
|
nArg = 0;
|
|
regAgg = 0;
|
|
}
|
|
if( pF->iDistinct>=0 ){
|
|
addrNext = sqlite3VdbeMakeLabel(v);
|
|
testcase( nArg==0 ); /* Error condition */
|
|
testcase( nArg>1 ); /* Also an error */
|
|
codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
|
|
}
|
|
if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
|
|
CollSeq *pColl = 0;
|
|
struct ExprList_item *pItem;
|
|
int j;
|
|
assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
|
|
for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
|
|
pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
|
|
}
|
|
if( !pColl ){
|
|
pColl = pParse->db->pDfltColl;
|
|
}
|
|
if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
|
|
sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
|
|
}
|
|
sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
|
|
(void*)pF->pFunc, P4_FUNCDEF);
|
|
sqlite3VdbeChangeP5(v, (u8)nArg);
|
|
sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
|
|
sqlite3ReleaseTempRange(pParse, regAgg, nArg);
|
|
if( addrNext ){
|
|
sqlite3VdbeResolveLabel(v, addrNext);
|
|
sqlite3ExprCacheClear(pParse);
|
|
}
|
|
}
|
|
|
|
/* Before populating the accumulator registers, clear the column cache.
|
|
** Otherwise, if any of the required column values are already present
|
|
** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
|
|
** to pC->iMem. But by the time the value is used, the original register
|
|
** may have been used, invalidating the underlying buffer holding the
|
|
** text or blob value. See ticket [883034dcb5].
|
|
**
|
|
** Another solution would be to change the OP_SCopy used to copy cached
|
|
** values to an OP_Copy.
|
|
*/
|
|
if( regHit ){
|
|
addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
|
|
}
|
|
sqlite3ExprCacheClear(pParse);
|
|
for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
|
|
sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
|
|
}
|
|
pAggInfo->directMode = 0;
|
|
sqlite3ExprCacheClear(pParse);
|
|
if( addrHitTest ){
|
|
sqlite3VdbeJumpHere(v, addrHitTest);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Add a single OP_Explain instruction to the VDBE to explain a simple
|
|
** count(*) query ("SELECT count(*) FROM pTab").
|
|
*/
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
static void explainSimpleCount(
|
|
Parse *pParse, /* Parse context */
|
|
Table *pTab, /* Table being queried */
|
|
Index *pIdx /* Index used to optimize scan, or NULL */
|
|
){
|
|
if( pParse->explain==2 ){
|
|
int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
|
|
char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
|
|
pTab->zName,
|
|
bCover ? " USING COVERING INDEX " : "",
|
|
bCover ? pIdx->zName : ""
|
|
);
|
|
sqlite3VdbeAddOp4(
|
|
pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
|
|
);
|
|
}
|
|
}
|
|
#else
|
|
# define explainSimpleCount(a,b,c)
|
|
#endif
|
|
|
|
/*
|
|
** Generate code for the SELECT statement given in the p argument.
|
|
**
|
|
** The results are returned according to the SelectDest structure.
|
|
** See comments in sqliteInt.h for further information.
|
|
**
|
|
** This routine returns the number of errors. If any errors are
|
|
** encountered, then an appropriate error message is left in
|
|
** pParse->zErrMsg.
|
|
**
|
|
** This routine does NOT free the Select structure passed in. The
|
|
** calling function needs to do that.
|
|
*/
|
|
int sqlite3Select(
|
|
Parse *pParse, /* The parser context */
|
|
Select *p, /* The SELECT statement being coded. */
|
|
SelectDest *pDest /* What to do with the query results */
|
|
){
|
|
int i, j; /* Loop counters */
|
|
WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
|
|
Vdbe *v; /* The virtual machine under construction */
|
|
int isAgg; /* True for select lists like "count(*)" */
|
|
ExprList *pEList = 0; /* List of columns to extract. */
|
|
SrcList *pTabList; /* List of tables to select from */
|
|
Expr *pWhere; /* The WHERE clause. May be NULL */
|
|
ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
|
|
Expr *pHaving; /* The HAVING clause. May be NULL */
|
|
int rc = 1; /* Value to return from this function */
|
|
DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
|
|
SortCtx sSort; /* Info on how to code the ORDER BY clause */
|
|
AggInfo sAggInfo; /* Information used by aggregate queries */
|
|
int iEnd; /* Address of the end of the query */
|
|
sqlite3 *db; /* The database connection */
|
|
|
|
#ifndef SQLITE_OMIT_EXPLAIN
|
|
int iRestoreSelectId = pParse->iSelectId;
|
|
pParse->iSelectId = pParse->iNextSelectId++;
|
|
#endif
|
|
|
|
db = pParse->db;
|
|
if( p==0 || db->mallocFailed || pParse->nErr ){
|
|
return 1;
|
|
}
|
|
if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
|
|
memset(&sAggInfo, 0, sizeof(sAggInfo));
|
|
#if SELECTTRACE_ENABLED
|
|
pParse->nSelectIndent++;
|
|
SELECTTRACE(1,pParse,p, ("begin processing:\n"));
|
|
if( sqlite3SelectTrace & 0x100 ){
|
|
sqlite3TreeViewSelect(0, p, 0);
|
|
}
|
|
#endif
|
|
|
|
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
|
|
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
|
|
assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
|
|
assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
|
|
if( IgnorableOrderby(pDest) ){
|
|
assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
|
|
pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
|
|
pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
|
|
pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
|
|
/* If ORDER BY makes no difference in the output then neither does
|
|
** DISTINCT so it can be removed too. */
|
|
sqlite3ExprListDelete(db, p->pOrderBy);
|
|
p->pOrderBy = 0;
|
|
p->selFlags &= ~SF_Distinct;
|
|
}
|
|
sqlite3SelectPrep(pParse, p, 0);
|
|
memset(&sSort, 0, sizeof(sSort));
|
|
sSort.pOrderBy = p->pOrderBy;
|
|
pTabList = p->pSrc;
|
|
if( pParse->nErr || db->mallocFailed ){
|
|
goto select_end;
|
|
}
|
|
assert( p->pEList!=0 );
|
|
isAgg = (p->selFlags & SF_Aggregate)!=0;
|
|
#if SELECTTRACE_ENABLED
|
|
if( sqlite3SelectTrace & 0x100 ){
|
|
SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
|
|
sqlite3TreeViewSelect(0, p, 0);
|
|
}
|
|
#endif
|
|
|
|
|
|
/* If writing to memory or generating a set
|
|
** only a single column may be output.
|
|
*/
|
|
#ifndef SQLITE_OMIT_SUBQUERY
|
|
if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
|
|
goto select_end;
|
|
}
|
|
#endif
|
|
|
|
/* Try to flatten subqueries in the FROM clause up into the main query
|
|
*/
|
|
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
|
|
for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
|
|
struct SrcList_item *pItem = &pTabList->a[i];
|
|
Select *pSub = pItem->pSelect;
|
|
int isAggSub;
|
|
Table *pTab = pItem->pTab;
|
|
if( pSub==0 ) continue;
|
|
|
|
/* Catch mismatch in the declared columns of a view and the number of
|
|
** columns in the SELECT on the RHS */
|
|
if( pTab->nCol!=pSub->pEList->nExpr ){
|
|
sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
|
|
pTab->nCol, pTab->zName, pSub->pEList->nExpr);
|
|
goto select_end;
|
|
}
|
|
|
|
isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
|
|
if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
|
|
/* This subquery can be absorbed into its parent. */
|
|
if( isAggSub ){
|
|
isAgg = 1;
|
|
p->selFlags |= SF_Aggregate;
|
|
}
|
|
i = -1;
|
|
}
|
|
pTabList = p->pSrc;
|
|
if( db->mallocFailed ) goto select_end;
|
|
if( !IgnorableOrderby(pDest) ){
|
|
sSort.pOrderBy = p->pOrderBy;
|
|
}
|
|
}
|
|
#endif
|
|
|
|
/* Get a pointer the VDBE under construction, allocating a new VDBE if one
|
|
** does not already exist */
|
|
v = sqlite3GetVdbe(pParse);
|
|
if( v==0 ) goto select_end;
|
|
|
|
#ifndef SQLITE_OMIT_COMPOUND_SELECT
|
|
/* Handle compound SELECT statements using the separate multiSelect()
|
|
** procedure.
|
|
*/
|
|
if( p->pPrior ){
|
|
rc = multiSelect(pParse, p, pDest);
|
|
explainSetInteger(pParse->iSelectId, iRestoreSelectId);
|
|
#if SELECTTRACE_ENABLED
|
|
SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
|
|
pParse->nSelectIndent--;
|
|
#endif
|
|
return rc;
|
|
}
|
|
#endif
|
|
|
|
/* Generate code for all sub-queries in the FROM clause
|
|
*/
|
|
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
|
|
for(i=0; i<pTabList->nSrc; i++){
|
|
struct SrcList_item *pItem = &pTabList->a[i];
|
|
SelectDest dest;
|
|
Select *pSub = pItem->pSelect;
|
|
if( pSub==0 ) continue;
|
|
|
|
/* Sometimes the code for a subquery will be generated more than
|
|
** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
|
|
** for example. In that case, do not regenerate the code to manifest
|
|
** a view or the co-routine to implement a view. The first instance
|
|
** is sufficient, though the subroutine to manifest the view does need
|
|
** to be invoked again. */
|
|
if( pItem->addrFillSub ){
|
|
if( pItem->fg.viaCoroutine==0 ){
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
/* Increment Parse.nHeight by the height of the largest expression
|
|
** tree referred to by this, the parent select. The child select
|
|
** may contain expression trees of at most
|
|
** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
|
|
** more conservative than necessary, but much easier than enforcing
|
|
** an exact limit.
|
|
*/
|
|
pParse->nHeight += sqlite3SelectExprHeight(p);
|
|
|
|
/* Make copies of constant WHERE-clause terms in the outer query down
|
|
** inside the subquery. This can help the subquery to run more efficiently.
|
|
*/
|
|
if( (pItem->fg.jointype & JT_OUTER)==0
|
|
&& pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
|
|
){
|
|
#if SELECTTRACE_ENABLED
|
|
if( sqlite3SelectTrace & 0x100 ){
|
|
SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
|
|
sqlite3TreeViewSelect(0, p, 0);
|
|
}
|
|
#endif
|
|
}
|
|
|
|
/* Generate code to implement the subquery
|
|
*/
|
|
if( pTabList->nSrc==1
|
|
&& (p->selFlags & SF_All)==0
|
|
&& OptimizationEnabled(db, SQLITE_SubqCoroutine)
|
|
){
|
|
/* Implement a co-routine that will return a single row of the result
|
|
** set on each invocation.
|
|
*/
|
|
int addrTop = sqlite3VdbeCurrentAddr(v)+1;
|
|
pItem->regReturn = ++pParse->nMem;
|
|
sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
|
|
VdbeComment((v, "%s", pItem->pTab->zName));
|
|
pItem->addrFillSub = addrTop;
|
|
sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
|
|
explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
|
|
sqlite3Select(pParse, pSub, &dest);
|
|
pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
|
|
pItem->fg.viaCoroutine = 1;
|
|
pItem->regResult = dest.iSdst;
|
|
sqlite3VdbeEndCoroutine(v, pItem->regReturn);
|
|
sqlite3VdbeJumpHere(v, addrTop-1);
|
|
sqlite3ClearTempRegCache(pParse);
|
|
}else{
|
|
/* Generate a subroutine that will fill an ephemeral table with
|
|
** the content of this subquery. pItem->addrFillSub will point
|
|
** to the address of the generated subroutine. pItem->regReturn
|
|
** is a register allocated to hold the subroutine return address
|
|
*/
|
|
int topAddr;
|
|
int onceAddr = 0;
|
|
int retAddr;
|
|
assert( pItem->addrFillSub==0 );
|
|
pItem->regReturn = ++pParse->nMem;
|
|
topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
|
|
pItem->addrFillSub = topAddr+1;
|
|
if( pItem->fg.isCorrelated==0 ){
|
|
/* If the subquery is not correlated and if we are not inside of
|
|
** a trigger, then we only need to compute the value of the subquery
|
|
** once. */
|
|
onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
|
|
VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
|
|
}else{
|
|
VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
|
|
}
|
|
sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
|
|
explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
|
|
sqlite3Select(pParse, pSub, &dest);
|
|
pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
|
|
if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
|
|
retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
|
|
VdbeComment((v, "end %s", pItem->pTab->zName));
|
|
sqlite3VdbeChangeP1(v, topAddr, retAddr);
|
|
sqlite3ClearTempRegCache(pParse);
|
|
}
|
|
if( db->mallocFailed ) goto select_end;
|
|
pParse->nHeight -= sqlite3SelectExprHeight(p);
|
|
}
|
|
#endif
|
|
|
|
/* Various elements of the SELECT copied into local variables for
|
|
** convenience */
|
|
pEList = p->pEList;
|
|
pWhere = p->pWhere;
|
|
pGroupBy = p->pGroupBy;
|
|
pHaving = p->pHaving;
|
|
sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
|
|
|
|
#if SELECTTRACE_ENABLED
|
|
if( sqlite3SelectTrace & 0x400 ){
|
|
SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
|
|
sqlite3TreeViewSelect(0, p, 0);
|
|
}
|
|
#endif
|
|
|
|
/* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
|
|
** if the select-list is the same as the ORDER BY list, then this query
|
|
** can be rewritten as a GROUP BY. In other words, this:
|
|
**
|
|
** SELECT DISTINCT xyz FROM ... ORDER BY xyz
|
|
**
|
|
** is transformed to:
|
|
**
|
|
** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
|
|
**
|
|
** The second form is preferred as a single index (or temp-table) may be
|
|
** used for both the ORDER BY and DISTINCT processing. As originally
|
|
** written the query must use a temp-table for at least one of the ORDER
|
|
** BY and DISTINCT, and an index or separate temp-table for the other.
|
|
*/
|
|
if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
|
|
&& sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
|
|
){
|
|
p->selFlags &= ~SF_Distinct;
|
|
pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
|
|
/* Notice that even thought SF_Distinct has been cleared from p->selFlags,
|
|
** the sDistinct.isTnct is still set. Hence, isTnct represents the
|
|
** original setting of the SF_Distinct flag, not the current setting */
|
|
assert( sDistinct.isTnct );
|
|
}
|
|
|
|
/* If there is an ORDER BY clause, then create an ephemeral index to
|
|
** do the sorting. But this sorting ephemeral index might end up
|
|
** being unused if the data can be extracted in pre-sorted order.
|
|
** If that is the case, then the OP_OpenEphemeral instruction will be
|
|
** changed to an OP_Noop once we figure out that the sorting index is
|
|
** not needed. The sSort.addrSortIndex variable is used to facilitate
|
|
** that change.
|
|
*/
|
|
if( sSort.pOrderBy ){
|
|
KeyInfo *pKeyInfo;
|
|
pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
|
|
sSort.iECursor = pParse->nTab++;
|
|
sSort.addrSortIndex =
|
|
sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
|
|
sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
|
|
(char*)pKeyInfo, P4_KEYINFO
|
|
);
|
|
}else{
|
|
sSort.addrSortIndex = -1;
|
|
}
|
|
|
|
/* If the output is destined for a temporary table, open that table.
|
|
*/
|
|
if( pDest->eDest==SRT_EphemTab ){
|
|
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
|
|
}
|
|
|
|
/* Set the limiter.
|
|
*/
|
|
iEnd = sqlite3VdbeMakeLabel(v);
|
|
p->nSelectRow = LARGEST_INT64;
|
|
computeLimitRegisters(pParse, p, iEnd);
|
|
if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
|
|
sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
|
|
sSort.sortFlags |= SORTFLAG_UseSorter;
|
|
}
|
|
|
|
/* Open an ephemeral index to use for the distinct set.
|
|
*/
|
|
if( p->selFlags & SF_Distinct ){
|
|
sDistinct.tabTnct = pParse->nTab++;
|
|
sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
|
|
sDistinct.tabTnct, 0, 0,
|
|
(char*)keyInfoFromExprList(pParse, p->pEList,0,0),
|
|
P4_KEYINFO);
|
|
sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
|
|
sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
|
|
}else{
|
|
sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
|
|
}
|
|
|
|
if( !isAgg && pGroupBy==0 ){
|
|
/* No aggregate functions and no GROUP BY clause */
|
|
u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
|
|
|
|
/* Begin the database scan. */
|
|
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
|
|
p->pEList, wctrlFlags, 0);
|
|
if( pWInfo==0 ) goto select_end;
|
|
if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
|
|
p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
|
|
}
|
|
if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
|
|
sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
|
|
}
|
|
if( sSort.pOrderBy ){
|
|
sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
|
|
if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
|
|
sSort.pOrderBy = 0;
|
|
}
|
|
}
|
|
|
|
/* If sorting index that was created by a prior OP_OpenEphemeral
|
|
** instruction ended up not being needed, then change the OP_OpenEphemeral
|
|
** into an OP_Noop.
|
|
*/
|
|
if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
|
|
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
|
|
}
|
|
|
|
/* Use the standard inner loop. */
|
|
selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
|
|
sqlite3WhereContinueLabel(pWInfo),
|
|
sqlite3WhereBreakLabel(pWInfo));
|
|
|
|
/* End the database scan loop.
|
|
*/
|
|
sqlite3WhereEnd(pWInfo);
|
|
}else{
|
|
/* This case when there exist aggregate functions or a GROUP BY clause
|
|
** or both */
|
|
NameContext sNC; /* Name context for processing aggregate information */
|
|
int iAMem; /* First Mem address for storing current GROUP BY */
|
|
int iBMem; /* First Mem address for previous GROUP BY */
|
|
int iUseFlag; /* Mem address holding flag indicating that at least
|
|
** one row of the input to the aggregator has been
|
|
** processed */
|
|
int iAbortFlag; /* Mem address which causes query abort if positive */
|
|
int groupBySort; /* Rows come from source in GROUP BY order */
|
|
int addrEnd; /* End of processing for this SELECT */
|
|
int sortPTab = 0; /* Pseudotable used to decode sorting results */
|
|
int sortOut = 0; /* Output register from the sorter */
|
|
int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
|
|
|
|
/* Remove any and all aliases between the result set and the
|
|
** GROUP BY clause.
|
|
*/
|
|
if( pGroupBy ){
|
|
int k; /* Loop counter */
|
|
struct ExprList_item *pItem; /* For looping over expression in a list */
|
|
|
|
for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
|
|
pItem->u.x.iAlias = 0;
|
|
}
|
|
for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
|
|
pItem->u.x.iAlias = 0;
|
|
}
|
|
if( p->nSelectRow>100 ) p->nSelectRow = 100;
|
|
}else{
|
|
p->nSelectRow = 1;
|
|
}
|
|
|
|
/* If there is both a GROUP BY and an ORDER BY clause and they are
|
|
** identical, then it may be possible to disable the ORDER BY clause
|
|
** on the grounds that the GROUP BY will cause elements to come out
|
|
** in the correct order. It also may not - the GROUP BY might use a
|
|
** database index that causes rows to be grouped together as required
|
|
** but not actually sorted. Either way, record the fact that the
|
|
** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
|
|
** variable. */
|
|
if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
|
|
orderByGrp = 1;
|
|
}
|
|
|
|
/* Create a label to jump to when we want to abort the query */
|
|
addrEnd = sqlite3VdbeMakeLabel(v);
|
|
|
|
/* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
|
|
** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
|
|
** SELECT statement.
|
|
*/
|
|
memset(&sNC, 0, sizeof(sNC));
|
|
sNC.pParse = pParse;
|
|
sNC.pSrcList = pTabList;
|
|
sNC.pAggInfo = &sAggInfo;
|
|
sAggInfo.mnReg = pParse->nMem+1;
|
|
sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
|
|
sAggInfo.pGroupBy = pGroupBy;
|
|
sqlite3ExprAnalyzeAggList(&sNC, pEList);
|
|
sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
|
|
if( pHaving ){
|
|
sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
|
|
}
|
|
sAggInfo.nAccumulator = sAggInfo.nColumn;
|
|
for(i=0; i<sAggInfo.nFunc; i++){
|
|
assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
|
|
sNC.ncFlags |= NC_InAggFunc;
|
|
sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
|
|
sNC.ncFlags &= ~NC_InAggFunc;
|
|
}
|
|
sAggInfo.mxReg = pParse->nMem;
|
|
if( db->mallocFailed ) goto select_end;
|
|
|
|
/* Processing for aggregates with GROUP BY is very different and
|
|
** much more complex than aggregates without a GROUP BY.
|
|
*/
|
|
if( pGroupBy ){
|
|
KeyInfo *pKeyInfo; /* Keying information for the group by clause */
|
|
int addr1; /* A-vs-B comparision jump */
|
|
int addrOutputRow; /* Start of subroutine that outputs a result row */
|
|
int regOutputRow; /* Return address register for output subroutine */
|
|
int addrSetAbort; /* Set the abort flag and return */
|
|
int addrTopOfLoop; /* Top of the input loop */
|
|
int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
|
|
int addrReset; /* Subroutine for resetting the accumulator */
|
|
int regReset; /* Return address register for reset subroutine */
|
|
|
|
/* If there is a GROUP BY clause we might need a sorting index to
|
|
** implement it. Allocate that sorting index now. If it turns out
|
|
** that we do not need it after all, the OP_SorterOpen instruction
|
|
** will be converted into a Noop.
|
|
*/
|
|
sAggInfo.sortingIdx = pParse->nTab++;
|
|
pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
|
|
addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
|
|
sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
|
|
0, (char*)pKeyInfo, P4_KEYINFO);
|
|
|
|
/* Initialize memory locations used by GROUP BY aggregate processing
|
|
*/
|
|
iUseFlag = ++pParse->nMem;
|
|
iAbortFlag = ++pParse->nMem;
|
|
regOutputRow = ++pParse->nMem;
|
|
addrOutputRow = sqlite3VdbeMakeLabel(v);
|
|
regReset = ++pParse->nMem;
|
|
addrReset = sqlite3VdbeMakeLabel(v);
|
|
iAMem = pParse->nMem + 1;
|
|
pParse->nMem += pGroupBy->nExpr;
|
|
iBMem = pParse->nMem + 1;
|
|
pParse->nMem += pGroupBy->nExpr;
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
|
|
VdbeComment((v, "clear abort flag"));
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
|
|
VdbeComment((v, "indicate accumulator empty"));
|
|
sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
|
|
|
|
/* Begin a loop that will extract all source rows in GROUP BY order.
|
|
** This might involve two separate loops with an OP_Sort in between, or
|
|
** it might be a single loop that uses an index to extract information
|
|
** in the right order to begin with.
|
|
*/
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
|
|
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
|
|
WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
|
|
);
|
|
if( pWInfo==0 ) goto select_end;
|
|
if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
|
|
/* The optimizer is able to deliver rows in group by order so
|
|
** we do not have to sort. The OP_OpenEphemeral table will be
|
|
** cancelled later because we still need to use the pKeyInfo
|
|
*/
|
|
groupBySort = 0;
|
|
}else{
|
|
/* Rows are coming out in undetermined order. We have to push
|
|
** each row into a sorting index, terminate the first loop,
|
|
** then loop over the sorting index in order to get the output
|
|
** in sorted order
|
|
*/
|
|
int regBase;
|
|
int regRecord;
|
|
int nCol;
|
|
int nGroupBy;
|
|
|
|
explainTempTable(pParse,
|
|
(sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
|
|
"DISTINCT" : "GROUP BY");
|
|
|
|
groupBySort = 1;
|
|
nGroupBy = pGroupBy->nExpr;
|
|
nCol = nGroupBy;
|
|
j = nGroupBy;
|
|
for(i=0; i<sAggInfo.nColumn; i++){
|
|
if( sAggInfo.aCol[i].iSorterColumn>=j ){
|
|
nCol++;
|
|
j++;
|
|
}
|
|
}
|
|
regBase = sqlite3GetTempRange(pParse, nCol);
|
|
sqlite3ExprCacheClear(pParse);
|
|
sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
|
|
j = nGroupBy;
|
|
for(i=0; i<sAggInfo.nColumn; i++){
|
|
struct AggInfo_col *pCol = &sAggInfo.aCol[i];
|
|
if( pCol->iSorterColumn>=j ){
|
|
int r1 = j + regBase;
|
|
sqlite3ExprCodeGetColumnToReg(pParse,
|
|
pCol->pTab, pCol->iColumn, pCol->iTable, r1);
|
|
j++;
|
|
}
|
|
}
|
|
regRecord = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
|
|
sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
|
|
sqlite3ReleaseTempReg(pParse, regRecord);
|
|
sqlite3ReleaseTempRange(pParse, regBase, nCol);
|
|
sqlite3WhereEnd(pWInfo);
|
|
sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
|
|
sortOut = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
|
|
sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
|
|
VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
|
|
sAggInfo.useSortingIdx = 1;
|
|
sqlite3ExprCacheClear(pParse);
|
|
|
|
}
|
|
|
|
/* If the index or temporary table used by the GROUP BY sort
|
|
** will naturally deliver rows in the order required by the ORDER BY
|
|
** clause, cancel the ephemeral table open coded earlier.
|
|
**
|
|
** This is an optimization - the correct answer should result regardless.
|
|
** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
|
|
** disable this optimization for testing purposes. */
|
|
if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
|
|
&& (groupBySort || sqlite3WhereIsSorted(pWInfo))
|
|
){
|
|
sSort.pOrderBy = 0;
|
|
sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
|
|
}
|
|
|
|
/* Evaluate the current GROUP BY terms and store in b0, b1, b2...
|
|
** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
|
|
** Then compare the current GROUP BY terms against the GROUP BY terms
|
|
** from the previous row currently stored in a0, a1, a2...
|
|
*/
|
|
addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3ExprCacheClear(pParse);
|
|
if( groupBySort ){
|
|
sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
|
|
sortOut, sortPTab);
|
|
}
|
|
for(j=0; j<pGroupBy->nExpr; j++){
|
|
if( groupBySort ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
|
|
}else{
|
|
sAggInfo.directMode = 1;
|
|
sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
|
|
}
|
|
}
|
|
sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
|
|
(char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
|
|
addr1 = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
|
|
|
|
/* Generate code that runs whenever the GROUP BY changes.
|
|
** Changes in the GROUP BY are detected by the previous code
|
|
** block. If there were no changes, this block is skipped.
|
|
**
|
|
** This code copies current group by terms in b0,b1,b2,...
|
|
** over to a0,a1,a2. It then calls the output subroutine
|
|
** and resets the aggregate accumulator registers in preparation
|
|
** for the next GROUP BY batch.
|
|
*/
|
|
sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
|
|
VdbeComment((v, "output one row"));
|
|
sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
|
|
VdbeComment((v, "check abort flag"));
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
|
|
VdbeComment((v, "reset accumulator"));
|
|
|
|
/* Update the aggregate accumulators based on the content of
|
|
** the current row
|
|
*/
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
updateAccumulator(pParse, &sAggInfo);
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
|
|
VdbeComment((v, "indicate data in accumulator"));
|
|
|
|
/* End of the loop
|
|
*/
|
|
if( groupBySort ){
|
|
sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
|
|
VdbeCoverage(v);
|
|
}else{
|
|
sqlite3WhereEnd(pWInfo);
|
|
sqlite3VdbeChangeToNoop(v, addrSortingIdx);
|
|
}
|
|
|
|
/* Output the final row of result
|
|
*/
|
|
sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
|
|
VdbeComment((v, "output final row"));
|
|
|
|
/* Jump over the subroutines
|
|
*/
|
|
sqlite3VdbeGoto(v, addrEnd);
|
|
|
|
/* Generate a subroutine that outputs a single row of the result
|
|
** set. This subroutine first looks at the iUseFlag. If iUseFlag
|
|
** is less than or equal to zero, the subroutine is a no-op. If
|
|
** the processing calls for the query to abort, this subroutine
|
|
** increments the iAbortFlag memory location before returning in
|
|
** order to signal the caller to abort.
|
|
*/
|
|
addrSetAbort = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
|
|
VdbeComment((v, "set abort flag"));
|
|
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
|
|
sqlite3VdbeResolveLabel(v, addrOutputRow);
|
|
addrOutputRow = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
|
|
VdbeCoverage(v);
|
|
VdbeComment((v, "Groupby result generator entry point"));
|
|
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
|
|
finalizeAggFunctions(pParse, &sAggInfo);
|
|
sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
|
|
selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
|
|
&sDistinct, pDest,
|
|
addrOutputRow+1, addrSetAbort);
|
|
sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
|
|
VdbeComment((v, "end groupby result generator"));
|
|
|
|
/* Generate a subroutine that will reset the group-by accumulator
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, addrReset);
|
|
resetAccumulator(pParse, &sAggInfo);
|
|
sqlite3VdbeAddOp1(v, OP_Return, regReset);
|
|
|
|
} /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
|
|
else {
|
|
ExprList *pDel = 0;
|
|
#ifndef SQLITE_OMIT_BTREECOUNT
|
|
Table *pTab;
|
|
if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
|
|
/* If isSimpleCount() returns a pointer to a Table structure, then
|
|
** the SQL statement is of the form:
|
|
**
|
|
** SELECT count(*) FROM <tbl>
|
|
**
|
|
** where the Table structure returned represents table <tbl>.
|
|
**
|
|
** This statement is so common that it is optimized specially. The
|
|
** OP_Count instruction is executed either on the intkey table that
|
|
** contains the data for table <tbl> or on one of its indexes. It
|
|
** is better to execute the op on an index, as indexes are almost
|
|
** always spread across less pages than their corresponding tables.
|
|
*/
|
|
const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
|
const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
|
|
Index *pIdx; /* Iterator variable */
|
|
KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
|
|
Index *pBest = 0; /* Best index found so far */
|
|
int iRoot = pTab->tnum; /* Root page of scanned b-tree */
|
|
|
|
sqlite3CodeVerifySchema(pParse, iDb);
|
|
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
|
|
|
|
/* Search for the index that has the lowest scan cost.
|
|
**
|
|
** (2011-04-15) Do not do a full scan of an unordered index.
|
|
**
|
|
** (2013-10-03) Do not count the entries in a partial index.
|
|
**
|
|
** In practice the KeyInfo structure will not be used. It is only
|
|
** passed to keep OP_OpenRead happy.
|
|
*/
|
|
if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
|
|
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
if( pIdx->bUnordered==0
|
|
&& pIdx->szIdxRow<pTab->szTabRow
|
|
&& pIdx->pPartIdxWhere==0
|
|
&& (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
|
|
){
|
|
pBest = pIdx;
|
|
}
|
|
}
|
|
if( pBest ){
|
|
iRoot = pBest->tnum;
|
|
pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
|
|
}
|
|
|
|
/* Open a read-only cursor, execute the OP_Count, close the cursor. */
|
|
sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
|
|
if( pKeyInfo ){
|
|
sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
|
|
}
|
|
sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
|
|
sqlite3VdbeAddOp1(v, OP_Close, iCsr);
|
|
explainSimpleCount(pParse, pTab, pBest);
|
|
}else
|
|
#endif /* SQLITE_OMIT_BTREECOUNT */
|
|
{
|
|
/* Check if the query is of one of the following forms:
|
|
**
|
|
** SELECT min(x) FROM ...
|
|
** SELECT max(x) FROM ...
|
|
**
|
|
** If it is, then ask the code in where.c to attempt to sort results
|
|
** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
|
|
** If where.c is able to produce results sorted in this order, then
|
|
** add vdbe code to break out of the processing loop after the
|
|
** first iteration (since the first iteration of the loop is
|
|
** guaranteed to operate on the row with the minimum or maximum
|
|
** value of x, the only row required).
|
|
**
|
|
** A special flag must be passed to sqlite3WhereBegin() to slightly
|
|
** modify behavior as follows:
|
|
**
|
|
** + If the query is a "SELECT min(x)", then the loop coded by
|
|
** where.c should not iterate over any values with a NULL value
|
|
** for x.
|
|
**
|
|
** + The optimizer code in where.c (the thing that decides which
|
|
** index or indices to use) should place a different priority on
|
|
** satisfying the 'ORDER BY' clause than it does in other cases.
|
|
** Refer to code and comments in where.c for details.
|
|
*/
|
|
ExprList *pMinMax = 0;
|
|
u8 flag = WHERE_ORDERBY_NORMAL;
|
|
|
|
assert( p->pGroupBy==0 );
|
|
assert( flag==0 );
|
|
if( p->pHaving==0 ){
|
|
flag = minMaxQuery(&sAggInfo, &pMinMax);
|
|
}
|
|
assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
|
|
|
|
if( flag ){
|
|
pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
|
|
pDel = pMinMax;
|
|
assert( db->mallocFailed || pMinMax!=0 );
|
|
if( !db->mallocFailed ){
|
|
pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
|
|
pMinMax->a[0].pExpr->op = TK_COLUMN;
|
|
}
|
|
}
|
|
|
|
/* This case runs if the aggregate has no GROUP BY clause. The
|
|
** processing is much simpler since there is only a single row
|
|
** of output.
|
|
*/
|
|
resetAccumulator(pParse, &sAggInfo);
|
|
pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
|
|
if( pWInfo==0 ){
|
|
sqlite3ExprListDelete(db, pDel);
|
|
goto select_end;
|
|
}
|
|
updateAccumulator(pParse, &sAggInfo);
|
|
assert( pMinMax==0 || pMinMax->nExpr==1 );
|
|
if( sqlite3WhereIsOrdered(pWInfo)>0 ){
|
|
sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
|
|
VdbeComment((v, "%s() by index",
|
|
(flag==WHERE_ORDERBY_MIN?"min":"max")));
|
|
}
|
|
sqlite3WhereEnd(pWInfo);
|
|
finalizeAggFunctions(pParse, &sAggInfo);
|
|
}
|
|
|
|
sSort.pOrderBy = 0;
|
|
sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
|
|
selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
|
|
pDest, addrEnd, addrEnd);
|
|
sqlite3ExprListDelete(db, pDel);
|
|
}
|
|
sqlite3VdbeResolveLabel(v, addrEnd);
|
|
|
|
} /* endif aggregate query */
|
|
|
|
if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
|
|
explainTempTable(pParse, "DISTINCT");
|
|
}
|
|
|
|
/* If there is an ORDER BY clause, then we need to sort the results
|
|
** and send them to the callback one by one.
|
|
*/
|
|
if( sSort.pOrderBy ){
|
|
explainTempTable(pParse,
|
|
sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
|
|
generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
|
|
}
|
|
|
|
/* Jump here to skip this query
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, iEnd);
|
|
|
|
/* The SELECT has been coded. If there is an error in the Parse structure,
|
|
** set the return code to 1. Otherwise 0. */
|
|
rc = (pParse->nErr>0);
|
|
|
|
/* Control jumps to here if an error is encountered above, or upon
|
|
** successful coding of the SELECT.
|
|
*/
|
|
select_end:
|
|
explainSetInteger(pParse->iSelectId, iRestoreSelectId);
|
|
|
|
/* Identify column names if results of the SELECT are to be output.
|
|
*/
|
|
if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
|
|
generateColumnNames(pParse, pTabList, pEList);
|
|
}
|
|
|
|
sqlite3DbFree(db, sAggInfo.aCol);
|
|
sqlite3DbFree(db, sAggInfo.aFunc);
|
|
#if SELECTTRACE_ENABLED
|
|
SELECTTRACE(1,pParse,p,("end processing\n"));
|
|
pParse->nSelectIndent--;
|
|
#endif
|
|
return rc;
|
|
}
|