
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
2175 lines
81 KiB
C
2175 lines
81 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 INSERT statements in SQLite.
|
|
*/
|
|
#include "sqliteInt.h"
|
|
|
|
/*
|
|
** Generate code that will
|
|
**
|
|
** (1) acquire a lock for table pTab then
|
|
** (2) open pTab as cursor iCur.
|
|
**
|
|
** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
|
|
** for that table that is actually opened.
|
|
*/
|
|
void sqlite3OpenTable(
|
|
Parse *pParse, /* Generate code into this VDBE */
|
|
int iCur, /* The cursor number of the table */
|
|
int iDb, /* The database index in sqlite3.aDb[] */
|
|
Table *pTab, /* The table to be opened */
|
|
int opcode /* OP_OpenRead or OP_OpenWrite */
|
|
){
|
|
Vdbe *v;
|
|
assert( !IsVirtual(pTab) );
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
|
|
sqlite3TableLock(pParse, iDb, pTab->tnum,
|
|
(opcode==OP_OpenWrite)?1:0, pTab->zName);
|
|
if( HasRowid(pTab) ){
|
|
sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
|
|
VdbeComment((v, "%s", pTab->zName));
|
|
}else{
|
|
Index *pPk = sqlite3PrimaryKeyIndex(pTab);
|
|
assert( pPk!=0 );
|
|
assert( pPk->tnum==pTab->tnum );
|
|
sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
|
|
sqlite3VdbeSetP4KeyInfo(pParse, pPk);
|
|
VdbeComment((v, "%s", pTab->zName));
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Return a pointer to the column affinity string associated with index
|
|
** pIdx. A column affinity string has one character for each column in
|
|
** the table, according to the affinity of the column:
|
|
**
|
|
** Character Column affinity
|
|
** ------------------------------
|
|
** 'A' BLOB
|
|
** 'B' TEXT
|
|
** 'C' NUMERIC
|
|
** 'D' INTEGER
|
|
** 'F' REAL
|
|
**
|
|
** An extra 'D' is appended to the end of the string to cover the
|
|
** rowid that appears as the last column in every index.
|
|
**
|
|
** Memory for the buffer containing the column index affinity string
|
|
** is managed along with the rest of the Index structure. It will be
|
|
** released when sqlite3DeleteIndex() is called.
|
|
*/
|
|
const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
|
|
if( !pIdx->zColAff ){
|
|
/* The first time a column affinity string for a particular index is
|
|
** required, it is allocated and populated here. It is then stored as
|
|
** a member of the Index structure for subsequent use.
|
|
**
|
|
** The column affinity string will eventually be deleted by
|
|
** sqliteDeleteIndex() when the Index structure itself is cleaned
|
|
** up.
|
|
*/
|
|
int n;
|
|
Table *pTab = pIdx->pTable;
|
|
pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
|
|
if( !pIdx->zColAff ){
|
|
sqlite3OomFault(db);
|
|
return 0;
|
|
}
|
|
for(n=0; n<pIdx->nColumn; n++){
|
|
i16 x = pIdx->aiColumn[n];
|
|
if( x>=0 ){
|
|
pIdx->zColAff[n] = pTab->aCol[x].affinity;
|
|
}else if( x==XN_ROWID ){
|
|
pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
|
|
}else{
|
|
char aff;
|
|
assert( x==XN_EXPR );
|
|
assert( pIdx->aColExpr!=0 );
|
|
aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
|
|
if( aff==0 ) aff = SQLITE_AFF_BLOB;
|
|
pIdx->zColAff[n] = aff;
|
|
}
|
|
}
|
|
pIdx->zColAff[n] = 0;
|
|
}
|
|
|
|
return pIdx->zColAff;
|
|
}
|
|
|
|
/*
|
|
** Compute the affinity string for table pTab, if it has not already been
|
|
** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
|
|
**
|
|
** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
|
|
** if iReg>0 then code an OP_Affinity opcode that will set the affinities
|
|
** for register iReg and following. Or if affinities exists and iReg==0,
|
|
** then just set the P4 operand of the previous opcode (which should be
|
|
** an OP_MakeRecord) to the affinity string.
|
|
**
|
|
** A column affinity string has one character per column:
|
|
**
|
|
** Character Column affinity
|
|
** ------------------------------
|
|
** 'A' BLOB
|
|
** 'B' TEXT
|
|
** 'C' NUMERIC
|
|
** 'D' INTEGER
|
|
** 'E' REAL
|
|
*/
|
|
void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
|
|
int i;
|
|
char *zColAff = pTab->zColAff;
|
|
if( zColAff==0 ){
|
|
sqlite3 *db = sqlite3VdbeDb(v);
|
|
zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
|
|
if( !zColAff ){
|
|
sqlite3OomFault(db);
|
|
return;
|
|
}
|
|
|
|
for(i=0; i<pTab->nCol; i++){
|
|
zColAff[i] = pTab->aCol[i].affinity;
|
|
}
|
|
do{
|
|
zColAff[i--] = 0;
|
|
}while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
|
|
pTab->zColAff = zColAff;
|
|
}
|
|
i = sqlite3Strlen30(zColAff);
|
|
if( i ){
|
|
if( iReg ){
|
|
sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
|
|
}else{
|
|
sqlite3VdbeChangeP4(v, -1, zColAff, i);
|
|
}
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Return non-zero if the table pTab in database iDb or any of its indices
|
|
** have been opened at any point in the VDBE program. This is used to see if
|
|
** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
|
|
** run without using a temporary table for the results of the SELECT.
|
|
*/
|
|
static int readsTable(Parse *p, int iDb, Table *pTab){
|
|
Vdbe *v = sqlite3GetVdbe(p);
|
|
int i;
|
|
int iEnd = sqlite3VdbeCurrentAddr(v);
|
|
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
|
VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
|
|
#endif
|
|
|
|
for(i=1; i<iEnd; i++){
|
|
VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
|
|
assert( pOp!=0 );
|
|
if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
|
|
Index *pIndex;
|
|
int tnum = pOp->p2;
|
|
if( tnum==pTab->tnum ){
|
|
return 1;
|
|
}
|
|
for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
|
|
if( tnum==pIndex->tnum ){
|
|
return 1;
|
|
}
|
|
}
|
|
}
|
|
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
|
if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
|
|
assert( pOp->p4.pVtab!=0 );
|
|
assert( pOp->p4type==P4_VTAB );
|
|
return 1;
|
|
}
|
|
#endif
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
#ifndef SQLITE_OMIT_AUTOINCREMENT
|
|
/*
|
|
** Locate or create an AutoincInfo structure associated with table pTab
|
|
** which is in database iDb. Return the register number for the register
|
|
** that holds the maximum rowid.
|
|
**
|
|
** There is at most one AutoincInfo structure per table even if the
|
|
** same table is autoincremented multiple times due to inserts within
|
|
** triggers. A new AutoincInfo structure is created if this is the
|
|
** first use of table pTab. On 2nd and subsequent uses, the original
|
|
** AutoincInfo structure is used.
|
|
**
|
|
** Three memory locations are allocated:
|
|
**
|
|
** (1) Register to hold the name of the pTab table.
|
|
** (2) Register to hold the maximum ROWID of pTab.
|
|
** (3) Register to hold the rowid in sqlite_sequence of pTab
|
|
**
|
|
** The 2nd register is the one that is returned. That is all the
|
|
** insert routine needs to know about.
|
|
*/
|
|
static int autoIncBegin(
|
|
Parse *pParse, /* Parsing context */
|
|
int iDb, /* Index of the database holding pTab */
|
|
Table *pTab /* The table we are writing to */
|
|
){
|
|
int memId = 0; /* Register holding maximum rowid */
|
|
if( pTab->tabFlags & TF_Autoincrement ){
|
|
Parse *pToplevel = sqlite3ParseToplevel(pParse);
|
|
AutoincInfo *pInfo;
|
|
|
|
pInfo = pToplevel->pAinc;
|
|
while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
|
|
if( pInfo==0 ){
|
|
pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
|
|
if( pInfo==0 ) return 0;
|
|
pInfo->pNext = pToplevel->pAinc;
|
|
pToplevel->pAinc = pInfo;
|
|
pInfo->pTab = pTab;
|
|
pInfo->iDb = iDb;
|
|
pToplevel->nMem++; /* Register to hold name of table */
|
|
pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
|
|
pToplevel->nMem++; /* Rowid in sqlite_sequence */
|
|
}
|
|
memId = pInfo->regCtr;
|
|
}
|
|
return memId;
|
|
}
|
|
|
|
/*
|
|
** This routine generates code that will initialize all of the
|
|
** register used by the autoincrement tracker.
|
|
*/
|
|
void sqlite3AutoincrementBegin(Parse *pParse){
|
|
AutoincInfo *p; /* Information about an AUTOINCREMENT */
|
|
sqlite3 *db = pParse->db; /* The database connection */
|
|
Db *pDb; /* Database only autoinc table */
|
|
int memId; /* Register holding max rowid */
|
|
Vdbe *v = pParse->pVdbe; /* VDBE under construction */
|
|
|
|
/* This routine is never called during trigger-generation. It is
|
|
** only called from the top-level */
|
|
assert( pParse->pTriggerTab==0 );
|
|
assert( sqlite3IsToplevel(pParse) );
|
|
|
|
assert( v ); /* We failed long ago if this is not so */
|
|
for(p = pParse->pAinc; p; p = p->pNext){
|
|
static const int iLn = VDBE_OFFSET_LINENO(2);
|
|
static const VdbeOpList autoInc[] = {
|
|
/* 0 */ {OP_Null, 0, 0, 0},
|
|
/* 1 */ {OP_Rewind, 0, 9, 0},
|
|
/* 2 */ {OP_Column, 0, 0, 0},
|
|
/* 3 */ {OP_Ne, 0, 7, 0},
|
|
/* 4 */ {OP_Rowid, 0, 0, 0},
|
|
/* 5 */ {OP_Column, 0, 1, 0},
|
|
/* 6 */ {OP_Goto, 0, 9, 0},
|
|
/* 7 */ {OP_Next, 0, 2, 0},
|
|
/* 8 */ {OP_Integer, 0, 0, 0},
|
|
/* 9 */ {OP_Close, 0, 0, 0}
|
|
};
|
|
VdbeOp *aOp;
|
|
pDb = &db->aDb[p->iDb];
|
|
memId = p->regCtr;
|
|
assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
|
|
sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
|
|
sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
|
|
aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
|
|
if( aOp==0 ) break;
|
|
aOp[0].p2 = memId;
|
|
aOp[0].p3 = memId+1;
|
|
aOp[2].p3 = memId;
|
|
aOp[3].p1 = memId-1;
|
|
aOp[3].p3 = memId;
|
|
aOp[3].p5 = SQLITE_JUMPIFNULL;
|
|
aOp[4].p2 = memId+1;
|
|
aOp[5].p3 = memId;
|
|
aOp[8].p2 = memId;
|
|
}
|
|
}
|
|
|
|
/*
|
|
** Update the maximum rowid for an autoincrement calculation.
|
|
**
|
|
** This routine should be called when the regRowid register holds a
|
|
** new rowid that is about to be inserted. If that new rowid is
|
|
** larger than the maximum rowid in the memId memory cell, then the
|
|
** memory cell is updated.
|
|
*/
|
|
static void autoIncStep(Parse *pParse, int memId, int regRowid){
|
|
if( memId>0 ){
|
|
sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
|
|
}
|
|
}
|
|
|
|
/*
|
|
** This routine generates the code needed to write autoincrement
|
|
** maximum rowid values back into the sqlite_sequence register.
|
|
** Every statement that might do an INSERT into an autoincrement
|
|
** table (either directly or through triggers) needs to call this
|
|
** routine just before the "exit" code.
|
|
*/
|
|
static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
|
|
AutoincInfo *p;
|
|
Vdbe *v = pParse->pVdbe;
|
|
sqlite3 *db = pParse->db;
|
|
|
|
assert( v );
|
|
for(p = pParse->pAinc; p; p = p->pNext){
|
|
static const int iLn = VDBE_OFFSET_LINENO(2);
|
|
static const VdbeOpList autoIncEnd[] = {
|
|
/* 0 */ {OP_NotNull, 0, 2, 0},
|
|
/* 1 */ {OP_NewRowid, 0, 0, 0},
|
|
/* 2 */ {OP_MakeRecord, 0, 2, 0},
|
|
/* 3 */ {OP_Insert, 0, 0, 0},
|
|
/* 4 */ {OP_Close, 0, 0, 0}
|
|
};
|
|
VdbeOp *aOp;
|
|
Db *pDb = &db->aDb[p->iDb];
|
|
int iRec;
|
|
int memId = p->regCtr;
|
|
|
|
iRec = sqlite3GetTempReg(pParse);
|
|
assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
|
|
sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
|
|
aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
|
|
if( aOp==0 ) break;
|
|
aOp[0].p1 = memId+1;
|
|
aOp[1].p2 = memId+1;
|
|
aOp[2].p1 = memId-1;
|
|
aOp[2].p3 = iRec;
|
|
aOp[3].p2 = iRec;
|
|
aOp[3].p3 = memId+1;
|
|
aOp[3].p5 = OPFLAG_APPEND;
|
|
sqlite3ReleaseTempReg(pParse, iRec);
|
|
}
|
|
}
|
|
void sqlite3AutoincrementEnd(Parse *pParse){
|
|
if( pParse->pAinc ) autoIncrementEnd(pParse);
|
|
}
|
|
#else
|
|
/*
|
|
** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
|
|
** above are all no-ops
|
|
*/
|
|
# define autoIncBegin(A,B,C) (0)
|
|
# define autoIncStep(A,B,C)
|
|
#endif /* SQLITE_OMIT_AUTOINCREMENT */
|
|
|
|
|
|
/* Forward declaration */
|
|
static int xferOptimization(
|
|
Parse *pParse, /* Parser context */
|
|
Table *pDest, /* The table we are inserting into */
|
|
Select *pSelect, /* A SELECT statement to use as the data source */
|
|
int onError, /* How to handle constraint errors */
|
|
int iDbDest /* The database of pDest */
|
|
);
|
|
|
|
/*
|
|
** This routine is called to handle SQL of the following forms:
|
|
**
|
|
** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
|
|
** insert into TABLE (IDLIST) select
|
|
** insert into TABLE (IDLIST) default values
|
|
**
|
|
** The IDLIST following the table name is always optional. If omitted,
|
|
** then a list of all (non-hidden) columns for the table is substituted.
|
|
** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
|
|
** is omitted.
|
|
**
|
|
** For the pSelect parameter holds the values to be inserted for the
|
|
** first two forms shown above. A VALUES clause is really just short-hand
|
|
** for a SELECT statement that omits the FROM clause and everything else
|
|
** that follows. If the pSelect parameter is NULL, that means that the
|
|
** DEFAULT VALUES form of the INSERT statement is intended.
|
|
**
|
|
** The code generated follows one of four templates. For a simple
|
|
** insert with data coming from a single-row VALUES clause, the code executes
|
|
** once straight down through. Pseudo-code follows (we call this
|
|
** the "1st template"):
|
|
**
|
|
** open write cursor to <table> and its indices
|
|
** put VALUES clause expressions into registers
|
|
** write the resulting record into <table>
|
|
** cleanup
|
|
**
|
|
** The three remaining templates assume the statement is of the form
|
|
**
|
|
** INSERT INTO <table> SELECT ...
|
|
**
|
|
** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
|
|
** in other words if the SELECT pulls all columns from a single table
|
|
** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
|
|
** if <table2> and <table1> are distinct tables but have identical
|
|
** schemas, including all the same indices, then a special optimization
|
|
** is invoked that copies raw records from <table2> over to <table1>.
|
|
** See the xferOptimization() function for the implementation of this
|
|
** template. This is the 2nd template.
|
|
**
|
|
** open a write cursor to <table>
|
|
** open read cursor on <table2>
|
|
** transfer all records in <table2> over to <table>
|
|
** close cursors
|
|
** foreach index on <table>
|
|
** open a write cursor on the <table> index
|
|
** open a read cursor on the corresponding <table2> index
|
|
** transfer all records from the read to the write cursors
|
|
** close cursors
|
|
** end foreach
|
|
**
|
|
** The 3rd template is for when the second template does not apply
|
|
** and the SELECT clause does not read from <table> at any time.
|
|
** The generated code follows this template:
|
|
**
|
|
** X <- A
|
|
** goto B
|
|
** A: setup for the SELECT
|
|
** loop over the rows in the SELECT
|
|
** load values into registers R..R+n
|
|
** yield X
|
|
** end loop
|
|
** cleanup after the SELECT
|
|
** end-coroutine X
|
|
** B: open write cursor to <table> and its indices
|
|
** C: yield X, at EOF goto D
|
|
** insert the select result into <table> from R..R+n
|
|
** goto C
|
|
** D: cleanup
|
|
**
|
|
** The 4th template is used if the insert statement takes its
|
|
** values from a SELECT but the data is being inserted into a table
|
|
** that is also read as part of the SELECT. In the third form,
|
|
** we have to use an intermediate table to store the results of
|
|
** the select. The template is like this:
|
|
**
|
|
** X <- A
|
|
** goto B
|
|
** A: setup for the SELECT
|
|
** loop over the tables in the SELECT
|
|
** load value into register R..R+n
|
|
** yield X
|
|
** end loop
|
|
** cleanup after the SELECT
|
|
** end co-routine R
|
|
** B: open temp table
|
|
** L: yield X, at EOF goto M
|
|
** insert row from R..R+n into temp table
|
|
** goto L
|
|
** M: open write cursor to <table> and its indices
|
|
** rewind temp table
|
|
** C: loop over rows of intermediate table
|
|
** transfer values form intermediate table into <table>
|
|
** end loop
|
|
** D: cleanup
|
|
*/
|
|
void sqlite3Insert(
|
|
Parse *pParse, /* Parser context */
|
|
SrcList *pTabList, /* Name of table into which we are inserting */
|
|
Select *pSelect, /* A SELECT statement to use as the data source */
|
|
IdList *pColumn, /* Column names corresponding to IDLIST. */
|
|
int onError /* How to handle constraint errors */
|
|
){
|
|
sqlite3 *db; /* The main database structure */
|
|
Table *pTab; /* The table to insert into. aka TABLE */
|
|
char *zTab; /* Name of the table into which we are inserting */
|
|
const char *zDb; /* Name of the database holding this table */
|
|
int i, j, idx; /* Loop counters */
|
|
Vdbe *v; /* Generate code into this virtual machine */
|
|
Index *pIdx; /* For looping over indices of the table */
|
|
int nColumn; /* Number of columns in the data */
|
|
int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
|
|
int iDataCur = 0; /* VDBE cursor that is the main data repository */
|
|
int iIdxCur = 0; /* First index cursor */
|
|
int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
|
|
int endOfLoop; /* Label for the end of the insertion loop */
|
|
int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
|
|
int addrInsTop = 0; /* Jump to label "D" */
|
|
int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
|
|
SelectDest dest; /* Destination for SELECT on rhs of INSERT */
|
|
int iDb; /* Index of database holding TABLE */
|
|
Db *pDb; /* The database containing table being inserted into */
|
|
u8 useTempTable = 0; /* Store SELECT results in intermediate table */
|
|
u8 appendFlag = 0; /* True if the insert is likely to be an append */
|
|
u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
|
|
u8 bIdListInOrder; /* True if IDLIST is in table order */
|
|
ExprList *pList = 0; /* List of VALUES() to be inserted */
|
|
|
|
/* Register allocations */
|
|
int regFromSelect = 0;/* Base register for data coming from SELECT */
|
|
int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
|
|
int regRowCount = 0; /* Memory cell used for the row counter */
|
|
int regIns; /* Block of regs holding rowid+data being inserted */
|
|
int regRowid; /* registers holding insert rowid */
|
|
int regData; /* register holding first column to insert */
|
|
int *aRegIdx = 0; /* One register allocated to each index */
|
|
|
|
#ifndef SQLITE_OMIT_TRIGGER
|
|
int isView; /* True if attempting to insert into a view */
|
|
Trigger *pTrigger; /* List of triggers on pTab, if required */
|
|
int tmask; /* Mask of trigger times */
|
|
#endif
|
|
|
|
db = pParse->db;
|
|
memset(&dest, 0, sizeof(dest));
|
|
if( pParse->nErr || db->mallocFailed ){
|
|
goto insert_cleanup;
|
|
}
|
|
|
|
/* If the Select object is really just a simple VALUES() list with a
|
|
** single row (the common case) then keep that one row of values
|
|
** and discard the other (unused) parts of the pSelect object
|
|
*/
|
|
if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
|
|
pList = pSelect->pEList;
|
|
pSelect->pEList = 0;
|
|
sqlite3SelectDelete(db, pSelect);
|
|
pSelect = 0;
|
|
}
|
|
|
|
/* Locate the table into which we will be inserting new information.
|
|
*/
|
|
assert( pTabList->nSrc==1 );
|
|
zTab = pTabList->a[0].zName;
|
|
if( NEVER(zTab==0) ) goto insert_cleanup;
|
|
pTab = sqlite3SrcListLookup(pParse, pTabList);
|
|
if( pTab==0 ){
|
|
goto insert_cleanup;
|
|
}
|
|
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
|
assert( iDb<db->nDb );
|
|
pDb = &db->aDb[iDb];
|
|
zDb = pDb->zName;
|
|
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
|
|
goto insert_cleanup;
|
|
}
|
|
withoutRowid = !HasRowid(pTab);
|
|
|
|
/* Figure out if we have any triggers and if the table being
|
|
** inserted into is a view
|
|
*/
|
|
#ifndef SQLITE_OMIT_TRIGGER
|
|
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
|
|
isView = pTab->pSelect!=0;
|
|
#else
|
|
# define pTrigger 0
|
|
# define tmask 0
|
|
# define isView 0
|
|
#endif
|
|
#ifdef SQLITE_OMIT_VIEW
|
|
# undef isView
|
|
# define isView 0
|
|
#endif
|
|
assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
|
|
|
|
/* If pTab is really a view, make sure it has been initialized.
|
|
** ViewGetColumnNames() is a no-op if pTab is not a view.
|
|
*/
|
|
if( sqlite3ViewGetColumnNames(pParse, pTab) ){
|
|
goto insert_cleanup;
|
|
}
|
|
|
|
/* Cannot insert into a read-only table.
|
|
*/
|
|
if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
|
|
goto insert_cleanup;
|
|
}
|
|
|
|
/* Allocate a VDBE
|
|
*/
|
|
v = sqlite3GetVdbe(pParse);
|
|
if( v==0 ) goto insert_cleanup;
|
|
if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
|
|
sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
|
|
|
|
#ifndef SQLITE_OMIT_XFER_OPT
|
|
/* If the statement is of the form
|
|
**
|
|
** INSERT INTO <table1> SELECT * FROM <table2>;
|
|
**
|
|
** Then special optimizations can be applied that make the transfer
|
|
** very fast and which reduce fragmentation of indices.
|
|
**
|
|
** This is the 2nd template.
|
|
*/
|
|
if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
|
|
assert( !pTrigger );
|
|
assert( pList==0 );
|
|
goto insert_end;
|
|
}
|
|
#endif /* SQLITE_OMIT_XFER_OPT */
|
|
|
|
/* If this is an AUTOINCREMENT table, look up the sequence number in the
|
|
** sqlite_sequence table and store it in memory cell regAutoinc.
|
|
*/
|
|
regAutoinc = autoIncBegin(pParse, iDb, pTab);
|
|
|
|
/* Allocate registers for holding the rowid of the new row,
|
|
** the content of the new row, and the assembled row record.
|
|
*/
|
|
regRowid = regIns = pParse->nMem+1;
|
|
pParse->nMem += pTab->nCol + 1;
|
|
if( IsVirtual(pTab) ){
|
|
regRowid++;
|
|
pParse->nMem++;
|
|
}
|
|
regData = regRowid+1;
|
|
|
|
/* If the INSERT statement included an IDLIST term, then make sure
|
|
** all elements of the IDLIST really are columns of the table and
|
|
** remember the column indices.
|
|
**
|
|
** If the table has an INTEGER PRIMARY KEY column and that column
|
|
** is named in the IDLIST, then record in the ipkColumn variable
|
|
** the index into IDLIST of the primary key column. ipkColumn is
|
|
** the index of the primary key as it appears in IDLIST, not as
|
|
** is appears in the original table. (The index of the INTEGER
|
|
** PRIMARY KEY in the original table is pTab->iPKey.)
|
|
*/
|
|
bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
|
|
if( pColumn ){
|
|
for(i=0; i<pColumn->nId; i++){
|
|
pColumn->a[i].idx = -1;
|
|
}
|
|
for(i=0; i<pColumn->nId; i++){
|
|
for(j=0; j<pTab->nCol; j++){
|
|
if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
|
|
pColumn->a[i].idx = j;
|
|
if( i!=j ) bIdListInOrder = 0;
|
|
if( j==pTab->iPKey ){
|
|
ipkColumn = i; assert( !withoutRowid );
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
if( j>=pTab->nCol ){
|
|
if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
|
|
ipkColumn = i;
|
|
bIdListInOrder = 0;
|
|
}else{
|
|
sqlite3ErrorMsg(pParse, "table %S has no column named %s",
|
|
pTabList, 0, pColumn->a[i].zName);
|
|
pParse->checkSchema = 1;
|
|
goto insert_cleanup;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Figure out how many columns of data are supplied. If the data
|
|
** is coming from a SELECT statement, then generate a co-routine that
|
|
** produces a single row of the SELECT on each invocation. The
|
|
** co-routine is the common header to the 3rd and 4th templates.
|
|
*/
|
|
if( pSelect ){
|
|
/* Data is coming from a SELECT or from a multi-row VALUES clause.
|
|
** Generate a co-routine to run the SELECT. */
|
|
int regYield; /* Register holding co-routine entry-point */
|
|
int addrTop; /* Top of the co-routine */
|
|
int rc; /* Result code */
|
|
|
|
regYield = ++pParse->nMem;
|
|
addrTop = sqlite3VdbeCurrentAddr(v) + 1;
|
|
sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
|
|
sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
|
|
dest.iSdst = bIdListInOrder ? regData : 0;
|
|
dest.nSdst = pTab->nCol;
|
|
rc = sqlite3Select(pParse, pSelect, &dest);
|
|
regFromSelect = dest.iSdst;
|
|
if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
|
|
sqlite3VdbeEndCoroutine(v, regYield);
|
|
sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
|
|
assert( pSelect->pEList );
|
|
nColumn = pSelect->pEList->nExpr;
|
|
|
|
/* Set useTempTable to TRUE if the result of the SELECT statement
|
|
** should be written into a temporary table (template 4). Set to
|
|
** FALSE if each output row of the SELECT can be written directly into
|
|
** the destination table (template 3).
|
|
**
|
|
** A temp table must be used if the table being updated is also one
|
|
** of the tables being read by the SELECT statement. Also use a
|
|
** temp table in the case of row triggers.
|
|
*/
|
|
if( pTrigger || readsTable(pParse, iDb, pTab) ){
|
|
useTempTable = 1;
|
|
}
|
|
|
|
if( useTempTable ){
|
|
/* Invoke the coroutine to extract information from the SELECT
|
|
** and add it to a transient table srcTab. The code generated
|
|
** here is from the 4th template:
|
|
**
|
|
** B: open temp table
|
|
** L: yield X, goto M at EOF
|
|
** insert row from R..R+n into temp table
|
|
** goto L
|
|
** M: ...
|
|
*/
|
|
int regRec; /* Register to hold packed record */
|
|
int regTempRowid; /* Register to hold temp table ROWID */
|
|
int addrL; /* Label "L" */
|
|
|
|
srcTab = pParse->nTab++;
|
|
regRec = sqlite3GetTempReg(pParse);
|
|
regTempRowid = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
|
|
addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
|
|
sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
|
|
sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
|
|
sqlite3VdbeGoto(v, addrL);
|
|
sqlite3VdbeJumpHere(v, addrL);
|
|
sqlite3ReleaseTempReg(pParse, regRec);
|
|
sqlite3ReleaseTempReg(pParse, regTempRowid);
|
|
}
|
|
}else{
|
|
/* This is the case if the data for the INSERT is coming from a
|
|
** single-row VALUES clause
|
|
*/
|
|
NameContext sNC;
|
|
memset(&sNC, 0, sizeof(sNC));
|
|
sNC.pParse = pParse;
|
|
srcTab = -1;
|
|
assert( useTempTable==0 );
|
|
if( pList ){
|
|
nColumn = pList->nExpr;
|
|
if( sqlite3ResolveExprListNames(&sNC, pList) ){
|
|
goto insert_cleanup;
|
|
}
|
|
}else{
|
|
nColumn = 0;
|
|
}
|
|
}
|
|
|
|
/* If there is no IDLIST term but the table has an integer primary
|
|
** key, the set the ipkColumn variable to the integer primary key
|
|
** column index in the original table definition.
|
|
*/
|
|
if( pColumn==0 && nColumn>0 ){
|
|
ipkColumn = pTab->iPKey;
|
|
}
|
|
|
|
/* Make sure the number of columns in the source data matches the number
|
|
** of columns to be inserted into the table.
|
|
*/
|
|
for(i=0; i<pTab->nCol; i++){
|
|
nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
|
|
}
|
|
if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
|
|
sqlite3ErrorMsg(pParse,
|
|
"table %S has %d columns but %d values were supplied",
|
|
pTabList, 0, pTab->nCol-nHidden, nColumn);
|
|
goto insert_cleanup;
|
|
}
|
|
if( pColumn!=0 && nColumn!=pColumn->nId ){
|
|
sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
|
|
goto insert_cleanup;
|
|
}
|
|
|
|
/* Initialize the count of rows to be inserted
|
|
*/
|
|
if( db->flags & SQLITE_CountRows ){
|
|
regRowCount = ++pParse->nMem;
|
|
sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
|
|
}
|
|
|
|
/* If this is not a view, open the table and and all indices */
|
|
if( !isView ){
|
|
int nIdx;
|
|
nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
|
|
&iDataCur, &iIdxCur);
|
|
aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
|
|
if( aRegIdx==0 ){
|
|
goto insert_cleanup;
|
|
}
|
|
for(i=0; i<nIdx; i++){
|
|
aRegIdx[i] = ++pParse->nMem;
|
|
}
|
|
}
|
|
|
|
/* This is the top of the main insertion loop */
|
|
if( useTempTable ){
|
|
/* This block codes the top of loop only. The complete loop is the
|
|
** following pseudocode (template 4):
|
|
**
|
|
** rewind temp table, if empty goto D
|
|
** C: loop over rows of intermediate table
|
|
** transfer values form intermediate table into <table>
|
|
** end loop
|
|
** D: ...
|
|
*/
|
|
addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
|
|
addrCont = sqlite3VdbeCurrentAddr(v);
|
|
}else if( pSelect ){
|
|
/* This block codes the top of loop only. The complete loop is the
|
|
** following pseudocode (template 3):
|
|
**
|
|
** C: yield X, at EOF goto D
|
|
** insert the select result into <table> from R..R+n
|
|
** goto C
|
|
** D: ...
|
|
*/
|
|
addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
|
|
VdbeCoverage(v);
|
|
}
|
|
|
|
/* Run the BEFORE and INSTEAD OF triggers, if there are any
|
|
*/
|
|
endOfLoop = sqlite3VdbeMakeLabel(v);
|
|
if( tmask & TRIGGER_BEFORE ){
|
|
int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
|
|
|
|
/* build the NEW.* reference row. Note that if there is an INTEGER
|
|
** PRIMARY KEY into which a NULL is being inserted, that NULL will be
|
|
** translated into a unique ID for the row. But on a BEFORE trigger,
|
|
** we do not know what the unique ID will be (because the insert has
|
|
** not happened yet) so we substitute a rowid of -1
|
|
*/
|
|
if( ipkColumn<0 ){
|
|
sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
|
|
}else{
|
|
int addr1;
|
|
assert( !withoutRowid );
|
|
if( useTempTable ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
|
|
}else{
|
|
assert( pSelect==0 ); /* Otherwise useTempTable is true */
|
|
sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
|
|
}
|
|
addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
|
|
}
|
|
|
|
/* Cannot have triggers on a virtual table. If it were possible,
|
|
** this block would have to account for hidden column.
|
|
*/
|
|
assert( !IsVirtual(pTab) );
|
|
|
|
/* Create the new column data
|
|
*/
|
|
for(i=j=0; i<pTab->nCol; i++){
|
|
if( pColumn ){
|
|
for(j=0; j<pColumn->nId; j++){
|
|
if( pColumn->a[j].idx==i ) break;
|
|
}
|
|
}
|
|
if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
|
|
|| (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
|
|
sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
|
|
}else if( useTempTable ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
|
|
}else{
|
|
assert( pSelect==0 ); /* Otherwise useTempTable is true */
|
|
sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
|
|
}
|
|
if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
|
|
}
|
|
|
|
/* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
|
|
** do not attempt any conversions before assembling the record.
|
|
** If this is a real table, attempt conversions as required by the
|
|
** table column affinities.
|
|
*/
|
|
if( !isView ){
|
|
sqlite3TableAffinity(v, pTab, regCols+1);
|
|
}
|
|
|
|
/* Fire BEFORE or INSTEAD OF triggers */
|
|
sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
|
|
pTab, regCols-pTab->nCol-1, onError, endOfLoop);
|
|
|
|
sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
|
|
}
|
|
|
|
/* Compute the content of the next row to insert into a range of
|
|
** registers beginning at regIns.
|
|
*/
|
|
if( !isView ){
|
|
if( IsVirtual(pTab) ){
|
|
/* The row that the VUpdate opcode will delete: none */
|
|
sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
|
|
}
|
|
if( ipkColumn>=0 ){
|
|
if( useTempTable ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
|
|
}else if( pSelect ){
|
|
sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
|
|
}else{
|
|
VdbeOp *pOp;
|
|
sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
|
|
pOp = sqlite3VdbeGetOp(v, -1);
|
|
if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
|
|
appendFlag = 1;
|
|
pOp->opcode = OP_NewRowid;
|
|
pOp->p1 = iDataCur;
|
|
pOp->p2 = regRowid;
|
|
pOp->p3 = regAutoinc;
|
|
}
|
|
}
|
|
/* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
|
|
** to generate a unique primary key value.
|
|
*/
|
|
if( !appendFlag ){
|
|
int addr1;
|
|
if( !IsVirtual(pTab) ){
|
|
addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
}else{
|
|
addr1 = sqlite3VdbeCurrentAddr(v);
|
|
sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
|
|
}
|
|
}else if( IsVirtual(pTab) || withoutRowid ){
|
|
sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
|
|
}else{
|
|
sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
|
|
appendFlag = 1;
|
|
}
|
|
autoIncStep(pParse, regAutoinc, regRowid);
|
|
|
|
/* Compute data for all columns of the new entry, beginning
|
|
** with the first column.
|
|
*/
|
|
nHidden = 0;
|
|
for(i=0; i<pTab->nCol; i++){
|
|
int iRegStore = regRowid+1+i;
|
|
if( i==pTab->iPKey ){
|
|
/* The value of the INTEGER PRIMARY KEY column is always a NULL.
|
|
** Whenever this column is read, the rowid will be substituted
|
|
** in its place. Hence, fill this column with a NULL to avoid
|
|
** taking up data space with information that will never be used.
|
|
** As there may be shallow copies of this value, make it a soft-NULL */
|
|
sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
|
|
continue;
|
|
}
|
|
if( pColumn==0 ){
|
|
if( IsHiddenColumn(&pTab->aCol[i]) ){
|
|
j = -1;
|
|
nHidden++;
|
|
}else{
|
|
j = i - nHidden;
|
|
}
|
|
}else{
|
|
for(j=0; j<pColumn->nId; j++){
|
|
if( pColumn->a[j].idx==i ) break;
|
|
}
|
|
}
|
|
if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
|
|
sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
|
|
}else if( useTempTable ){
|
|
sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
|
|
}else if( pSelect ){
|
|
if( regFromSelect!=regData ){
|
|
sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
|
|
}
|
|
}else{
|
|
sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
|
|
}
|
|
}
|
|
|
|
/* Generate code to check constraints and generate index keys and
|
|
** do the insertion.
|
|
*/
|
|
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
|
if( IsVirtual(pTab) ){
|
|
const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
|
|
sqlite3VtabMakeWritable(pParse, pTab);
|
|
sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
|
|
sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
|
|
sqlite3MayAbort(pParse);
|
|
}else
|
|
#endif
|
|
{
|
|
int isReplace; /* Set to true if constraints may cause a replace */
|
|
sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
|
|
regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
|
|
);
|
|
sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
|
|
sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
|
|
regIns, aRegIdx, 0, appendFlag, isReplace==0);
|
|
}
|
|
}
|
|
|
|
/* Update the count of rows that are inserted
|
|
*/
|
|
if( (db->flags & SQLITE_CountRows)!=0 ){
|
|
sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
|
|
}
|
|
|
|
if( pTrigger ){
|
|
/* Code AFTER triggers */
|
|
sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
|
|
pTab, regData-2-pTab->nCol, onError, endOfLoop);
|
|
}
|
|
|
|
/* The bottom of the main insertion loop, if the data source
|
|
** is a SELECT statement.
|
|
*/
|
|
sqlite3VdbeResolveLabel(v, endOfLoop);
|
|
if( useTempTable ){
|
|
sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
|
|
sqlite3VdbeJumpHere(v, addrInsTop);
|
|
sqlite3VdbeAddOp1(v, OP_Close, srcTab);
|
|
}else if( pSelect ){
|
|
sqlite3VdbeGoto(v, addrCont);
|
|
sqlite3VdbeJumpHere(v, addrInsTop);
|
|
}
|
|
|
|
if( !IsVirtual(pTab) && !isView ){
|
|
/* Close all tables opened */
|
|
if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
|
|
for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
|
|
sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
|
|
}
|
|
}
|
|
|
|
insert_end:
|
|
/* Update the sqlite_sequence table by storing the content of the
|
|
** maximum rowid counter values recorded while inserting into
|
|
** autoincrement tables.
|
|
*/
|
|
if( pParse->nested==0 && pParse->pTriggerTab==0 ){
|
|
sqlite3AutoincrementEnd(pParse);
|
|
}
|
|
|
|
/*
|
|
** Return the number of rows inserted. If this routine is
|
|
** generating code because of a call to sqlite3NestedParse(), do not
|
|
** invoke the callback function.
|
|
*/
|
|
if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
|
|
sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
|
|
sqlite3VdbeSetNumCols(v, 1);
|
|
sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
|
|
}
|
|
|
|
insert_cleanup:
|
|
sqlite3SrcListDelete(db, pTabList);
|
|
sqlite3ExprListDelete(db, pList);
|
|
sqlite3SelectDelete(db, pSelect);
|
|
sqlite3IdListDelete(db, pColumn);
|
|
sqlite3DbFree(db, aRegIdx);
|
|
}
|
|
|
|
/* Make sure "isView" and other macros defined above are undefined. Otherwise
|
|
** they may interfere with compilation of other functions in this file
|
|
** (or in another file, if this file becomes part of the amalgamation). */
|
|
#ifdef isView
|
|
#undef isView
|
|
#endif
|
|
#ifdef pTrigger
|
|
#undef pTrigger
|
|
#endif
|
|
#ifdef tmask
|
|
#undef tmask
|
|
#endif
|
|
|
|
/*
|
|
** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
|
|
*/
|
|
#define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
|
|
#define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
|
|
|
|
/* This is the Walker callback from checkConstraintUnchanged(). Set
|
|
** bit 0x01 of pWalker->eCode if
|
|
** pWalker->eCode to 0 if this expression node references any of the
|
|
** columns that are being modifed by an UPDATE statement.
|
|
*/
|
|
static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
|
|
if( pExpr->op==TK_COLUMN ){
|
|
assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
|
|
if( pExpr->iColumn>=0 ){
|
|
if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
|
|
pWalker->eCode |= CKCNSTRNT_COLUMN;
|
|
}
|
|
}else{
|
|
pWalker->eCode |= CKCNSTRNT_ROWID;
|
|
}
|
|
}
|
|
return WRC_Continue;
|
|
}
|
|
|
|
/*
|
|
** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
|
|
** only columns that are modified by the UPDATE are those for which
|
|
** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
|
|
**
|
|
** Return true if CHECK constraint pExpr does not use any of the
|
|
** changing columns (or the rowid if it is changing). In other words,
|
|
** return true if this CHECK constraint can be skipped when validating
|
|
** the new row in the UPDATE statement.
|
|
*/
|
|
static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
|
|
Walker w;
|
|
memset(&w, 0, sizeof(w));
|
|
w.eCode = 0;
|
|
w.xExprCallback = checkConstraintExprNode;
|
|
w.u.aiCol = aiChng;
|
|
sqlite3WalkExpr(&w, pExpr);
|
|
if( !chngRowid ){
|
|
testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
|
|
w.eCode &= ~CKCNSTRNT_ROWID;
|
|
}
|
|
testcase( w.eCode==0 );
|
|
testcase( w.eCode==CKCNSTRNT_COLUMN );
|
|
testcase( w.eCode==CKCNSTRNT_ROWID );
|
|
testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
|
|
return !w.eCode;
|
|
}
|
|
|
|
/*
|
|
** Generate code to do constraint checks prior to an INSERT or an UPDATE
|
|
** on table pTab.
|
|
**
|
|
** The regNewData parameter is the first register in a range that contains
|
|
** the data to be inserted or the data after the update. There will be
|
|
** pTab->nCol+1 registers in this range. The first register (the one
|
|
** that regNewData points to) will contain the new rowid, or NULL in the
|
|
** case of a WITHOUT ROWID table. The second register in the range will
|
|
** contain the content of the first table column. The third register will
|
|
** contain the content of the second table column. And so forth.
|
|
**
|
|
** The regOldData parameter is similar to regNewData except that it contains
|
|
** the data prior to an UPDATE rather than afterwards. regOldData is zero
|
|
** for an INSERT. This routine can distinguish between UPDATE and INSERT by
|
|
** checking regOldData for zero.
|
|
**
|
|
** For an UPDATE, the pkChng boolean is true if the true primary key (the
|
|
** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
|
|
** might be modified by the UPDATE. If pkChng is false, then the key of
|
|
** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
|
|
**
|
|
** For an INSERT, the pkChng boolean indicates whether or not the rowid
|
|
** was explicitly specified as part of the INSERT statement. If pkChng
|
|
** is zero, it means that the either rowid is computed automatically or
|
|
** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
|
|
** pkChng will only be true if the INSERT statement provides an integer
|
|
** value for either the rowid column or its INTEGER PRIMARY KEY alias.
|
|
**
|
|
** The code generated by this routine will store new index entries into
|
|
** registers identified by aRegIdx[]. No index entry is created for
|
|
** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
|
|
** the same as the order of indices on the linked list of indices
|
|
** at pTab->pIndex.
|
|
**
|
|
** The caller must have already opened writeable cursors on the main
|
|
** table and all applicable indices (that is to say, all indices for which
|
|
** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
|
|
** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
|
|
** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
|
|
** for the first index in the pTab->pIndex list. Cursors for other indices
|
|
** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
|
|
**
|
|
** This routine also generates code to check constraints. NOT NULL,
|
|
** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
|
|
** then the appropriate action is performed. There are five possible
|
|
** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
|
|
**
|
|
** Constraint type Action What Happens
|
|
** --------------- ---------- ----------------------------------------
|
|
** any ROLLBACK The current transaction is rolled back and
|
|
** sqlite3_step() returns immediately with a
|
|
** return code of SQLITE_CONSTRAINT.
|
|
**
|
|
** any ABORT Back out changes from the current command
|
|
** only (do not do a complete rollback) then
|
|
** cause sqlite3_step() to return immediately
|
|
** with SQLITE_CONSTRAINT.
|
|
**
|
|
** any FAIL Sqlite3_step() returns immediately with a
|
|
** return code of SQLITE_CONSTRAINT. The
|
|
** transaction is not rolled back and any
|
|
** changes to prior rows are retained.
|
|
**
|
|
** any IGNORE The attempt in insert or update the current
|
|
** row is skipped, without throwing an error.
|
|
** Processing continues with the next row.
|
|
** (There is an immediate jump to ignoreDest.)
|
|
**
|
|
** NOT NULL REPLACE The NULL value is replace by the default
|
|
** value for that column. If the default value
|
|
** is NULL, the action is the same as ABORT.
|
|
**
|
|
** UNIQUE REPLACE The other row that conflicts with the row
|
|
** being inserted is removed.
|
|
**
|
|
** CHECK REPLACE Illegal. The results in an exception.
|
|
**
|
|
** Which action to take is determined by the overrideError parameter.
|
|
** Or if overrideError==OE_Default, then the pParse->onError parameter
|
|
** is used. Or if pParse->onError==OE_Default then the onError value
|
|
** for the constraint is used.
|
|
*/
|
|
void sqlite3GenerateConstraintChecks(
|
|
Parse *pParse, /* The parser context */
|
|
Table *pTab, /* The table being inserted or updated */
|
|
int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
|
|
int iDataCur, /* Canonical data cursor (main table or PK index) */
|
|
int iIdxCur, /* First index cursor */
|
|
int regNewData, /* First register in a range holding values to insert */
|
|
int regOldData, /* Previous content. 0 for INSERTs */
|
|
u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
|
|
u8 overrideError, /* Override onError to this if not OE_Default */
|
|
int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
|
|
int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
|
|
int *aiChng /* column i is unchanged if aiChng[i]<0 */
|
|
){
|
|
Vdbe *v; /* VDBE under constrution */
|
|
Index *pIdx; /* Pointer to one of the indices */
|
|
Index *pPk = 0; /* The PRIMARY KEY index */
|
|
sqlite3 *db; /* Database connection */
|
|
int i; /* loop counter */
|
|
int ix; /* Index loop counter */
|
|
int nCol; /* Number of columns */
|
|
int onError; /* Conflict resolution strategy */
|
|
int addr1; /* Address of jump instruction */
|
|
int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
|
|
int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
|
|
int ipkTop = 0; /* Top of the rowid change constraint check */
|
|
int ipkBottom = 0; /* Bottom of the rowid change constraint check */
|
|
u8 isUpdate; /* True if this is an UPDATE operation */
|
|
u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
|
|
int regRowid = -1; /* Register holding ROWID value */
|
|
|
|
isUpdate = regOldData!=0;
|
|
db = pParse->db;
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( v!=0 );
|
|
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
|
|
nCol = pTab->nCol;
|
|
|
|
/* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
|
|
** normal rowid tables. nPkField is the number of key fields in the
|
|
** pPk index or 1 for a rowid table. In other words, nPkField is the
|
|
** number of fields in the true primary key of the table. */
|
|
if( HasRowid(pTab) ){
|
|
pPk = 0;
|
|
nPkField = 1;
|
|
}else{
|
|
pPk = sqlite3PrimaryKeyIndex(pTab);
|
|
nPkField = pPk->nKeyCol;
|
|
}
|
|
|
|
/* Record that this module has started */
|
|
VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
|
|
iDataCur, iIdxCur, regNewData, regOldData, pkChng));
|
|
|
|
/* Test all NOT NULL constraints.
|
|
*/
|
|
for(i=0; i<nCol; i++){
|
|
if( i==pTab->iPKey ){
|
|
continue; /* ROWID is never NULL */
|
|
}
|
|
if( aiChng && aiChng[i]<0 ){
|
|
/* Don't bother checking for NOT NULL on columns that do not change */
|
|
continue;
|
|
}
|
|
onError = pTab->aCol[i].notNull;
|
|
if( onError==OE_None ) continue; /* This column is allowed to be NULL */
|
|
if( overrideError!=OE_Default ){
|
|
onError = overrideError;
|
|
}else if( onError==OE_Default ){
|
|
onError = OE_Abort;
|
|
}
|
|
if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
|
|
onError = OE_Abort;
|
|
}
|
|
assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
|
|
|| onError==OE_Ignore || onError==OE_Replace );
|
|
switch( onError ){
|
|
case OE_Abort:
|
|
sqlite3MayAbort(pParse);
|
|
/* Fall through */
|
|
case OE_Rollback:
|
|
case OE_Fail: {
|
|
char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
|
|
pTab->aCol[i].zName);
|
|
sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
|
|
regNewData+1+i, zMsg, P4_DYNAMIC);
|
|
sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
|
|
VdbeCoverage(v);
|
|
break;
|
|
}
|
|
case OE_Ignore: {
|
|
sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
|
|
VdbeCoverage(v);
|
|
break;
|
|
}
|
|
default: {
|
|
assert( onError==OE_Replace );
|
|
addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
|
|
VdbeCoverage(v);
|
|
sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Test all CHECK constraints
|
|
*/
|
|
#ifndef SQLITE_OMIT_CHECK
|
|
if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
|
|
ExprList *pCheck = pTab->pCheck;
|
|
pParse->ckBase = regNewData+1;
|
|
onError = overrideError!=OE_Default ? overrideError : OE_Abort;
|
|
for(i=0; i<pCheck->nExpr; i++){
|
|
int allOk;
|
|
Expr *pExpr = pCheck->a[i].pExpr;
|
|
if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
|
|
allOk = sqlite3VdbeMakeLabel(v);
|
|
sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
|
|
if( onError==OE_Ignore ){
|
|
sqlite3VdbeGoto(v, ignoreDest);
|
|
}else{
|
|
char *zName = pCheck->a[i].zName;
|
|
if( zName==0 ) zName = pTab->zName;
|
|
if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
|
|
sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
|
|
onError, zName, P4_TRANSIENT,
|
|
P5_ConstraintCheck);
|
|
}
|
|
sqlite3VdbeResolveLabel(v, allOk);
|
|
}
|
|
}
|
|
#endif /* !defined(SQLITE_OMIT_CHECK) */
|
|
|
|
/* If rowid is changing, make sure the new rowid does not previously
|
|
** exist in the table.
|
|
*/
|
|
if( pkChng && pPk==0 ){
|
|
int addrRowidOk = sqlite3VdbeMakeLabel(v);
|
|
|
|
/* Figure out what action to take in case of a rowid collision */
|
|
onError = pTab->keyConf;
|
|
if( overrideError!=OE_Default ){
|
|
onError = overrideError;
|
|
}else if( onError==OE_Default ){
|
|
onError = OE_Abort;
|
|
}
|
|
|
|
if( isUpdate ){
|
|
/* pkChng!=0 does not mean that the rowid has change, only that
|
|
** it might have changed. Skip the conflict logic below if the rowid
|
|
** is unchanged. */
|
|
sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
|
|
sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
|
|
VdbeCoverage(v);
|
|
}
|
|
|
|
/* If the response to a rowid conflict is REPLACE but the response
|
|
** to some other UNIQUE constraint is FAIL or IGNORE, then we need
|
|
** to defer the running of the rowid conflict checking until after
|
|
** the UNIQUE constraints have run.
|
|
*/
|
|
if( onError==OE_Replace && overrideError!=OE_Replace ){
|
|
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
|
|
ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Check to see if the new rowid already exists in the table. Skip
|
|
** the following conflict logic if it does not. */
|
|
sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
|
|
VdbeCoverage(v);
|
|
|
|
/* Generate code that deals with a rowid collision */
|
|
switch( onError ){
|
|
default: {
|
|
onError = OE_Abort;
|
|
/* Fall thru into the next case */
|
|
}
|
|
case OE_Rollback:
|
|
case OE_Abort:
|
|
case OE_Fail: {
|
|
sqlite3RowidConstraint(pParse, onError, pTab);
|
|
break;
|
|
}
|
|
case OE_Replace: {
|
|
/* If there are DELETE triggers on this table and the
|
|
** recursive-triggers flag is set, call GenerateRowDelete() to
|
|
** remove the conflicting row from the table. This will fire
|
|
** the triggers and remove both the table and index b-tree entries.
|
|
**
|
|
** Otherwise, if there are no triggers or the recursive-triggers
|
|
** flag is not set, but the table has one or more indexes, call
|
|
** GenerateRowIndexDelete(). This removes the index b-tree entries
|
|
** only. The table b-tree entry will be replaced by the new entry
|
|
** when it is inserted.
|
|
**
|
|
** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
|
|
** also invoke MultiWrite() to indicate that this VDBE may require
|
|
** statement rollback (if the statement is aborted after the delete
|
|
** takes place). Earlier versions called sqlite3MultiWrite() regardless,
|
|
** but being more selective here allows statements like:
|
|
**
|
|
** REPLACE INTO t(rowid) VALUES($newrowid)
|
|
**
|
|
** to run without a statement journal if there are no indexes on the
|
|
** table.
|
|
*/
|
|
Trigger *pTrigger = 0;
|
|
if( db->flags&SQLITE_RecTriggers ){
|
|
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
|
|
}
|
|
if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
|
|
sqlite3MultiWrite(pParse);
|
|
sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
|
|
regNewData, 1, 0, OE_Replace,
|
|
ONEPASS_SINGLE, -1);
|
|
}else{
|
|
if( pTab->pIndex ){
|
|
sqlite3MultiWrite(pParse);
|
|
sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
|
|
}
|
|
}
|
|
seenReplace = 1;
|
|
break;
|
|
}
|
|
case OE_Ignore: {
|
|
/*assert( seenReplace==0 );*/
|
|
sqlite3VdbeGoto(v, ignoreDest);
|
|
break;
|
|
}
|
|
}
|
|
sqlite3VdbeResolveLabel(v, addrRowidOk);
|
|
if( ipkTop ){
|
|
ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
|
|
sqlite3VdbeJumpHere(v, ipkTop);
|
|
}
|
|
}
|
|
|
|
/* Test all UNIQUE constraints by creating entries for each UNIQUE
|
|
** index and making sure that duplicate entries do not already exist.
|
|
** Compute the revised record entries for indices as we go.
|
|
**
|
|
** This loop also handles the case of the PRIMARY KEY index for a
|
|
** WITHOUT ROWID table.
|
|
*/
|
|
for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
|
|
int regIdx; /* Range of registers hold conent for pIdx */
|
|
int regR; /* Range of registers holding conflicting PK */
|
|
int iThisCur; /* Cursor for this UNIQUE index */
|
|
int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
|
|
|
|
if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
|
|
if( bAffinityDone==0 ){
|
|
sqlite3TableAffinity(v, pTab, regNewData+1);
|
|
bAffinityDone = 1;
|
|
}
|
|
iThisCur = iIdxCur+ix;
|
|
addrUniqueOk = sqlite3VdbeMakeLabel(v);
|
|
|
|
/* Skip partial indices for which the WHERE clause is not true */
|
|
if( pIdx->pPartIdxWhere ){
|
|
sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
|
|
pParse->ckBase = regNewData+1;
|
|
sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
|
|
SQLITE_JUMPIFNULL);
|
|
pParse->ckBase = 0;
|
|
}
|
|
|
|
/* Create a record for this index entry as it should appear after
|
|
** the insert or update. Store that record in the aRegIdx[ix] register
|
|
*/
|
|
regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
|
|
for(i=0; i<pIdx->nColumn; i++){
|
|
int iField = pIdx->aiColumn[i];
|
|
int x;
|
|
if( iField==XN_EXPR ){
|
|
pParse->ckBase = regNewData+1;
|
|
sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
|
|
pParse->ckBase = 0;
|
|
VdbeComment((v, "%s column %d", pIdx->zName, i));
|
|
}else{
|
|
if( iField==XN_ROWID || iField==pTab->iPKey ){
|
|
if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
|
|
x = regNewData;
|
|
regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
|
|
}else{
|
|
x = iField + regNewData + 1;
|
|
}
|
|
sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
|
|
VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
|
|
}
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
|
|
VdbeComment((v, "for %s", pIdx->zName));
|
|
sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
|
|
|
|
/* In an UPDATE operation, if this index is the PRIMARY KEY index
|
|
** of a WITHOUT ROWID table and there has been no change the
|
|
** primary key, then no collision is possible. The collision detection
|
|
** logic below can all be skipped. */
|
|
if( isUpdate && pPk==pIdx && pkChng==0 ){
|
|
sqlite3VdbeResolveLabel(v, addrUniqueOk);
|
|
continue;
|
|
}
|
|
|
|
/* Find out what action to take in case there is a uniqueness conflict */
|
|
onError = pIdx->onError;
|
|
if( onError==OE_None ){
|
|
sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
|
|
sqlite3VdbeResolveLabel(v, addrUniqueOk);
|
|
continue; /* pIdx is not a UNIQUE index */
|
|
}
|
|
if( overrideError!=OE_Default ){
|
|
onError = overrideError;
|
|
}else if( onError==OE_Default ){
|
|
onError = OE_Abort;
|
|
}
|
|
|
|
/* Check to see if the new index entry will be unique */
|
|
sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
|
|
regIdx, pIdx->nKeyCol); VdbeCoverage(v);
|
|
|
|
/* Generate code to handle collisions */
|
|
regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
|
|
if( isUpdate || onError==OE_Replace ){
|
|
if( HasRowid(pTab) ){
|
|
sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
|
|
/* Conflict only if the rowid of the existing index entry
|
|
** is different from old-rowid */
|
|
if( isUpdate ){
|
|
sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
|
|
sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
|
|
VdbeCoverage(v);
|
|
}
|
|
}else{
|
|
int x;
|
|
/* Extract the PRIMARY KEY from the end of the index entry and
|
|
** store it in registers regR..regR+nPk-1 */
|
|
if( pIdx!=pPk ){
|
|
for(i=0; i<pPk->nKeyCol; i++){
|
|
assert( pPk->aiColumn[i]>=0 );
|
|
x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
|
|
sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
|
|
VdbeComment((v, "%s.%s", pTab->zName,
|
|
pTab->aCol[pPk->aiColumn[i]].zName));
|
|
}
|
|
}
|
|
if( isUpdate ){
|
|
/* If currently processing the PRIMARY KEY of a WITHOUT ROWID
|
|
** table, only conflict if the new PRIMARY KEY values are actually
|
|
** different from the old.
|
|
**
|
|
** For a UNIQUE index, only conflict if the PRIMARY KEY values
|
|
** of the matched index row are different from the original PRIMARY
|
|
** KEY values of this row before the update. */
|
|
int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
|
|
int op = OP_Ne;
|
|
int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
|
|
|
|
for(i=0; i<pPk->nKeyCol; i++){
|
|
char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
|
|
x = pPk->aiColumn[i];
|
|
assert( x>=0 );
|
|
if( i==(pPk->nKeyCol-1) ){
|
|
addrJump = addrUniqueOk;
|
|
op = OP_Eq;
|
|
}
|
|
sqlite3VdbeAddOp4(v, op,
|
|
regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
|
|
);
|
|
sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
|
|
VdbeCoverageIf(v, op==OP_Eq);
|
|
VdbeCoverageIf(v, op==OP_Ne);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/* Generate code that executes if the new index entry is not unique */
|
|
assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
|
|
|| onError==OE_Ignore || onError==OE_Replace );
|
|
switch( onError ){
|
|
case OE_Rollback:
|
|
case OE_Abort:
|
|
case OE_Fail: {
|
|
sqlite3UniqueConstraint(pParse, onError, pIdx);
|
|
break;
|
|
}
|
|
case OE_Ignore: {
|
|
sqlite3VdbeGoto(v, ignoreDest);
|
|
break;
|
|
}
|
|
default: {
|
|
Trigger *pTrigger = 0;
|
|
assert( onError==OE_Replace );
|
|
sqlite3MultiWrite(pParse);
|
|
if( db->flags&SQLITE_RecTriggers ){
|
|
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
|
|
}
|
|
sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
|
|
regR, nPkField, 0, OE_Replace,
|
|
(pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
|
|
seenReplace = 1;
|
|
break;
|
|
}
|
|
}
|
|
sqlite3VdbeResolveLabel(v, addrUniqueOk);
|
|
sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
|
|
if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
|
|
}
|
|
if( ipkTop ){
|
|
sqlite3VdbeGoto(v, ipkTop+1);
|
|
sqlite3VdbeJumpHere(v, ipkBottom);
|
|
}
|
|
|
|
*pbMayReplace = seenReplace;
|
|
VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
|
|
}
|
|
|
|
/*
|
|
** This routine generates code to finish the INSERT or UPDATE operation
|
|
** that was started by a prior call to sqlite3GenerateConstraintChecks.
|
|
** A consecutive range of registers starting at regNewData contains the
|
|
** rowid and the content to be inserted.
|
|
**
|
|
** The arguments to this routine should be the same as the first six
|
|
** arguments to sqlite3GenerateConstraintChecks.
|
|
*/
|
|
void sqlite3CompleteInsertion(
|
|
Parse *pParse, /* The parser context */
|
|
Table *pTab, /* the table into which we are inserting */
|
|
int iDataCur, /* Cursor of the canonical data source */
|
|
int iIdxCur, /* First index cursor */
|
|
int regNewData, /* Range of content */
|
|
int *aRegIdx, /* Register used by each index. 0 for unused indices */
|
|
int isUpdate, /* True for UPDATE, False for INSERT */
|
|
int appendBias, /* True if this is likely to be an append */
|
|
int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
|
|
){
|
|
Vdbe *v; /* Prepared statements under construction */
|
|
Index *pIdx; /* An index being inserted or updated */
|
|
u8 pik_flags; /* flag values passed to the btree insert */
|
|
int regData; /* Content registers (after the rowid) */
|
|
int regRec; /* Register holding assembled record for the table */
|
|
int i; /* Loop counter */
|
|
u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
|
|
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( v!=0 );
|
|
assert( pTab->pSelect==0 ); /* This table is not a VIEW */
|
|
for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
|
if( aRegIdx[i]==0 ) continue;
|
|
bAffinityDone = 1;
|
|
if( pIdx->pPartIdxWhere ){
|
|
sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
|
|
VdbeCoverage(v);
|
|
}
|
|
sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
|
|
pik_flags = 0;
|
|
if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
|
|
if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
|
|
assert( pParse->nested==0 );
|
|
pik_flags |= OPFLAG_NCHANGE;
|
|
}
|
|
sqlite3VdbeChangeP5(v, pik_flags);
|
|
}
|
|
if( !HasRowid(pTab) ) return;
|
|
regData = regNewData + 1;
|
|
regRec = sqlite3GetTempReg(pParse);
|
|
sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
|
|
if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
|
|
sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
|
|
if( pParse->nested ){
|
|
pik_flags = 0;
|
|
}else{
|
|
pik_flags = OPFLAG_NCHANGE;
|
|
pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
|
|
}
|
|
if( appendBias ){
|
|
pik_flags |= OPFLAG_APPEND;
|
|
}
|
|
if( useSeekResult ){
|
|
pik_flags |= OPFLAG_USESEEKRESULT;
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
|
|
if( !pParse->nested ){
|
|
sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
|
|
}
|
|
sqlite3VdbeChangeP5(v, pik_flags);
|
|
}
|
|
|
|
/*
|
|
** Allocate cursors for the pTab table and all its indices and generate
|
|
** code to open and initialized those cursors.
|
|
**
|
|
** The cursor for the object that contains the complete data (normally
|
|
** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
|
|
** ROWID table) is returned in *piDataCur. The first index cursor is
|
|
** returned in *piIdxCur. The number of indices is returned.
|
|
**
|
|
** Use iBase as the first cursor (either the *piDataCur for rowid tables
|
|
** or the first index for WITHOUT ROWID tables) if it is non-negative.
|
|
** If iBase is negative, then allocate the next available cursor.
|
|
**
|
|
** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
|
|
** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
|
|
** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
|
|
** pTab->pIndex list.
|
|
**
|
|
** If pTab is a virtual table, then this routine is a no-op and the
|
|
** *piDataCur and *piIdxCur values are left uninitialized.
|
|
*/
|
|
int sqlite3OpenTableAndIndices(
|
|
Parse *pParse, /* Parsing context */
|
|
Table *pTab, /* Table to be opened */
|
|
int op, /* OP_OpenRead or OP_OpenWrite */
|
|
u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
|
|
int iBase, /* Use this for the table cursor, if there is one */
|
|
u8 *aToOpen, /* If not NULL: boolean for each table and index */
|
|
int *piDataCur, /* Write the database source cursor number here */
|
|
int *piIdxCur /* Write the first index cursor number here */
|
|
){
|
|
int i;
|
|
int iDb;
|
|
int iDataCur;
|
|
Index *pIdx;
|
|
Vdbe *v;
|
|
|
|
assert( op==OP_OpenRead || op==OP_OpenWrite );
|
|
assert( op==OP_OpenWrite || p5==0 );
|
|
if( IsVirtual(pTab) ){
|
|
/* This routine is a no-op for virtual tables. Leave the output
|
|
** variables *piDataCur and *piIdxCur uninitialized so that valgrind
|
|
** can detect if they are used by mistake in the caller. */
|
|
return 0;
|
|
}
|
|
iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
|
v = sqlite3GetVdbe(pParse);
|
|
assert( v!=0 );
|
|
if( iBase<0 ) iBase = pParse->nTab;
|
|
iDataCur = iBase++;
|
|
if( piDataCur ) *piDataCur = iDataCur;
|
|
if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
|
|
sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
|
|
}else{
|
|
sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
|
|
}
|
|
if( piIdxCur ) *piIdxCur = iBase;
|
|
for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
|
|
int iIdxCur = iBase++;
|
|
assert( pIdx->pSchema==pTab->pSchema );
|
|
if( aToOpen==0 || aToOpen[i+1] ){
|
|
sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
|
|
sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
|
|
VdbeComment((v, "%s", pIdx->zName));
|
|
}
|
|
if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
|
|
if( piDataCur ) *piDataCur = iIdxCur;
|
|
}else{
|
|
sqlite3VdbeChangeP5(v, p5);
|
|
}
|
|
}
|
|
if( iBase>pParse->nTab ) pParse->nTab = iBase;
|
|
return i;
|
|
}
|
|
|
|
|
|
#ifdef SQLITE_TEST
|
|
/*
|
|
** The following global variable is incremented whenever the
|
|
** transfer optimization is used. This is used for testing
|
|
** purposes only - to make sure the transfer optimization really
|
|
** is happening when it is supposed to.
|
|
*/
|
|
int sqlite3_xferopt_count;
|
|
#endif /* SQLITE_TEST */
|
|
|
|
|
|
#ifndef SQLITE_OMIT_XFER_OPT
|
|
/*
|
|
** Check to see if index pSrc is compatible as a source of data
|
|
** for index pDest in an insert transfer optimization. The rules
|
|
** for a compatible index:
|
|
**
|
|
** * The index is over the same set of columns
|
|
** * The same DESC and ASC markings occurs on all columns
|
|
** * The same onError processing (OE_Abort, OE_Ignore, etc)
|
|
** * The same collating sequence on each column
|
|
** * The index has the exact same WHERE clause
|
|
*/
|
|
static int xferCompatibleIndex(Index *pDest, Index *pSrc){
|
|
int i;
|
|
assert( pDest && pSrc );
|
|
assert( pDest->pTable!=pSrc->pTable );
|
|
if( pDest->nKeyCol!=pSrc->nKeyCol ){
|
|
return 0; /* Different number of columns */
|
|
}
|
|
if( pDest->onError!=pSrc->onError ){
|
|
return 0; /* Different conflict resolution strategies */
|
|
}
|
|
for(i=0; i<pSrc->nKeyCol; i++){
|
|
if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
|
|
return 0; /* Different columns indexed */
|
|
}
|
|
if( pSrc->aiColumn[i]==XN_EXPR ){
|
|
assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
|
|
if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
|
|
pDest->aColExpr->a[i].pExpr, -1)!=0 ){
|
|
return 0; /* Different expressions in the index */
|
|
}
|
|
}
|
|
if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
|
|
return 0; /* Different sort orders */
|
|
}
|
|
if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
|
|
return 0; /* Different collating sequences */
|
|
}
|
|
}
|
|
if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
|
|
return 0; /* Different WHERE clauses */
|
|
}
|
|
|
|
/* If no test above fails then the indices must be compatible */
|
|
return 1;
|
|
}
|
|
|
|
/*
|
|
** Attempt the transfer optimization on INSERTs of the form
|
|
**
|
|
** INSERT INTO tab1 SELECT * FROM tab2;
|
|
**
|
|
** The xfer optimization transfers raw records from tab2 over to tab1.
|
|
** Columns are not decoded and reassembled, which greatly improves
|
|
** performance. Raw index records are transferred in the same way.
|
|
**
|
|
** The xfer optimization is only attempted if tab1 and tab2 are compatible.
|
|
** There are lots of rules for determining compatibility - see comments
|
|
** embedded in the code for details.
|
|
**
|
|
** This routine returns TRUE if the optimization is guaranteed to be used.
|
|
** Sometimes the xfer optimization will only work if the destination table
|
|
** is empty - a factor that can only be determined at run-time. In that
|
|
** case, this routine generates code for the xfer optimization but also
|
|
** does a test to see if the destination table is empty and jumps over the
|
|
** xfer optimization code if the test fails. In that case, this routine
|
|
** returns FALSE so that the caller will know to go ahead and generate
|
|
** an unoptimized transfer. This routine also returns FALSE if there
|
|
** is no chance that the xfer optimization can be applied.
|
|
**
|
|
** This optimization is particularly useful at making VACUUM run faster.
|
|
*/
|
|
static int xferOptimization(
|
|
Parse *pParse, /* Parser context */
|
|
Table *pDest, /* The table we are inserting into */
|
|
Select *pSelect, /* A SELECT statement to use as the data source */
|
|
int onError, /* How to handle constraint errors */
|
|
int iDbDest /* The database of pDest */
|
|
){
|
|
sqlite3 *db = pParse->db;
|
|
ExprList *pEList; /* The result set of the SELECT */
|
|
Table *pSrc; /* The table in the FROM clause of SELECT */
|
|
Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
|
|
struct SrcList_item *pItem; /* An element of pSelect->pSrc */
|
|
int i; /* Loop counter */
|
|
int iDbSrc; /* The database of pSrc */
|
|
int iSrc, iDest; /* Cursors from source and destination */
|
|
int addr1, addr2; /* Loop addresses */
|
|
int emptyDestTest = 0; /* Address of test for empty pDest */
|
|
int emptySrcTest = 0; /* Address of test for empty pSrc */
|
|
Vdbe *v; /* The VDBE we are building */
|
|
int regAutoinc; /* Memory register used by AUTOINC */
|
|
int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
|
|
int regData, regRowid; /* Registers holding data and rowid */
|
|
|
|
if( pSelect==0 ){
|
|
return 0; /* Must be of the form INSERT INTO ... SELECT ... */
|
|
}
|
|
if( pParse->pWith || pSelect->pWith ){
|
|
/* Do not attempt to process this query if there are an WITH clauses
|
|
** attached to it. Proceeding may generate a false "no such table: xxx"
|
|
** error if pSelect reads from a CTE named "xxx". */
|
|
return 0;
|
|
}
|
|
if( sqlite3TriggerList(pParse, pDest) ){
|
|
return 0; /* tab1 must not have triggers */
|
|
}
|
|
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
|
if( pDest->tabFlags & TF_Virtual ){
|
|
return 0; /* tab1 must not be a virtual table */
|
|
}
|
|
#endif
|
|
if( onError==OE_Default ){
|
|
if( pDest->iPKey>=0 ) onError = pDest->keyConf;
|
|
if( onError==OE_Default ) onError = OE_Abort;
|
|
}
|
|
assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
|
|
if( pSelect->pSrc->nSrc!=1 ){
|
|
return 0; /* FROM clause must have exactly one term */
|
|
}
|
|
if( pSelect->pSrc->a[0].pSelect ){
|
|
return 0; /* FROM clause cannot contain a subquery */
|
|
}
|
|
if( pSelect->pWhere ){
|
|
return 0; /* SELECT may not have a WHERE clause */
|
|
}
|
|
if( pSelect->pOrderBy ){
|
|
return 0; /* SELECT may not have an ORDER BY clause */
|
|
}
|
|
/* Do not need to test for a HAVING clause. If HAVING is present but
|
|
** there is no ORDER BY, we will get an error. */
|
|
if( pSelect->pGroupBy ){
|
|
return 0; /* SELECT may not have a GROUP BY clause */
|
|
}
|
|
if( pSelect->pLimit ){
|
|
return 0; /* SELECT may not have a LIMIT clause */
|
|
}
|
|
assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
|
|
if( pSelect->pPrior ){
|
|
return 0; /* SELECT may not be a compound query */
|
|
}
|
|
if( pSelect->selFlags & SF_Distinct ){
|
|
return 0; /* SELECT may not be DISTINCT */
|
|
}
|
|
pEList = pSelect->pEList;
|
|
assert( pEList!=0 );
|
|
if( pEList->nExpr!=1 ){
|
|
return 0; /* The result set must have exactly one column */
|
|
}
|
|
assert( pEList->a[0].pExpr );
|
|
if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
|
|
return 0; /* The result set must be the special operator "*" */
|
|
}
|
|
|
|
/* At this point we have established that the statement is of the
|
|
** correct syntactic form to participate in this optimization. Now
|
|
** we have to check the semantics.
|
|
*/
|
|
pItem = pSelect->pSrc->a;
|
|
pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
|
|
if( pSrc==0 ){
|
|
return 0; /* FROM clause does not contain a real table */
|
|
}
|
|
if( pSrc==pDest ){
|
|
return 0; /* tab1 and tab2 may not be the same table */
|
|
}
|
|
if( HasRowid(pDest)!=HasRowid(pSrc) ){
|
|
return 0; /* source and destination must both be WITHOUT ROWID or not */
|
|
}
|
|
#ifndef SQLITE_OMIT_VIRTUALTABLE
|
|
if( pSrc->tabFlags & TF_Virtual ){
|
|
return 0; /* tab2 must not be a virtual table */
|
|
}
|
|
#endif
|
|
if( pSrc->pSelect ){
|
|
return 0; /* tab2 may not be a view */
|
|
}
|
|
if( pDest->nCol!=pSrc->nCol ){
|
|
return 0; /* Number of columns must be the same in tab1 and tab2 */
|
|
}
|
|
if( pDest->iPKey!=pSrc->iPKey ){
|
|
return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
|
|
}
|
|
for(i=0; i<pDest->nCol; i++){
|
|
Column *pDestCol = &pDest->aCol[i];
|
|
Column *pSrcCol = &pSrc->aCol[i];
|
|
#ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
|
|
if( (db->flags & SQLITE_Vacuum)==0
|
|
&& (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
|
|
){
|
|
return 0; /* Neither table may have __hidden__ columns */
|
|
}
|
|
#endif
|
|
if( pDestCol->affinity!=pSrcCol->affinity ){
|
|
return 0; /* Affinity must be the same on all columns */
|
|
}
|
|
if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
|
|
return 0; /* Collating sequence must be the same on all columns */
|
|
}
|
|
if( pDestCol->notNull && !pSrcCol->notNull ){
|
|
return 0; /* tab2 must be NOT NULL if tab1 is */
|
|
}
|
|
/* Default values for second and subsequent columns need to match. */
|
|
if( i>0
|
|
&& ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
|
|
|| (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
|
|
){
|
|
return 0; /* Default values must be the same for all columns */
|
|
}
|
|
}
|
|
for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
|
|
if( IsUniqueIndex(pDestIdx) ){
|
|
destHasUniqueIdx = 1;
|
|
}
|
|
for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
|
|
if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
|
|
}
|
|
if( pSrcIdx==0 ){
|
|
return 0; /* pDestIdx has no corresponding index in pSrc */
|
|
}
|
|
}
|
|
#ifndef SQLITE_OMIT_CHECK
|
|
if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
|
|
return 0; /* Tables have different CHECK constraints. Ticket #2252 */
|
|
}
|
|
#endif
|
|
#ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
/* Disallow the transfer optimization if the destination table constains
|
|
** any foreign key constraints. This is more restrictive than necessary.
|
|
** But the main beneficiary of the transfer optimization is the VACUUM
|
|
** command, and the VACUUM command disables foreign key constraints. So
|
|
** the extra complication to make this rule less restrictive is probably
|
|
** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
|
|
*/
|
|
if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
|
|
return 0;
|
|
}
|
|
#endif
|
|
if( (db->flags & SQLITE_CountRows)!=0 ){
|
|
return 0; /* xfer opt does not play well with PRAGMA count_changes */
|
|
}
|
|
|
|
/* If we get this far, it means that the xfer optimization is at
|
|
** least a possibility, though it might only work if the destination
|
|
** table (tab1) is initially empty.
|
|
*/
|
|
#ifdef SQLITE_TEST
|
|
sqlite3_xferopt_count++;
|
|
#endif
|
|
iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
|
|
v = sqlite3GetVdbe(pParse);
|
|
sqlite3CodeVerifySchema(pParse, iDbSrc);
|
|
iSrc = pParse->nTab++;
|
|
iDest = pParse->nTab++;
|
|
regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
|
|
regData = sqlite3GetTempReg(pParse);
|
|
regRowid = sqlite3GetTempReg(pParse);
|
|
sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
|
|
assert( HasRowid(pDest) || destHasUniqueIdx );
|
|
if( (db->flags & SQLITE_Vacuum)==0 && (
|
|
(pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
|
|
|| destHasUniqueIdx /* (2) */
|
|
|| (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
|
|
)){
|
|
/* In some circumstances, we are able to run the xfer optimization
|
|
** only if the destination table is initially empty. Unless the
|
|
** SQLITE_Vacuum flag is set, this block generates code to make
|
|
** that determination. If SQLITE_Vacuum is set, then the destination
|
|
** table is always empty.
|
|
**
|
|
** Conditions under which the destination must be empty:
|
|
**
|
|
** (1) There is no INTEGER PRIMARY KEY but there are indices.
|
|
** (If the destination is not initially empty, the rowid fields
|
|
** of index entries might need to change.)
|
|
**
|
|
** (2) The destination has a unique index. (The xfer optimization
|
|
** is unable to test uniqueness.)
|
|
**
|
|
** (3) onError is something other than OE_Abort and OE_Rollback.
|
|
*/
|
|
addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
|
|
emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
}
|
|
if( HasRowid(pSrc) ){
|
|
sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
|
|
emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
|
|
if( pDest->iPKey>=0 ){
|
|
addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
|
|
addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
|
|
VdbeCoverage(v);
|
|
sqlite3RowidConstraint(pParse, onError, pDest);
|
|
sqlite3VdbeJumpHere(v, addr2);
|
|
autoIncStep(pParse, regAutoinc, regRowid);
|
|
}else if( pDest->pIndex==0 ){
|
|
addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
|
|
}else{
|
|
addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
|
|
assert( (pDest->tabFlags & TF_Autoincrement)==0 );
|
|
}
|
|
sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
|
|
sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
|
|
pDest->zName, 0);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
|
|
sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
|
|
sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
|
|
}else{
|
|
sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
|
|
sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
|
|
}
|
|
for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
|
|
u8 idxInsFlags = 0;
|
|
for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
|
|
if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
|
|
}
|
|
assert( pSrcIdx );
|
|
sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
|
|
sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
|
|
VdbeComment((v, "%s", pSrcIdx->zName));
|
|
sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
|
|
sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
|
|
sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
|
|
VdbeComment((v, "%s", pDestIdx->zName));
|
|
addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
|
|
sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
|
|
if( db->flags & SQLITE_Vacuum ){
|
|
/* This INSERT command is part of a VACUUM operation, which guarantees
|
|
** that the destination table is empty. If all indexed columns use
|
|
** collation sequence BINARY, then it can also be assumed that the
|
|
** index will be populated by inserting keys in strictly sorted
|
|
** order. In this case, instead of seeking within the b-tree as part
|
|
** of every OP_IdxInsert opcode, an OP_Last is added before the
|
|
** OP_IdxInsert to seek to the point within the b-tree where each key
|
|
** should be inserted. This is faster.
|
|
**
|
|
** If any of the indexed columns use a collation sequence other than
|
|
** BINARY, this optimization is disabled. This is because the user
|
|
** might change the definition of a collation sequence and then run
|
|
** a VACUUM command. In that case keys may not be written in strictly
|
|
** sorted order. */
|
|
for(i=0; i<pSrcIdx->nColumn; i++){
|
|
const char *zColl = pSrcIdx->azColl[i];
|
|
assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
|
|
|| sqlite3StrBINARY==zColl );
|
|
if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
|
|
}
|
|
if( i==pSrcIdx->nColumn ){
|
|
idxInsFlags = OPFLAG_USESEEKRESULT;
|
|
sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
|
|
}
|
|
}
|
|
if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
|
|
idxInsFlags |= OPFLAG_NCHANGE;
|
|
}
|
|
sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
|
|
sqlite3VdbeChangeP5(v, idxInsFlags);
|
|
sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
|
|
sqlite3VdbeJumpHere(v, addr1);
|
|
sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
|
|
sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
|
|
}
|
|
if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
|
|
sqlite3ReleaseTempReg(pParse, regRowid);
|
|
sqlite3ReleaseTempReg(pParse, regData);
|
|
if( emptyDestTest ){
|
|
sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
|
|
sqlite3VdbeJumpHere(v, emptyDestTest);
|
|
sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
|
|
return 0;
|
|
}else{
|
|
return 1;
|
|
}
|
|
}
|
|
#endif /* SQLITE_OMIT_XFER_OPT */
|