Fossil SCM

Update SQLite to 3.13.0

jan.nijtmans 2016-05-19 14:19 UTC branch-1.34
Commit 256b950a7b016dcf4da14e3923099a797851f812
2 files changed +9536 -1998 +1478 -23
+9536 -1998
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -1,8 +1,8 @@
11
/******************************************************************************
22
** This file is an amalgamation of many separate C source files from SQLite
3
-** version 3.12.1. By combining all the individual C code files into this
3
+** version 3.13.0. By combining all the individual C code files into this
44
** single large file, the entire code can be compiled as a single translation
55
** unit. This allows many compilers to do optimizations that would not be
66
** possible if the files were compiled separately. Performance improvements
77
** of 5% or more are commonly seen when SQLite is compiled as a single
88
** translation unit.
@@ -37,10 +37,37 @@
3737
** Internal interface definitions for SQLite.
3838
**
3939
*/
4040
#ifndef _SQLITEINT_H_
4141
#define _SQLITEINT_H_
42
+
43
+/* Special Comments:
44
+**
45
+** Some comments have special meaning to the tools that measure test
46
+** coverage:
47
+**
48
+** NO_TEST - The branches on this line are not
49
+** measured by branch coverage. This is
50
+** used on lines of code that actually
51
+** implement parts of coverage testing.
52
+**
53
+** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
54
+** and the correct answer is still obtained,
55
+** though perhaps more slowly.
56
+**
57
+** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
58
+** and the correct answer is still obtained,
59
+** though perhaps more slowly.
60
+**
61
+** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
62
+** that would be harmless and undetectable
63
+** if it did occur.
64
+**
65
+** In all cases, the special comment must be enclosed in the usual
66
+** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67
+** asterisks and the comment text.
68
+*/
4269
4370
/*
4471
** Make sure that rand_s() is available on Windows systems with MSVC 2005
4572
** or higher.
4673
*/
@@ -334,13 +361,13 @@
334361
**
335362
** See also: [sqlite3_libversion()],
336363
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
337364
** [sqlite_version()] and [sqlite_source_id()].
338365
*/
339
-#define SQLITE_VERSION "3.12.1"
340
-#define SQLITE_VERSION_NUMBER 3012001
341
-#define SQLITE_SOURCE_ID "2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d"
366
+#define SQLITE_VERSION "3.13.0"
367
+#define SQLITE_VERSION_NUMBER 3013000
368
+#define SQLITE_SOURCE_ID "2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2"
342369
343370
/*
344371
** CAPI3REF: Run-Time Library Version Numbers
345372
** KEYWORDS: sqlite3_version, sqlite3_sourceid
346373
**
@@ -2155,16 +2182,34 @@
21552182
** The second parameter is a pointer to an integer into which
21562183
** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
21572184
** following this call. The second parameter may be a NULL pointer, in
21582185
** which case the new setting is not reported back. </dd>
21592186
**
2187
+** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2188
+** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2189
+** interface independently of the [load_extension()] SQL function.
2190
+** The [sqlite3_enable_load_extension()] API enables or disables both the
2191
+** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2192
+** There should be two additional arguments.
2193
+** When the first argument to this interface is 1, then only the C-API is
2194
+** enabled and the SQL function remains disabled. If the first argment to
2195
+** this interface is 0, then both the C-API and the SQL function are disabled.
2196
+** If the first argument is -1, then no changes are made to state of either the
2197
+** C-API or the SQL function.
2198
+** The second parameter is a pointer to an integer into which
2199
+** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2200
+** is disabled or enabled following this call. The second parameter may
2201
+** be a NULL pointer, in which case the new setting is not reported back.
2202
+** </dd>
2203
+**
21602204
** </dl>
21612205
*/
21622206
#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
21632207
#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
21642208
#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
21652209
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2210
+#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
21662211
21672212
21682213
/*
21692214
** CAPI3REF: Enable Or Disable Extended Result Codes
21702215
** METHOD: sqlite3
@@ -5410,11 +5455,11 @@
54105455
** METHOD: sqlite3
54115456
**
54125457
** ^The sqlite3_update_hook() interface registers a callback function
54135458
** with the [database connection] identified by the first argument
54145459
** to be invoked whenever a row is updated, inserted or deleted in
5415
-** a rowid table.
5460
+** a [rowid table].
54165461
** ^Any callback set by a previous call to this function
54175462
** for the same database connection is overridden.
54185463
**
54195464
** ^The second argument is a pointer to the function to invoke when a
54205465
** row is updated, inserted or deleted in a rowid table.
@@ -5449,12 +5494,12 @@
54495494
** ^The sqlite3_update_hook(D,C,P) function
54505495
** returns the P argument from the previous call
54515496
** on the same [database connection] D, or NULL for
54525497
** the first call on D.
54535498
**
5454
-** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5455
-** interfaces.
5499
+** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5500
+** and [sqlite3_preupdate_hook()] interfaces.
54565501
*/
54575502
SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
54585503
sqlite3*,
54595504
void(*)(void *,int ,char const *,char const *,sqlite3_int64),
54605505
void*
@@ -5697,12 +5742,21 @@
56975742
** fill *pzErrMsg with error message text stored in memory
56985743
** obtained from [sqlite3_malloc()]. The calling function
56995744
** should free this memory by calling [sqlite3_free()].
57005745
**
57015746
** ^Extension loading must be enabled using
5702
-** [sqlite3_enable_load_extension()] prior to calling this API,
5747
+** [sqlite3_enable_load_extension()] or
5748
+** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5749
+** prior to calling this API,
57035750
** otherwise an error will be returned.
5751
+**
5752
+** <b>Security warning:</b> It is recommended that the
5753
+** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5754
+** interface. The use of the [sqlite3_enable_load_extension()] interface
5755
+** should be avoided. This will keep the SQL function [load_extension()]
5756
+** disabled and prevent SQL injections from giving attackers
5757
+** access to extension loading capabilities.
57045758
**
57055759
** See also the [load_extension() SQL function].
57065760
*/
57075761
SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
57085762
sqlite3 *db, /* Load the extension into this database connection */
@@ -5722,10 +5776,21 @@
57225776
**
57235777
** ^Extension loading is off by default.
57245778
** ^Call the sqlite3_enable_load_extension() routine with onoff==1
57255779
** to turn extension loading on and call it with onoff==0 to turn
57265780
** it back off again.
5781
+**
5782
+** ^This interface enables or disables both the C-API
5783
+** [sqlite3_load_extension()] and the SQL function [load_extension()].
5784
+** Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5785
+** to enable or disable only the C-API.
5786
+**
5787
+** <b>Security warning:</b> It is recommended that extension loading
5788
+** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5789
+** rather than this interface, so the [load_extension()] SQL function
5790
+** remains disabled. This will prevent SQL injections from giving attackers
5791
+** access to extension loading capabilities.
57275792
*/
57285793
SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
57295794
57305795
/*
57315796
** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7360,11 +7425,11 @@
73607425
** and database name of the source database, respectively.
73617426
** ^The source and destination [database connections] (parameters S and D)
73627427
** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
73637428
** an error.
73647429
**
7365
-** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7430
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
73667431
** there is already a read or read-write transaction open on the
73677432
** destination database.
73687433
**
73697434
** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
73707435
** returned and an error code and error message are stored in the
@@ -8138,15 +8203,111 @@
81388203
** ^This function does not set the database handle error code or message
81398204
** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
81408205
*/
81418206
SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
81428207
8208
+/*
8209
+** CAPI3REF: The pre-update hook.
8210
+**
8211
+** ^These interfaces are only available if SQLite is compiled using the
8212
+** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8213
+**
8214
+** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8215
+** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8216
+** on a [rowid table].
8217
+** ^At most one preupdate hook may be registered at a time on a single
8218
+** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8219
+** the previous setting.
8220
+** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8221
+** with a NULL pointer as the second parameter.
8222
+** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8223
+** the first parameter to callbacks.
8224
+**
8225
+** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8226
+** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8227
+** tables.
8228
+**
8229
+** ^The second parameter to the preupdate callback is a pointer to
8230
+** the [database connection] that registered the preupdate hook.
8231
+** ^The third parameter to the preupdate callback is one of the constants
8232
+** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to indentify the
8233
+** kind of update operation that is about to occur.
8234
+** ^(The fourth parameter to the preupdate callback is the name of the
8235
+** database within the database connection that is being modified. This
8236
+** will be "main" for the main database or "temp" for TEMP tables or
8237
+** the name given after the AS keyword in the [ATTACH] statement for attached
8238
+** databases.)^
8239
+** ^The fifth parameter to the preupdate callback is the name of the
8240
+** table that is being modified.
8241
+** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8242
+** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8243
+** undefined for SQLITE_INSERT changes.
8244
+** ^The seventh parameter to the preupdate callback is the final [rowid] of
8245
+** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8246
+** undefined for SQLITE_DELETE changes.
8247
+**
8248
+** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8249
+** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8250
+** provide additional information about a preupdate event. These routines
8251
+** may only be called from within a preupdate callback. Invoking any of
8252
+** these routines from outside of a preupdate callback or with a
8253
+** [database connection] pointer that is different from the one supplied
8254
+** to the preupdate callback results in undefined and probably undesirable
8255
+** behavior.
8256
+**
8257
+** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8258
+** in the row that is being inserted, updated, or deleted.
8259
+**
8260
+** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8261
+** a [protected sqlite3_value] that contains the value of the Nth column of
8262
+** the table row before it is updated. The N parameter must be between 0
8263
+** and one less than the number of columns or the behavior will be
8264
+** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8265
+** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8266
+** behavior is undefined. The [sqlite3_value] that P points to
8267
+** will be destroyed when the preupdate callback returns.
8268
+**
8269
+** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8270
+** a [protected sqlite3_value] that contains the value of the Nth column of
8271
+** the table row after it is updated. The N parameter must be between 0
8272
+** and one less than the number of columns or the behavior will be
8273
+** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8274
+** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8275
+** behavior is undefined. The [sqlite3_value] that P points to
8276
+** will be destroyed when the preupdate callback returns.
8277
+**
8278
+** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8279
+** callback was invoked as a result of a direct insert, update, or delete
8280
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
8281
+** triggers; or 2 for changes resulting from triggers called by top-level
8282
+** triggers; and so forth.
8283
+**
8284
+** See also: [sqlite3_update_hook()]
8285
+*/
8286
+SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8287
+ sqlite3 *db,
8288
+ void(*xPreUpdate)(
8289
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
8290
+ sqlite3 *db, /* Database handle */
8291
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
8292
+ char const *zDb, /* Database name */
8293
+ char const *zName, /* Table name */
8294
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8295
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8296
+ ),
8297
+ void*
8298
+);
8299
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8300
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8301
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8302
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8303
+
81438304
/*
81448305
** CAPI3REF: Low-level system error code
81458306
**
81468307
** ^Attempt to return the underlying operating system error code or error
8147
-** number that caused the most reason I/O error or failure to open a file.
8308
+** number that caused the most recent I/O error or failure to open a file.
81488309
** The return value is OS-dependent. For example, on unix systems, after
81498310
** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
81508311
** called to get back the underlying "errno" that caused the problem, such
81518312
** as ENOSPC, EAUTH, EISDIR, and so forth.
81528313
*/
@@ -8208,24 +8369,33 @@
82088369
82098370
/*
82108371
** CAPI3REF: Start a read transaction on an historical snapshot
82118372
** EXPERIMENTAL
82128373
**
8213
-** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
8214
-** read transaction that is currently open on schema S of
8215
-** [database connection] D so that it refers to historical [snapshot] P.
8374
+** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8375
+** read transaction for schema S of
8376
+** [database connection] D such that the read transaction
8377
+** refers to historical [snapshot] P, rather than the most
8378
+** recent change to the database.
82168379
** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
82178380
** or an appropriate [error code] if it fails.
82188381
**
82198382
** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8220
-** the first operation, apart from other sqlite3_snapshot_open() calls,
8221
-** following the [BEGIN] that starts a new read transaction.
8222
-** ^A [snapshot] will fail to open if it has been overwritten by a
8383
+** the first operation following the [BEGIN] that takes the schema S
8384
+** out of [autocommit mode].
8385
+** ^In other words, schema S must not currently be in
8386
+** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8387
+** database connection D must be out of [autocommit mode].
8388
+** ^A [snapshot] will fail to open if it has been overwritten by a
82238389
** [checkpoint].
8224
-** ^A [snapshot] will fail to open if the database connection D has not
8225
-** previously completed at least one read operation against the database
8226
-** file. (Hint: Run "[PRAGMA application_id]" against a newly opened
8390
+** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8391
+** database connection D does not know that the database file for
8392
+** schema S is in [WAL mode]. A database connection might not know
8393
+** that the database file is in [WAL mode] if there has been no prior
8394
+** I/O on that database connection, or if the database entered [WAL mode]
8395
+** after the most recent I/O on the database connection.)^
8396
+** (Hint: Run "[PRAGMA application_id]" against a newly opened
82278397
** database connection in order to make it ready to use snapshots.)
82288398
**
82298399
** The [sqlite3_snapshot_open()] interface is only available when the
82308400
** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
82318401
*/
@@ -8246,10 +8416,37 @@
82468416
** The [sqlite3_snapshot_free()] interface is only available when the
82478417
** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
82488418
*/
82498419
SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
82508420
8421
+/*
8422
+** CAPI3REF: Compare the ages of two snapshot handles.
8423
+** EXPERIMENTAL
8424
+**
8425
+** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8426
+** of two valid snapshot handles.
8427
+**
8428
+** If the two snapshot handles are not associated with the same database
8429
+** file, the result of the comparison is undefined.
8430
+**
8431
+** Additionally, the result of the comparison is only valid if both of the
8432
+** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8433
+** last time the wal file was deleted. The wal file is deleted when the
8434
+** database is changed back to rollback mode or when the number of database
8435
+** clients drops to zero. If either snapshot handle was obtained before the
8436
+** wal file was last deleted, the value returned by this function
8437
+** is undefined.
8438
+**
8439
+** Otherwise, this API returns a negative value if P1 refers to an older
8440
+** snapshot than P2, zero if the two handles refer to the same database
8441
+** snapshot, and a positive value if P1 is a newer snapshot than P2.
8442
+*/
8443
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8444
+ sqlite3_snapshot *p1,
8445
+ sqlite3_snapshot *p2
8446
+);
8447
+
82518448
/*
82528449
** Undo the hack that converts floating point types to integer for
82538450
** builds on processors without floating point support.
82548451
*/
82558452
#ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8259,10 +8456,11 @@
82598456
#if 0
82608457
} /* End of the 'extern "C"' block */
82618458
#endif
82628459
#endif /* _SQLITE3_H_ */
82638460
8461
+/******** Begin file sqlite3rtree.h *********/
82648462
/*
82658463
** 2010 August 30
82668464
**
82678465
** The author disclaims copyright to this source code. In place of
82688466
** a legal notice, here is a blessing:
@@ -8376,10 +8574,1291 @@
83768574
} /* end of the 'extern "C"' block */
83778575
#endif
83788576
83798577
#endif /* ifndef _SQLITE3RTREE_H_ */
83808578
8579
+/******** End of sqlite3rtree.h *********/
8580
+/******** Begin file sqlite3session.h *********/
8581
+
8582
+#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8583
+#define __SQLITESESSION_H_ 1
8584
+
8585
+/*
8586
+** Make sure we can call this stuff from C++.
8587
+*/
8588
+#if 0
8589
+extern "C" {
8590
+#endif
8591
+
8592
+
8593
+/*
8594
+** CAPI3REF: Session Object Handle
8595
+*/
8596
+typedef struct sqlite3_session sqlite3_session;
8597
+
8598
+/*
8599
+** CAPI3REF: Changeset Iterator Handle
8600
+*/
8601
+typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8602
+
8603
+/*
8604
+** CAPI3REF: Create A New Session Object
8605
+**
8606
+** Create a new session object attached to database handle db. If successful,
8607
+** a pointer to the new object is written to *ppSession and SQLITE_OK is
8608
+** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8609
+** error code (e.g. SQLITE_NOMEM) is returned.
8610
+**
8611
+** It is possible to create multiple session objects attached to a single
8612
+** database handle.
8613
+**
8614
+** Session objects created using this function should be deleted using the
8615
+** [sqlite3session_delete()] function before the database handle that they
8616
+** are attached to is itself closed. If the database handle is closed before
8617
+** the session object is deleted, then the results of calling any session
8618
+** module function, including [sqlite3session_delete()] on the session object
8619
+** are undefined.
8620
+**
8621
+** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8622
+** is not possible for an application to register a pre-update hook on a
8623
+** database handle that has one or more session objects attached. Nor is
8624
+** it possible to create a session object attached to a database handle for
8625
+** which a pre-update hook is already defined. The results of attempting
8626
+** either of these things are undefined.
8627
+**
8628
+** The session object will be used to create changesets for tables in
8629
+** database zDb, where zDb is either "main", or "temp", or the name of an
8630
+** attached database. It is not an error if database zDb is not attached
8631
+** to the database when the session object is created.
8632
+*/
8633
+int sqlite3session_create(
8634
+ sqlite3 *db, /* Database handle */
8635
+ const char *zDb, /* Name of db (e.g. "main") */
8636
+ sqlite3_session **ppSession /* OUT: New session object */
8637
+);
8638
+
8639
+/*
8640
+** CAPI3REF: Delete A Session Object
8641
+**
8642
+** Delete a session object previously allocated using
8643
+** [sqlite3session_create()]. Once a session object has been deleted, the
8644
+** results of attempting to use pSession with any other session module
8645
+** function are undefined.
8646
+**
8647
+** Session objects must be deleted before the database handle to which they
8648
+** are attached is closed. Refer to the documentation for
8649
+** [sqlite3session_create()] for details.
8650
+*/
8651
+void sqlite3session_delete(sqlite3_session *pSession);
8652
+
8653
+
8654
+/*
8655
+** CAPI3REF: Enable Or Disable A Session Object
8656
+**
8657
+** Enable or disable the recording of changes by a session object. When
8658
+** enabled, a session object records changes made to the database. When
8659
+** disabled - it does not. A newly created session object is enabled.
8660
+** Refer to the documentation for [sqlite3session_changeset()] for further
8661
+** details regarding how enabling and disabling a session object affects
8662
+** the eventual changesets.
8663
+**
8664
+** Passing zero to this function disables the session. Passing a value
8665
+** greater than zero enables it. Passing a value less than zero is a
8666
+** no-op, and may be used to query the current state of the session.
8667
+**
8668
+** The return value indicates the final state of the session object: 0 if
8669
+** the session is disabled, or 1 if it is enabled.
8670
+*/
8671
+int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8672
+
8673
+/*
8674
+** CAPI3REF: Set Or Clear the Indirect Change Flag
8675
+**
8676
+** Each change recorded by a session object is marked as either direct or
8677
+** indirect. A change is marked as indirect if either:
8678
+**
8679
+** <ul>
8680
+** <li> The session object "indirect" flag is set when the change is
8681
+** made, or
8682
+** <li> The change is made by an SQL trigger or foreign key action
8683
+** instead of directly as a result of a users SQL statement.
8684
+** </ul>
8685
+**
8686
+** If a single row is affected by more than one operation within a session,
8687
+** then the change is considered indirect if all operations meet the criteria
8688
+** for an indirect change above, or direct otherwise.
8689
+**
8690
+** This function is used to set, clear or query the session object indirect
8691
+** flag. If the second argument passed to this function is zero, then the
8692
+** indirect flag is cleared. If it is greater than zero, the indirect flag
8693
+** is set. Passing a value less than zero does not modify the current value
8694
+** of the indirect flag, and may be used to query the current state of the
8695
+** indirect flag for the specified session object.
8696
+**
8697
+** The return value indicates the final state of the indirect flag: 0 if
8698
+** it is clear, or 1 if it is set.
8699
+*/
8700
+int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8701
+
8702
+/*
8703
+** CAPI3REF: Attach A Table To A Session Object
8704
+**
8705
+** If argument zTab is not NULL, then it is the name of a table to attach
8706
+** to the session object passed as the first argument. All subsequent changes
8707
+** made to the table while the session object is enabled will be recorded. See
8708
+** documentation for [sqlite3session_changeset()] for further details.
8709
+**
8710
+** Or, if argument zTab is NULL, then changes are recorded for all tables
8711
+** in the database. If additional tables are added to the database (by
8712
+** executing "CREATE TABLE" statements) after this call is made, changes for
8713
+** the new tables are also recorded.
8714
+**
8715
+** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8716
+** defined as part of their CREATE TABLE statement. It does not matter if the
8717
+** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8718
+** KEY may consist of a single column, or may be a composite key.
8719
+**
8720
+** It is not an error if the named table does not exist in the database. Nor
8721
+** is it an error if the named table does not have a PRIMARY KEY. However,
8722
+** no changes will be recorded in either of these scenarios.
8723
+**
8724
+** Changes are not recorded for individual rows that have NULL values stored
8725
+** in one or more of their PRIMARY KEY columns.
8726
+**
8727
+** SQLITE_OK is returned if the call completes without error. Or, if an error
8728
+** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8729
+*/
8730
+int sqlite3session_attach(
8731
+ sqlite3_session *pSession, /* Session object */
8732
+ const char *zTab /* Table name */
8733
+);
8734
+
8735
+/*
8736
+** CAPI3REF: Set a table filter on a Session Object.
8737
+**
8738
+** The second argument (xFilter) is the "filter callback". For changes to rows
8739
+** in tables that are not attached to the Session oject, the filter is called
8740
+** to determine whether changes to the table's rows should be tracked or not.
8741
+** If xFilter returns 0, changes is not tracked. Note that once a table is
8742
+** attached, xFilter will not be called again.
8743
+*/
8744
+void sqlite3session_table_filter(
8745
+ sqlite3_session *pSession, /* Session object */
8746
+ int(*xFilter)(
8747
+ void *pCtx, /* Copy of third arg to _filter_table() */
8748
+ const char *zTab /* Table name */
8749
+ ),
8750
+ void *pCtx /* First argument passed to xFilter */
8751
+);
8752
+
8753
+/*
8754
+** CAPI3REF: Generate A Changeset From A Session Object
8755
+**
8756
+** Obtain a changeset containing changes to the tables attached to the
8757
+** session object passed as the first argument. If successful,
8758
+** set *ppChangeset to point to a buffer containing the changeset
8759
+** and *pnChangeset to the size of the changeset in bytes before returning
8760
+** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8761
+** zero and return an SQLite error code.
8762
+**
8763
+** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8764
+** each representing a change to a single row of an attached table. An INSERT
8765
+** change contains the values of each field of a new database row. A DELETE
8766
+** contains the original values of each field of a deleted database row. An
8767
+** UPDATE change contains the original values of each field of an updated
8768
+** database row along with the updated values for each updated non-primary-key
8769
+** column. It is not possible for an UPDATE change to represent a change that
8770
+** modifies the values of primary key columns. If such a change is made, it
8771
+** is represented in a changeset as a DELETE followed by an INSERT.
8772
+**
8773
+** Changes are not recorded for rows that have NULL values stored in one or
8774
+** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8775
+** no corresponding change is present in the changesets returned by this
8776
+** function. If an existing row with one or more NULL values stored in
8777
+** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8778
+** only an INSERT is appears in the changeset. Similarly, if an existing row
8779
+** with non-NULL PRIMARY KEY values is updated so that one or more of its
8780
+** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8781
+** DELETE change only.
8782
+**
8783
+** The contents of a changeset may be traversed using an iterator created
8784
+** using the [sqlite3changeset_start()] API. A changeset may be applied to
8785
+** a database with a compatible schema using the [sqlite3changeset_apply()]
8786
+** API.
8787
+**
8788
+** Within a changeset generated by this function, all changes related to a
8789
+** single table are grouped together. In other words, when iterating through
8790
+** a changeset or when applying a changeset to a database, all changes related
8791
+** to a single table are processed before moving on to the next table. Tables
8792
+** are sorted in the same order in which they were attached (or auto-attached)
8793
+** to the sqlite3_session object. The order in which the changes related to
8794
+** a single table are stored is undefined.
8795
+**
8796
+** Following a successful call to this function, it is the responsibility of
8797
+** the caller to eventually free the buffer that *ppChangeset points to using
8798
+** [sqlite3_free()].
8799
+**
8800
+** <h3>Changeset Generation</h3>
8801
+**
8802
+** Once a table has been attached to a session object, the session object
8803
+** records the primary key values of all new rows inserted into the table.
8804
+** It also records the original primary key and other column values of any
8805
+** deleted or updated rows. For each unique primary key value, data is only
8806
+** recorded once - the first time a row with said primary key is inserted,
8807
+** updated or deleted in the lifetime of the session.
8808
+**
8809
+** There is one exception to the previous paragraph: when a row is inserted,
8810
+** updated or deleted, if one or more of its primary key columns contain a
8811
+** NULL value, no record of the change is made.
8812
+**
8813
+** The session object therefore accumulates two types of records - those
8814
+** that consist of primary key values only (created when the user inserts
8815
+** a new record) and those that consist of the primary key values and the
8816
+** original values of other table columns (created when the users deletes
8817
+** or updates a record).
8818
+**
8819
+** When this function is called, the requested changeset is created using
8820
+** both the accumulated records and the current contents of the database
8821
+** file. Specifically:
8822
+**
8823
+** <ul>
8824
+** <li> For each record generated by an insert, the database is queried
8825
+** for a row with a matching primary key. If one is found, an INSERT
8826
+** change is added to the changeset. If no such row is found, no change
8827
+** is added to the changeset.
8828
+**
8829
+** <li> For each record generated by an update or delete, the database is
8830
+** queried for a row with a matching primary key. If such a row is
8831
+** found and one or more of the non-primary key fields have been
8832
+** modified from their original values, an UPDATE change is added to
8833
+** the changeset. Or, if no such row is found in the table, a DELETE
8834
+** change is added to the changeset. If there is a row with a matching
8835
+** primary key in the database, but all fields contain their original
8836
+** values, no change is added to the changeset.
8837
+** </ul>
8838
+**
8839
+** This means, amongst other things, that if a row is inserted and then later
8840
+** deleted while a session object is active, neither the insert nor the delete
8841
+** will be present in the changeset. Or if a row is deleted and then later a
8842
+** row with the same primary key values inserted while a session object is
8843
+** active, the resulting changeset will contain an UPDATE change instead of
8844
+** a DELETE and an INSERT.
8845
+**
8846
+** When a session object is disabled (see the [sqlite3session_enable()] API),
8847
+** it does not accumulate records when rows are inserted, updated or deleted.
8848
+** This may appear to have some counter-intuitive effects if a single row
8849
+** is written to more than once during a session. For example, if a row
8850
+** is inserted while a session object is enabled, then later deleted while
8851
+** the same session object is disabled, no INSERT record will appear in the
8852
+** changeset, even though the delete took place while the session was disabled.
8853
+** Or, if one field of a row is updated while a session is disabled, and
8854
+** another field of the same row is updated while the session is enabled, the
8855
+** resulting changeset will contain an UPDATE change that updates both fields.
8856
+*/
8857
+int sqlite3session_changeset(
8858
+ sqlite3_session *pSession, /* Session object */
8859
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
8860
+ void **ppChangeset /* OUT: Buffer containing changeset */
8861
+);
8862
+
8863
+/*
8864
+** CAPI3REF: Load The Difference Between Tables Into A Session
8865
+**
8866
+** If it is not already attached to the session object passed as the first
8867
+** argument, this function attaches table zTbl in the same manner as the
8868
+** [sqlite3session_attach()] function. If zTbl does not exist, or if it
8869
+** does not have a primary key, this function is a no-op (but does not return
8870
+** an error).
8871
+**
8872
+** Argument zFromDb must be the name of a database ("main", "temp" etc.)
8873
+** attached to the same database handle as the session object that contains
8874
+** a table compatible with the table attached to the session by this function.
8875
+** A table is considered compatible if it:
8876
+**
8877
+** <ul>
8878
+** <li> Has the same name,
8879
+** <li> Has the same set of columns declared in the same order, and
8880
+** <li> Has the same PRIMARY KEY definition.
8881
+** </ul>
8882
+**
8883
+** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
8884
+** are compatible but do not have any PRIMARY KEY columns, it is not an error
8885
+** but no changes are added to the session object. As with other session
8886
+** APIs, tables without PRIMARY KEYs are simply ignored.
8887
+**
8888
+** This function adds a set of changes to the session object that could be
8889
+** used to update the table in database zFrom (call this the "from-table")
8890
+** so that its content is the same as the table attached to the session
8891
+** object (call this the "to-table"). Specifically:
8892
+**
8893
+** <ul>
8894
+** <li> For each row (primary key) that exists in the to-table but not in
8895
+** the from-table, an INSERT record is added to the session object.
8896
+**
8897
+** <li> For each row (primary key) that exists in the to-table but not in
8898
+** the from-table, a DELETE record is added to the session object.
8899
+**
8900
+** <li> For each row (primary key) that exists in both tables, but features
8901
+** different in each, an UPDATE record is added to the session.
8902
+** </ul>
8903
+**
8904
+** To clarify, if this function is called and then a changeset constructed
8905
+** using [sqlite3session_changeset()], then after applying that changeset to
8906
+** database zFrom the contents of the two compatible tables would be
8907
+** identical.
8908
+**
8909
+** It an error if database zFrom does not exist or does not contain the
8910
+** required compatible table.
8911
+**
8912
+** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
8913
+** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
8914
+** may be set to point to a buffer containing an English language error
8915
+** message. It is the responsibility of the caller to free this buffer using
8916
+** sqlite3_free().
8917
+*/
8918
+int sqlite3session_diff(
8919
+ sqlite3_session *pSession,
8920
+ const char *zFromDb,
8921
+ const char *zTbl,
8922
+ char **pzErrMsg
8923
+);
8924
+
8925
+
8926
+/*
8927
+** CAPI3REF: Generate A Patchset From A Session Object
8928
+**
8929
+** The differences between a patchset and a changeset are that:
8930
+**
8931
+** <ul>
8932
+** <li> DELETE records consist of the primary key fields only. The
8933
+** original values of other fields are omitted.
8934
+** <li> The original values of any modified fields are omitted from
8935
+** UPDATE records.
8936
+** </ul>
8937
+**
8938
+** A patchset blob may be used with up to date versions of all
8939
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
8940
+** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
8941
+** attempting to use a patchset blob with old versions of the
8942
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
8943
+**
8944
+** Because the non-primary key "old.*" fields are omitted, no
8945
+** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
8946
+** is passed to the sqlite3changeset_apply() API. Other conflict types work
8947
+** in the same way as for changesets.
8948
+**
8949
+** Changes within a patchset are ordered in the same way as for changesets
8950
+** generated by the sqlite3session_changeset() function (i.e. all changes for
8951
+** a single table are grouped together, tables appear in the order in which
8952
+** they were attached to the session object).
8953
+*/
8954
+int sqlite3session_patchset(
8955
+ sqlite3_session *pSession, /* Session object */
8956
+ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
8957
+ void **ppPatchset /* OUT: Buffer containing changeset */
8958
+);
8959
+
8960
+/*
8961
+** CAPI3REF: Test if a changeset has recorded any changes.
8962
+**
8963
+** Return non-zero if no changes to attached tables have been recorded by
8964
+** the session object passed as the first argument. Otherwise, if one or
8965
+** more changes have been recorded, return zero.
8966
+**
8967
+** Even if this function returns zero, it is possible that calling
8968
+** [sqlite3session_changeset()] on the session handle may still return a
8969
+** changeset that contains no changes. This can happen when a row in
8970
+** an attached table is modified and then later on the original values
8971
+** are restored. However, if this function returns non-zero, then it is
8972
+** guaranteed that a call to sqlite3session_changeset() will return a
8973
+** changeset containing zero changes.
8974
+*/
8975
+int sqlite3session_isempty(sqlite3_session *pSession);
8976
+
8977
+/*
8978
+** CAPI3REF: Create An Iterator To Traverse A Changeset
8979
+**
8980
+** Create an iterator used to iterate through the contents of a changeset.
8981
+** If successful, *pp is set to point to the iterator handle and SQLITE_OK
8982
+** is returned. Otherwise, if an error occurs, *pp is set to zero and an
8983
+** SQLite error code is returned.
8984
+**
8985
+** The following functions can be used to advance and query a changeset
8986
+** iterator created by this function:
8987
+**
8988
+** <ul>
8989
+** <li> [sqlite3changeset_next()]
8990
+** <li> [sqlite3changeset_op()]
8991
+** <li> [sqlite3changeset_new()]
8992
+** <li> [sqlite3changeset_old()]
8993
+** </ul>
8994
+**
8995
+** It is the responsibility of the caller to eventually destroy the iterator
8996
+** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
8997
+** changeset (pChangeset) must remain valid until after the iterator is
8998
+** destroyed.
8999
+**
9000
+** Assuming the changeset blob was created by one of the
9001
+** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9002
+** [sqlite3changeset_invert()] functions, all changes within the changeset
9003
+** that apply to a single table are grouped together. This means that when
9004
+** an application iterates through a changeset using an iterator created by
9005
+** this function, all changes that relate to a single table are visted
9006
+** consecutively. There is no chance that the iterator will visit a change
9007
+** the applies to table X, then one for table Y, and then later on visit
9008
+** another change for table X.
9009
+*/
9010
+int sqlite3changeset_start(
9011
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9012
+ int nChangeset, /* Size of changeset blob in bytes */
9013
+ void *pChangeset /* Pointer to blob containing changeset */
9014
+);
9015
+
9016
+
9017
+/*
9018
+** CAPI3REF: Advance A Changeset Iterator
9019
+**
9020
+** This function may only be used with iterators created by function
9021
+** [sqlite3changeset_start()]. If it is called on an iterator passed to
9022
+** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9023
+** is returned and the call has no effect.
9024
+**
9025
+** Immediately after an iterator is created by sqlite3changeset_start(), it
9026
+** does not point to any change in the changeset. Assuming the changeset
9027
+** is not empty, the first call to this function advances the iterator to
9028
+** point to the first change in the changeset. Each subsequent call advances
9029
+** the iterator to point to the next change in the changeset (if any). If
9030
+** no error occurs and the iterator points to a valid change after a call
9031
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9032
+** Otherwise, if all changes in the changeset have already been visited,
9033
+** SQLITE_DONE is returned.
9034
+**
9035
+** If an error occurs, an SQLite error code is returned. Possible error
9036
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9037
+** SQLITE_NOMEM.
9038
+*/
9039
+int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9040
+
9041
+/*
9042
+** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9043
+**
9044
+** The pIter argument passed to this function may either be an iterator
9045
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9046
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
9047
+** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9048
+** is not the case, this function returns [SQLITE_MISUSE].
9049
+**
9050
+** If argument pzTab is not NULL, then *pzTab is set to point to a
9051
+** nul-terminated utf-8 encoded string containing the name of the table
9052
+** affected by the current change. The buffer remains valid until either
9053
+** sqlite3changeset_next() is called on the iterator or until the
9054
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9055
+** set to the number of columns in the table affected by the change. If
9056
+** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9057
+** is an indirect change, or false (0) otherwise. See the documentation for
9058
+** [sqlite3session_indirect()] for a description of direct and indirect
9059
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9060
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9061
+** type of change that the iterator currently points to.
9062
+**
9063
+** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9064
+** SQLite error code is returned. The values of the output variables may not
9065
+** be trusted in this case.
9066
+*/
9067
+int sqlite3changeset_op(
9068
+ sqlite3_changeset_iter *pIter, /* Iterator object */
9069
+ const char **pzTab, /* OUT: Pointer to table name */
9070
+ int *pnCol, /* OUT: Number of columns in table */
9071
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9072
+ int *pbIndirect /* OUT: True for an 'indirect' change */
9073
+);
9074
+
9075
+/*
9076
+** CAPI3REF: Obtain The Primary Key Definition Of A Table
9077
+**
9078
+** For each modified table, a changeset includes the following:
9079
+**
9080
+** <ul>
9081
+** <li> The number of columns in the table, and
9082
+** <li> Which of those columns make up the tables PRIMARY KEY.
9083
+** </ul>
9084
+**
9085
+** This function is used to find which columns comprise the PRIMARY KEY of
9086
+** the table modified by the change that iterator pIter currently points to.
9087
+** If successful, *pabPK is set to point to an array of nCol entries, where
9088
+** nCol is the number of columns in the table. Elements of *pabPK are set to
9089
+** 0x01 if the corresponding column is part of the tables primary key, or
9090
+** 0x00 if it is not.
9091
+**
9092
+** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
9093
+** in the table.
9094
+**
9095
+** If this function is called when the iterator does not point to a valid
9096
+** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9097
+** SQLITE_OK is returned and the output variables populated as described
9098
+** above.
9099
+*/
9100
+int sqlite3changeset_pk(
9101
+ sqlite3_changeset_iter *pIter, /* Iterator object */
9102
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9103
+ int *pnCol /* OUT: Number of entries in output array */
9104
+);
9105
+
9106
+/*
9107
+** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9108
+**
9109
+** The pIter argument passed to this function may either be an iterator
9110
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9111
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
9112
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9113
+** Furthermore, it may only be called if the type of change that the iterator
9114
+** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9115
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9116
+**
9117
+** Argument iVal must be greater than or equal to 0, and less than the number
9118
+** of columns in the table affected by the current change. Otherwise,
9119
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9120
+**
9121
+** If successful, this function sets *ppValue to point to a protected
9122
+** sqlite3_value object containing the iVal'th value from the vector of
9123
+** original row values stored as part of the UPDATE or DELETE change and
9124
+** returns SQLITE_OK. The name of the function comes from the fact that this
9125
+** is similar to the "old.*" columns available to update or delete triggers.
9126
+**
9127
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
9128
+** is returned and *ppValue is set to NULL.
9129
+*/
9130
+int sqlite3changeset_old(
9131
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
9132
+ int iVal, /* Column number */
9133
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9134
+);
9135
+
9136
+/*
9137
+** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9138
+**
9139
+** The pIter argument passed to this function may either be an iterator
9140
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9141
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
9142
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9143
+** Furthermore, it may only be called if the type of change that the iterator
9144
+** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9145
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9146
+**
9147
+** Argument iVal must be greater than or equal to 0, and less than the number
9148
+** of columns in the table affected by the current change. Otherwise,
9149
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9150
+**
9151
+** If successful, this function sets *ppValue to point to a protected
9152
+** sqlite3_value object containing the iVal'th value from the vector of
9153
+** new row values stored as part of the UPDATE or INSERT change and
9154
+** returns SQLITE_OK. If the change is an UPDATE and does not include
9155
+** a new value for the requested column, *ppValue is set to NULL and
9156
+** SQLITE_OK returned. The name of the function comes from the fact that
9157
+** this is similar to the "new.*" columns available to update or delete
9158
+** triggers.
9159
+**
9160
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
9161
+** is returned and *ppValue is set to NULL.
9162
+*/
9163
+int sqlite3changeset_new(
9164
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
9165
+ int iVal, /* Column number */
9166
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9167
+);
9168
+
9169
+/*
9170
+** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9171
+**
9172
+** This function should only be used with iterator objects passed to a
9173
+** conflict-handler callback by [sqlite3changeset_apply()] with either
9174
+** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9175
+** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9176
+** is set to NULL.
9177
+**
9178
+** Argument iVal must be greater than or equal to 0, and less than the number
9179
+** of columns in the table affected by the current change. Otherwise,
9180
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9181
+**
9182
+** If successful, this function sets *ppValue to point to a protected
9183
+** sqlite3_value object containing the iVal'th value from the
9184
+** "conflicting row" associated with the current conflict-handler callback
9185
+** and returns SQLITE_OK.
9186
+**
9187
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
9188
+** is returned and *ppValue is set to NULL.
9189
+*/
9190
+int sqlite3changeset_conflict(
9191
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
9192
+ int iVal, /* Column number */
9193
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
9194
+);
9195
+
9196
+/*
9197
+** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9198
+**
9199
+** This function may only be called with an iterator passed to an
9200
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9201
+** it sets the output variable to the total number of known foreign key
9202
+** violations in the destination database and returns SQLITE_OK.
9203
+**
9204
+** In all other cases this function returns SQLITE_MISUSE.
9205
+*/
9206
+int sqlite3changeset_fk_conflicts(
9207
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
9208
+ int *pnOut /* OUT: Number of FK violations */
9209
+);
9210
+
9211
+
9212
+/*
9213
+** CAPI3REF: Finalize A Changeset Iterator
9214
+**
9215
+** This function is used to finalize an iterator allocated with
9216
+** [sqlite3changeset_start()].
9217
+**
9218
+** This function should only be called on iterators created using the
9219
+** [sqlite3changeset_start()] function. If an application calls this
9220
+** function with an iterator passed to a conflict-handler by
9221
+** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9222
+** call has no effect.
9223
+**
9224
+** If an error was encountered within a call to an sqlite3changeset_xxx()
9225
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9226
+** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9227
+** to that error is returned by this function. Otherwise, SQLITE_OK is
9228
+** returned. This is to allow the following pattern (pseudo-code):
9229
+**
9230
+** sqlite3changeset_start();
9231
+** while( SQLITE_ROW==sqlite3changeset_next() ){
9232
+** // Do something with change.
9233
+** }
9234
+** rc = sqlite3changeset_finalize();
9235
+** if( rc!=SQLITE_OK ){
9236
+** // An error has occurred
9237
+** }
9238
+*/
9239
+int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9240
+
9241
+/*
9242
+** CAPI3REF: Invert A Changeset
9243
+**
9244
+** This function is used to "invert" a changeset object. Applying an inverted
9245
+** changeset to a database reverses the effects of applying the uninverted
9246
+** changeset. Specifically:
9247
+**
9248
+** <ul>
9249
+** <li> Each DELETE change is changed to an INSERT, and
9250
+** <li> Each INSERT change is changed to a DELETE, and
9251
+** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9252
+** </ul>
9253
+**
9254
+** This function does not change the order in which changes appear within
9255
+** the changeset. It merely reverses the sense of each individual change.
9256
+**
9257
+** If successful, a pointer to a buffer containing the inverted changeset
9258
+** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9259
+** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9260
+** zeroed and an SQLite error code returned.
9261
+**
9262
+** It is the responsibility of the caller to eventually call sqlite3_free()
9263
+** on the *ppOut pointer to free the buffer allocation following a successful
9264
+** call to this function.
9265
+**
9266
+** WARNING/TODO: This function currently assumes that the input is a valid
9267
+** changeset. If it is not, the results are undefined.
9268
+*/
9269
+int sqlite3changeset_invert(
9270
+ int nIn, const void *pIn, /* Input changeset */
9271
+ int *pnOut, void **ppOut /* OUT: Inverse of input */
9272
+);
9273
+
9274
+/*
9275
+** CAPI3REF: Concatenate Two Changeset Objects
9276
+**
9277
+** This function is used to concatenate two changesets, A and B, into a
9278
+** single changeset. The result is a changeset equivalent to applying
9279
+** changeset A followed by changeset B.
9280
+**
9281
+** This function combines the two input changesets using an
9282
+** sqlite3_changegroup object. Calling it produces similar results as the
9283
+** following code fragment:
9284
+**
9285
+** sqlite3_changegroup *pGrp;
9286
+** rc = sqlite3_changegroup_new(&pGrp);
9287
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9288
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9289
+** if( rc==SQLITE_OK ){
9290
+** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9291
+** }else{
9292
+** *ppOut = 0;
9293
+** *pnOut = 0;
9294
+** }
9295
+**
9296
+** Refer to the sqlite3_changegroup documentation below for details.
9297
+*/
9298
+int sqlite3changeset_concat(
9299
+ int nA, /* Number of bytes in buffer pA */
9300
+ void *pA, /* Pointer to buffer containing changeset A */
9301
+ int nB, /* Number of bytes in buffer pB */
9302
+ void *pB, /* Pointer to buffer containing changeset B */
9303
+ int *pnOut, /* OUT: Number of bytes in output changeset */
9304
+ void **ppOut /* OUT: Buffer containing output changeset */
9305
+);
9306
+
9307
+
9308
+/*
9309
+** Changegroup handle.
9310
+*/
9311
+typedef struct sqlite3_changegroup sqlite3_changegroup;
9312
+
9313
+/*
9314
+** CAPI3REF: Combine two or more changesets into a single changeset.
9315
+**
9316
+** An sqlite3_changegroup object is used to combine two or more changesets
9317
+** (or patchsets) into a single changeset (or patchset). A single changegroup
9318
+** object may combine changesets or patchsets, but not both. The output is
9319
+** always in the same format as the input.
9320
+**
9321
+** If successful, this function returns SQLITE_OK and populates (*pp) with
9322
+** a pointer to a new sqlite3_changegroup object before returning. The caller
9323
+** should eventually free the returned object using a call to
9324
+** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9325
+** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9326
+**
9327
+** The usual usage pattern for an sqlite3_changegroup object is as follows:
9328
+**
9329
+** <ul>
9330
+** <li> It is created using a call to sqlite3changegroup_new().
9331
+**
9332
+** <li> Zero or more changesets (or patchsets) are added to the object
9333
+** by calling sqlite3changegroup_add().
9334
+**
9335
+** <li> The result of combining all input changesets together is obtained
9336
+** by the application via a call to sqlite3changegroup_output().
9337
+**
9338
+** <li> The object is deleted using a call to sqlite3changegroup_delete().
9339
+** </ul>
9340
+**
9341
+** Any number of calls to add() and output() may be made between the calls to
9342
+** new() and delete(), and in any order.
9343
+**
9344
+** As well as the regular sqlite3changegroup_add() and
9345
+** sqlite3changegroup_output() functions, also available are the streaming
9346
+** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9347
+*/
9348
+int sqlite3changegroup_new(sqlite3_changegroup **pp);
9349
+
9350
+/*
9351
+** Add all changes within the changeset (or patchset) in buffer pData (size
9352
+** nData bytes) to the changegroup.
9353
+**
9354
+** If the buffer contains a patchset, then all prior calls to this function
9355
+** on the same changegroup object must also have specified patchsets. Or, if
9356
+** the buffer contains a changeset, so must have the earlier calls to this
9357
+** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9358
+** to the changegroup.
9359
+**
9360
+** Rows within the changeset and changegroup are identified by the values in
9361
+** their PRIMARY KEY columns. A change in the changeset is considered to
9362
+** apply to the same row as a change already present in the changegroup if
9363
+** the two rows have the same primary key.
9364
+**
9365
+** Changes to rows that that do not already appear in the changegroup are
9366
+** simply copied into it. Or, if both the new changeset and the changegroup
9367
+** contain changes that apply to a single row, the final contents of the
9368
+** changegroup depends on the type of each change, as follows:
9369
+**
9370
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
9371
+** <tr><th style="white-space:pre">Existing Change </th>
9372
+** <th style="white-space:pre">New Change </th>
9373
+** <th>Output Change
9374
+** <tr><td>INSERT <td>INSERT <td>
9375
+** The new change is ignored. This case does not occur if the new
9376
+** changeset was recorded immediately after the changesets already
9377
+** added to the changegroup.
9378
+** <tr><td>INSERT <td>UPDATE <td>
9379
+** The INSERT change remains in the changegroup. The values in the
9380
+** INSERT change are modified as if the row was inserted by the
9381
+** existing change and then updated according to the new change.
9382
+** <tr><td>INSERT <td>DELETE <td>
9383
+** The existing INSERT is removed from the changegroup. The DELETE is
9384
+** not added.
9385
+** <tr><td>UPDATE <td>INSERT <td>
9386
+** The new change is ignored. This case does not occur if the new
9387
+** changeset was recorded immediately after the changesets already
9388
+** added to the changegroup.
9389
+** <tr><td>UPDATE <td>UPDATE <td>
9390
+** The existing UPDATE remains within the changegroup. It is amended
9391
+** so that the accompanying values are as if the row was updated once
9392
+** by the existing change and then again by the new change.
9393
+** <tr><td>UPDATE <td>DELETE <td>
9394
+** The existing UPDATE is replaced by the new DELETE within the
9395
+** changegroup.
9396
+** <tr><td>DELETE <td>INSERT <td>
9397
+** If one or more of the column values in the row inserted by the
9398
+** new change differ from those in the row deleted by the existing
9399
+** change, the existing DELETE is replaced by an UPDATE within the
9400
+** changegroup. Otherwise, if the inserted row is exactly the same
9401
+** as the deleted row, the existing DELETE is simply discarded.
9402
+** <tr><td>DELETE <td>UPDATE <td>
9403
+** The new change is ignored. This case does not occur if the new
9404
+** changeset was recorded immediately after the changesets already
9405
+** added to the changegroup.
9406
+** <tr><td>DELETE <td>DELETE <td>
9407
+** The new change is ignored. This case does not occur if the new
9408
+** changeset was recorded immediately after the changesets already
9409
+** added to the changegroup.
9410
+** </table>
9411
+**
9412
+** If the new changeset contains changes to a table that is already present
9413
+** in the changegroup, then the number of columns and the position of the
9414
+** primary key columns for the table must be consistent. If this is not the
9415
+** case, this function fails with SQLITE_SCHEMA. If the input changeset
9416
+** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9417
+** returned. Or, if an out-of-memory condition occurs during processing, this
9418
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9419
+** final contents of the changegroup is undefined.
9420
+**
9421
+** If no error occurs, SQLITE_OK is returned.
9422
+*/
9423
+int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9424
+
9425
+/*
9426
+** Obtain a buffer containing a changeset (or patchset) representing the
9427
+** current contents of the changegroup. If the inputs to the changegroup
9428
+** were themselves changesets, the output is a changeset. Or, if the
9429
+** inputs were patchsets, the output is also a patchset.
9430
+**
9431
+** As with the output of the sqlite3session_changeset() and
9432
+** sqlite3session_patchset() functions, all changes related to a single
9433
+** table are grouped together in the output of this function. Tables appear
9434
+** in the same order as for the very first changeset added to the changegroup.
9435
+** If the second or subsequent changesets added to the changegroup contain
9436
+** changes for tables that do not appear in the first changeset, they are
9437
+** appended onto the end of the output changeset, again in the order in
9438
+** which they are first encountered.
9439
+**
9440
+** If an error occurs, an SQLite error code is returned and the output
9441
+** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9442
+** is returned and the output variables are set to the size of and a
9443
+** pointer to the output buffer, respectively. In this case it is the
9444
+** responsibility of the caller to eventually free the buffer using a
9445
+** call to sqlite3_free().
9446
+*/
9447
+int sqlite3changegroup_output(
9448
+ sqlite3_changegroup*,
9449
+ int *pnData, /* OUT: Size of output buffer in bytes */
9450
+ void **ppData /* OUT: Pointer to output buffer */
9451
+);
9452
+
9453
+/*
9454
+** Delete a changegroup object.
9455
+*/
9456
+void sqlite3changegroup_delete(sqlite3_changegroup*);
9457
+
9458
+/*
9459
+** CAPI3REF: Apply A Changeset To A Database
9460
+**
9461
+** Apply a changeset to a database. This function attempts to update the
9462
+** "main" database attached to handle db with the changes found in the
9463
+** changeset passed via the second and third arguments.
9464
+**
9465
+** The fourth argument (xFilter) passed to this function is the "filter
9466
+** callback". If it is not NULL, then for each table affected by at least one
9467
+** change in the changeset, the filter callback is invoked with
9468
+** the table name as the second argument, and a copy of the context pointer
9469
+** passed as the sixth argument to this function as the first. If the "filter
9470
+** callback" returns zero, then no attempt is made to apply any changes to
9471
+** the table. Otherwise, if the return value is non-zero or the xFilter
9472
+** argument to this function is NULL, all changes related to the table are
9473
+** attempted.
9474
+**
9475
+** For each table that is not excluded by the filter callback, this function
9476
+** tests that the target database contains a compatible table. A table is
9477
+** considered compatible if all of the following are true:
9478
+**
9479
+** <ul>
9480
+** <li> The table has the same name as the name recorded in the
9481
+** changeset, and
9482
+** <li> The table has the same number of columns as recorded in the
9483
+** changeset, and
9484
+** <li> The table has primary key columns in the same position as
9485
+** recorded in the changeset.
9486
+** </ul>
9487
+**
9488
+** If there is no compatible table, it is not an error, but none of the
9489
+** changes associated with the table are applied. A warning message is issued
9490
+** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9491
+** one such warning is issued for each table in the changeset.
9492
+**
9493
+** For each change for which there is a compatible table, an attempt is made
9494
+** to modify the table contents according to the UPDATE, INSERT or DELETE
9495
+** change. If a change cannot be applied cleanly, the conflict handler
9496
+** function passed as the fifth argument to sqlite3changeset_apply() may be
9497
+** invoked. A description of exactly when the conflict handler is invoked for
9498
+** each type of change is below.
9499
+**
9500
+** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9501
+** of passing anything other than a valid function pointer as the xConflict
9502
+** argument are undefined.
9503
+**
9504
+** Each time the conflict handler function is invoked, it must return one
9505
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9506
+** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9507
+** if the second argument passed to the conflict handler is either
9508
+** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9509
+** returns an illegal value, any changes already made are rolled back and
9510
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9511
+** actions are taken by sqlite3changeset_apply() depending on the value
9512
+** returned by each invocation of the conflict-handler function. Refer to
9513
+** the documentation for the three
9514
+** [SQLITE_CHANGESET_OMIT|available return values] for details.
9515
+**
9516
+** <dl>
9517
+** <dt>DELETE Changes<dd>
9518
+** For each DELETE change, this function checks if the target database
9519
+** contains a row with the same primary key value (or values) as the
9520
+** original row values stored in the changeset. If it does, and the values
9521
+** stored in all non-primary key columns also match the values stored in
9522
+** the changeset the row is deleted from the target database.
9523
+**
9524
+** If a row with matching primary key values is found, but one or more of
9525
+** the non-primary key fields contains a value different from the original
9526
+** row value stored in the changeset, the conflict-handler function is
9527
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9528
+**
9529
+** If no row with matching primary key values is found in the database,
9530
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9531
+** passed as the second argument.
9532
+**
9533
+** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9534
+** (which can only happen if a foreign key constraint is violated), the
9535
+** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9536
+** passed as the second argument. This includes the case where the DELETE
9537
+** operation is attempted because an earlier call to the conflict handler
9538
+** function returned [SQLITE_CHANGESET_REPLACE].
9539
+**
9540
+** <dt>INSERT Changes<dd>
9541
+** For each INSERT change, an attempt is made to insert the new row into
9542
+** the database.
9543
+**
9544
+** If the attempt to insert the row fails because the database already
9545
+** contains a row with the same primary key values, the conflict handler
9546
+** function is invoked with the second argument set to
9547
+** [SQLITE_CHANGESET_CONFLICT].
9548
+**
9549
+** If the attempt to insert the row fails because of some other constraint
9550
+** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9551
+** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9552
+** This includes the case where the INSERT operation is re-attempted because
9553
+** an earlier call to the conflict handler function returned
9554
+** [SQLITE_CHANGESET_REPLACE].
9555
+**
9556
+** <dt>UPDATE Changes<dd>
9557
+** For each UPDATE change, this function checks if the target database
9558
+** contains a row with the same primary key value (or values) as the
9559
+** original row values stored in the changeset. If it does, and the values
9560
+** stored in all non-primary key columns also match the values stored in
9561
+** the changeset the row is updated within the target database.
9562
+**
9563
+** If a row with matching primary key values is found, but one or more of
9564
+** the non-primary key fields contains a value different from an original
9565
+** row value stored in the changeset, the conflict-handler function is
9566
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9567
+** UPDATE changes only contain values for non-primary key fields that are
9568
+** to be modified, only those fields need to match the original values to
9569
+** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9570
+**
9571
+** If no row with matching primary key values is found in the database,
9572
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9573
+** passed as the second argument.
9574
+**
9575
+** If the UPDATE operation is attempted, but SQLite returns
9576
+** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9577
+** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9578
+** This includes the case where the UPDATE operation is attempted after
9579
+** an earlier call to the conflict handler function returned
9580
+** [SQLITE_CHANGESET_REPLACE].
9581
+** </dl>
9582
+**
9583
+** It is safe to execute SQL statements, including those that write to the
9584
+** table that the callback related to, from within the xConflict callback.
9585
+** This can be used to further customize the applications conflict
9586
+** resolution strategy.
9587
+**
9588
+** All changes made by this function are enclosed in a savepoint transaction.
9589
+** If any other error (aside from a constraint failure when attempting to
9590
+** write to the target database) occurs, then the savepoint transaction is
9591
+** rolled back, restoring the target database to its original state, and an
9592
+** SQLite error code returned.
9593
+*/
9594
+int sqlite3changeset_apply(
9595
+ sqlite3 *db, /* Apply change to "main" db of this handle */
9596
+ int nChangeset, /* Size of changeset in bytes */
9597
+ void *pChangeset, /* Changeset blob */
9598
+ int(*xFilter)(
9599
+ void *pCtx, /* Copy of sixth arg to _apply() */
9600
+ const char *zTab /* Table name */
9601
+ ),
9602
+ int(*xConflict)(
9603
+ void *pCtx, /* Copy of sixth arg to _apply() */
9604
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9605
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
9606
+ ),
9607
+ void *pCtx /* First argument passed to xConflict */
9608
+);
9609
+
9610
+/*
9611
+** CAPI3REF: Constants Passed To The Conflict Handler
9612
+**
9613
+** Values that may be passed as the second argument to a conflict-handler.
9614
+**
9615
+** <dl>
9616
+** <dt>SQLITE_CHANGESET_DATA<dd>
9617
+** The conflict handler is invoked with CHANGESET_DATA as the second argument
9618
+** when processing a DELETE or UPDATE change if a row with the required
9619
+** PRIMARY KEY fields is present in the database, but one or more other
9620
+** (non primary-key) fields modified by the update do not contain the
9621
+** expected "before" values.
9622
+**
9623
+** The conflicting row, in this case, is the database row with the matching
9624
+** primary key.
9625
+**
9626
+** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9627
+** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9628
+** argument when processing a DELETE or UPDATE change if a row with the
9629
+** required PRIMARY KEY fields is not present in the database.
9630
+**
9631
+** There is no conflicting row in this case. The results of invoking the
9632
+** sqlite3changeset_conflict() API are undefined.
9633
+**
9634
+** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9635
+** CHANGESET_CONFLICT is passed as the second argument to the conflict
9636
+** handler while processing an INSERT change if the operation would result
9637
+** in duplicate primary key values.
9638
+**
9639
+** The conflicting row in this case is the database row with the matching
9640
+** primary key.
9641
+**
9642
+** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9643
+** If foreign key handling is enabled, and applying a changeset leaves the
9644
+** database in a state containing foreign key violations, the conflict
9645
+** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9646
+** exactly once before the changeset is committed. If the conflict handler
9647
+** returns CHANGESET_OMIT, the changes, including those that caused the
9648
+** foreign key constraint violation, are committed. Or, if it returns
9649
+** CHANGESET_ABORT, the changeset is rolled back.
9650
+**
9651
+** No current or conflicting row information is provided. The only function
9652
+** it is possible to call on the supplied sqlite3_changeset_iter handle
9653
+** is sqlite3changeset_fk_conflicts().
9654
+**
9655
+** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9656
+** If any other constraint violation occurs while applying a change (i.e.
9657
+** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9658
+** invoked with CHANGESET_CONSTRAINT as the second argument.
9659
+**
9660
+** There is no conflicting row in this case. The results of invoking the
9661
+** sqlite3changeset_conflict() API are undefined.
9662
+**
9663
+** </dl>
9664
+*/
9665
+#define SQLITE_CHANGESET_DATA 1
9666
+#define SQLITE_CHANGESET_NOTFOUND 2
9667
+#define SQLITE_CHANGESET_CONFLICT 3
9668
+#define SQLITE_CHANGESET_CONSTRAINT 4
9669
+#define SQLITE_CHANGESET_FOREIGN_KEY 5
9670
+
9671
+/*
9672
+** CAPI3REF: Constants Returned By The Conflict Handler
9673
+**
9674
+** A conflict handler callback must return one of the following three values.
9675
+**
9676
+** <dl>
9677
+** <dt>SQLITE_CHANGESET_OMIT<dd>
9678
+** If a conflict handler returns this value no special action is taken. The
9679
+** change that caused the conflict is not applied. The session module
9680
+** continues to the next change in the changeset.
9681
+**
9682
+** <dt>SQLITE_CHANGESET_REPLACE<dd>
9683
+** This value may only be returned if the second argument to the conflict
9684
+** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9685
+** is not the case, any changes applied so far are rolled back and the
9686
+** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9687
+**
9688
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9689
+** handler, then the conflicting row is either updated or deleted, depending
9690
+** on the type of change.
9691
+**
9692
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9693
+** handler, then the conflicting row is removed from the database and a
9694
+** second attempt to apply the change is made. If this second attempt fails,
9695
+** the original row is restored to the database before continuing.
9696
+**
9697
+** <dt>SQLITE_CHANGESET_ABORT<dd>
9698
+** If this value is returned, any changes applied so far are rolled back
9699
+** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9700
+** </dl>
9701
+*/
9702
+#define SQLITE_CHANGESET_OMIT 0
9703
+#define SQLITE_CHANGESET_REPLACE 1
9704
+#define SQLITE_CHANGESET_ABORT 2
9705
+
9706
+/*
9707
+** CAPI3REF: Streaming Versions of API functions.
9708
+**
9709
+** The six streaming API xxx_strm() functions serve similar purposes to the
9710
+** corresponding non-streaming API functions:
9711
+**
9712
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
9713
+** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9714
+** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9715
+** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9716
+** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9717
+** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9718
+** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9719
+** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9720
+** </table>
9721
+**
9722
+** Non-streaming functions that accept changesets (or patchsets) as input
9723
+** require that the entire changeset be stored in a single buffer in memory.
9724
+** Similarly, those that return a changeset or patchset do so by returning
9725
+** a pointer to a single large buffer allocated using sqlite3_malloc().
9726
+** Normally this is convenient. However, if an application running in a
9727
+** low-memory environment is required to handle very large changesets, the
9728
+** large contiguous memory allocations required can become onerous.
9729
+**
9730
+** In order to avoid this problem, instead of a single large buffer, input
9731
+** is passed to a streaming API functions by way of a callback function that
9732
+** the sessions module invokes to incrementally request input data as it is
9733
+** required. In all cases, a pair of API function parameters such as
9734
+**
9735
+** <pre>
9736
+** &nbsp; int nChangeset,
9737
+** &nbsp; void *pChangeset,
9738
+** </pre>
9739
+**
9740
+** Is replaced by:
9741
+**
9742
+** <pre>
9743
+** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9744
+** &nbsp; void *pIn,
9745
+** </pre>
9746
+**
9747
+** Each time the xInput callback is invoked by the sessions module, the first
9748
+** argument passed is a copy of the supplied pIn context pointer. The second
9749
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9750
+** error occurs the xInput method should copy up to (*pnData) bytes of data
9751
+** into the buffer and set (*pnData) to the actual number of bytes copied
9752
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9753
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9754
+** error code should be returned. In all cases, if an xInput callback returns
9755
+** an error, all processing is abandoned and the streaming API function
9756
+** returns a copy of the error code to the caller.
9757
+**
9758
+** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9759
+** invoked by the sessions module at any point during the lifetime of the
9760
+** iterator. If such an xInput callback returns an error, the iterator enters
9761
+** an error state, whereby all subsequent calls to iterator functions
9762
+** immediately fail with the same error code as returned by xInput.
9763
+**
9764
+** Similarly, streaming API functions that return changesets (or patchsets)
9765
+** return them in chunks by way of a callback function instead of via a
9766
+** pointer to a single large buffer. In this case, a pair of parameters such
9767
+** as:
9768
+**
9769
+** <pre>
9770
+** &nbsp; int *pnChangeset,
9771
+** &nbsp; void **ppChangeset,
9772
+** </pre>
9773
+**
9774
+** Is replaced by:
9775
+**
9776
+** <pre>
9777
+** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9778
+** &nbsp; void *pOut
9779
+** </pre>
9780
+**
9781
+** The xOutput callback is invoked zero or more times to return data to
9782
+** the application. The first parameter passed to each call is a copy of the
9783
+** pOut pointer supplied by the application. The second parameter, pData,
9784
+** points to a buffer nData bytes in size containing the chunk of output
9785
+** data being returned. If the xOutput callback successfully processes the
9786
+** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9787
+** it should return some other SQLite error code. In this case processing
9788
+** is immediately abandoned and the streaming API function returns a copy
9789
+** of the xOutput error code to the application.
9790
+**
9791
+** The sessions module never invokes an xOutput callback with the third
9792
+** parameter set to a value less than or equal to zero. Other than this,
9793
+** no guarantees are made as to the size of the chunks of data returned.
9794
+*/
9795
+int sqlite3changeset_apply_strm(
9796
+ sqlite3 *db, /* Apply change to "main" db of this handle */
9797
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9798
+ void *pIn, /* First arg for xInput */
9799
+ int(*xFilter)(
9800
+ void *pCtx, /* Copy of sixth arg to _apply() */
9801
+ const char *zTab /* Table name */
9802
+ ),
9803
+ int(*xConflict)(
9804
+ void *pCtx, /* Copy of sixth arg to _apply() */
9805
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9806
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
9807
+ ),
9808
+ void *pCtx /* First argument passed to xConflict */
9809
+);
9810
+int sqlite3changeset_concat_strm(
9811
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
9812
+ void *pInA,
9813
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
9814
+ void *pInB,
9815
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9816
+ void *pOut
9817
+);
9818
+int sqlite3changeset_invert_strm(
9819
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9820
+ void *pIn,
9821
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9822
+ void *pOut
9823
+);
9824
+int sqlite3changeset_start_strm(
9825
+ sqlite3_changeset_iter **pp,
9826
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9827
+ void *pIn
9828
+);
9829
+int sqlite3session_changeset_strm(
9830
+ sqlite3_session *pSession,
9831
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9832
+ void *pOut
9833
+);
9834
+int sqlite3session_patchset_strm(
9835
+ sqlite3_session *pSession,
9836
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9837
+ void *pOut
9838
+);
9839
+int sqlite3changegroup_add_strm(sqlite3_changegroup*,
9840
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9841
+ void *pIn
9842
+);
9843
+int sqlite3changegroup_output_strm(sqlite3_changegroup*,
9844
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9845
+ void *pOut
9846
+);
9847
+
9848
+
9849
+/*
9850
+** Make sure we can call this stuff from C++.
9851
+*/
9852
+#if 0
9853
+}
9854
+#endif
9855
+
9856
+#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
9857
+
9858
+/******** End of sqlite3session.h *********/
9859
+/******** Begin file fts5.h *********/
83819860
/*
83829861
** 2014 May 31
83839862
**
83849863
** The author disclaims copyright to this source code. In place of
83859864
** a legal notice, here is a blessing:
@@ -8520,15 +9999,17 @@
85209999
** of the current query. Specifically, a query equivalent to:
852110000
**
852210001
** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
852310002
**
852410003
** with $p set to a phrase equivalent to the phrase iPhrase of the
8525
-** current query is executed. For each row visited, the callback function
8526
-** passed as the fourth argument is invoked. The context and API objects
8527
-** passed to the callback function may be used to access the properties of
8528
-** each matched row. Invoking Api.xUserData() returns a copy of the pointer
8529
-** passed as the third argument to pUserData.
10004
+** current query is executed. Any column filter that applies to
10005
+** phrase iPhrase of the current query is included in $p. For each
10006
+** row visited, the callback function passed as the fourth argument
10007
+** is invoked. The context and API objects passed to the callback
10008
+** function may be used to access the properties of each matched row.
10009
+** Invoking Api.xUserData() returns a copy of the pointer passed as
10010
+** the third argument to pUserData.
853010011
**
853110012
** If the callback function returns any value other than SQLITE_OK, the
853210013
** query is abandoned and the xQueryPhrase function returns immediately.
853310014
** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
853410015
** Otherwise, the error code is propagated upwards.
@@ -8954,10 +10435,11 @@
895410435
#endif
895510436
895610437
#endif /* _FTS5_H */
895710438
895810439
10440
+/******** End of fts5.h *********/
895910441
896010442
/************** End of sqlite3.h *********************************************/
896110443
/************** Continuing where we left off in sqliteInt.h ******************/
896210444
896310445
/*
@@ -9435,11 +10917,11 @@
943510917
**
943610918
** When doing coverage testing ALWAYS and NEVER are hard-coded to
943710919
** be true and false so that the unreachable code they specify will
943810920
** not be counted as untested code.
943910921
*/
9440
-#if defined(SQLITE_COVERAGE_TEST)
10922
+#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
944110923
# define ALWAYS(X) (1)
944210924
# define NEVER(X) (0)
944310925
#elif !defined(NDEBUG)
944410926
# define ALWAYS(X) ((X)?1:(assert(0),0))
944510927
# define NEVER(X) ((X)?(assert(0),1):0)
@@ -9640,80 +11122,80 @@
964011122
#define TK_LP 22
964111123
#define TK_RP 23
964211124
#define TK_AS 24
964311125
#define TK_WITHOUT 25
964411126
#define TK_COMMA 26
9645
-#define TK_ID 27
9646
-#define TK_INDEXED 28
9647
-#define TK_ABORT 29
9648
-#define TK_ACTION 30
9649
-#define TK_AFTER 31
9650
-#define TK_ANALYZE 32
9651
-#define TK_ASC 33
9652
-#define TK_ATTACH 34
9653
-#define TK_BEFORE 35
9654
-#define TK_BY 36
9655
-#define TK_CASCADE 37
9656
-#define TK_CAST 38
9657
-#define TK_COLUMNKW 39
9658
-#define TK_CONFLICT 40
9659
-#define TK_DATABASE 41
9660
-#define TK_DESC 42
9661
-#define TK_DETACH 43
9662
-#define TK_EACH 44
9663
-#define TK_FAIL 45
9664
-#define TK_FOR 46
9665
-#define TK_IGNORE 47
9666
-#define TK_INITIALLY 48
9667
-#define TK_INSTEAD 49
9668
-#define TK_LIKE_KW 50
9669
-#define TK_MATCH 51
9670
-#define TK_NO 52
9671
-#define TK_KEY 53
9672
-#define TK_OF 54
9673
-#define TK_OFFSET 55
9674
-#define TK_PRAGMA 56
9675
-#define TK_RAISE 57
9676
-#define TK_RECURSIVE 58
9677
-#define TK_REPLACE 59
9678
-#define TK_RESTRICT 60
9679
-#define TK_ROW 61
9680
-#define TK_TRIGGER 62
9681
-#define TK_VACUUM 63
9682
-#define TK_VIEW 64
9683
-#define TK_VIRTUAL 65
9684
-#define TK_WITH 66
9685
-#define TK_REINDEX 67
9686
-#define TK_RENAME 68
9687
-#define TK_CTIME_KW 69
9688
-#define TK_ANY 70
9689
-#define TK_OR 71
9690
-#define TK_AND 72
9691
-#define TK_IS 73
9692
-#define TK_BETWEEN 74
9693
-#define TK_IN 75
9694
-#define TK_ISNULL 76
9695
-#define TK_NOTNULL 77
9696
-#define TK_NE 78
9697
-#define TK_EQ 79
9698
-#define TK_GT 80
9699
-#define TK_LE 81
9700
-#define TK_LT 82
9701
-#define TK_GE 83
9702
-#define TK_ESCAPE 84
9703
-#define TK_BITAND 85
9704
-#define TK_BITOR 86
9705
-#define TK_LSHIFT 87
9706
-#define TK_RSHIFT 88
9707
-#define TK_PLUS 89
9708
-#define TK_MINUS 90
9709
-#define TK_STAR 91
9710
-#define TK_SLASH 92
9711
-#define TK_REM 93
9712
-#define TK_CONCAT 94
9713
-#define TK_COLLATE 95
9714
-#define TK_BITNOT 96
11127
+#define TK_OR 27
11128
+#define TK_AND 28
11129
+#define TK_IS 29
11130
+#define TK_MATCH 30
11131
+#define TK_LIKE_KW 31
11132
+#define TK_BETWEEN 32
11133
+#define TK_IN 33
11134
+#define TK_ISNULL 34
11135
+#define TK_NOTNULL 35
11136
+#define TK_NE 36
11137
+#define TK_EQ 37
11138
+#define TK_GT 38
11139
+#define TK_LE 39
11140
+#define TK_LT 40
11141
+#define TK_GE 41
11142
+#define TK_ESCAPE 42
11143
+#define TK_BITAND 43
11144
+#define TK_BITOR 44
11145
+#define TK_LSHIFT 45
11146
+#define TK_RSHIFT 46
11147
+#define TK_PLUS 47
11148
+#define TK_MINUS 48
11149
+#define TK_STAR 49
11150
+#define TK_SLASH 50
11151
+#define TK_REM 51
11152
+#define TK_CONCAT 52
11153
+#define TK_COLLATE 53
11154
+#define TK_BITNOT 54
11155
+#define TK_ID 55
11156
+#define TK_INDEXED 56
11157
+#define TK_ABORT 57
11158
+#define TK_ACTION 58
11159
+#define TK_AFTER 59
11160
+#define TK_ANALYZE 60
11161
+#define TK_ASC 61
11162
+#define TK_ATTACH 62
11163
+#define TK_BEFORE 63
11164
+#define TK_BY 64
11165
+#define TK_CASCADE 65
11166
+#define TK_CAST 66
11167
+#define TK_COLUMNKW 67
11168
+#define TK_CONFLICT 68
11169
+#define TK_DATABASE 69
11170
+#define TK_DESC 70
11171
+#define TK_DETACH 71
11172
+#define TK_EACH 72
11173
+#define TK_FAIL 73
11174
+#define TK_FOR 74
11175
+#define TK_IGNORE 75
11176
+#define TK_INITIALLY 76
11177
+#define TK_INSTEAD 77
11178
+#define TK_NO 78
11179
+#define TK_KEY 79
11180
+#define TK_OF 80
11181
+#define TK_OFFSET 81
11182
+#define TK_PRAGMA 82
11183
+#define TK_RAISE 83
11184
+#define TK_RECURSIVE 84
11185
+#define TK_REPLACE 85
11186
+#define TK_RESTRICT 86
11187
+#define TK_ROW 87
11188
+#define TK_TRIGGER 88
11189
+#define TK_VACUUM 89
11190
+#define TK_VIEW 90
11191
+#define TK_VIRTUAL 91
11192
+#define TK_WITH 92
11193
+#define TK_REINDEX 93
11194
+#define TK_RENAME 94
11195
+#define TK_CTIME_KW 95
11196
+#define TK_ANY 96
971511197
#define TK_STRING 97
971611198
#define TK_JOIN_KW 98
971711199
#define TK_CONSTRAINT 99
971811200
#define TK_DEFAULT 100
971911201
#define TK_NULL 101
@@ -10311,10 +11793,11 @@
1031111793
typedef struct Lookaside Lookaside;
1031211794
typedef struct LookasideSlot LookasideSlot;
1031311795
typedef struct Module Module;
1031411796
typedef struct NameContext NameContext;
1031511797
typedef struct Parse Parse;
11798
+typedef struct PreUpdate PreUpdate;
1031611799
typedef struct PrintfArguments PrintfArguments;
1031711800
typedef struct RowSet RowSet;
1031811801
typedef struct Savepoint Savepoint;
1031911802
typedef struct Select Select;
1032011803
typedef struct SQLiteThread SQLiteThread;
@@ -10723,11 +12206,11 @@
1072312206
** as an instance of the following structure:
1072412207
*/
1072512208
struct VdbeOp {
1072612209
u8 opcode; /* What operation to perform */
1072712210
signed char p4type; /* One of the P4_xxx constants for p4 */
10728
- u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
12211
+ u8 notUsed1;
1072912212
u8 p5; /* Fifth parameter is an unsigned character */
1073012213
int p1; /* First operand */
1073112214
int p2; /* Second parameter (often the jump destination) */
1073212215
int p3; /* The third parameter */
1073312216
union p4union { /* fourth parameter */
@@ -10742,10 +12225,11 @@
1074212225
Mem *pMem; /* Used when p4type is P4_MEM */
1074312226
VTable *pVtab; /* Used when p4type is P4_VTAB */
1074412227
KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
1074512228
int *ai; /* Used when p4type is P4_INTARRAY */
1074612229
SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12230
+ Table *pTab; /* Used when p4type is P4_TABLE */
1074712231
#ifdef SQLITE_ENABLE_CURSOR_HINTS
1074812232
Expr *pExpr; /* Used when p4type is P4_EXPR */
1074912233
#endif
1075012234
int (*xAdvance)(BtCursor *, int *);
1075112235
} p4;
@@ -10806,11 +12290,12 @@
1080612290
#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
1080712291
#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
1080812292
#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
1080912293
#define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
1081012294
#define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
10811
-#define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
12295
+#define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12296
+#define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
1081212297
1081312298
/* Error message codes for OP_Halt */
1081412299
#define P5_ConstraintNotNull 1
1081512300
#define P5_ConstraintUnique 2
1081612301
#define P5_ConstraintCheck 3
@@ -10864,157 +12349,156 @@
1086412349
#define OP_Vacuum 10
1086512350
#define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
1086612351
#define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
1086712352
#define OP_Goto 13
1086812353
#define OP_Gosub 14
10869
-#define OP_Return 15
10870
-#define OP_InitCoroutine 16
10871
-#define OP_EndCoroutine 17
10872
-#define OP_Yield 18
12354
+#define OP_InitCoroutine 15
12355
+#define OP_Yield 16
12356
+#define OP_MustBeInt 17
12357
+#define OP_Jump 18
1087312358
#define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
10874
-#define OP_HaltIfNull 20 /* synopsis: if r[P3]=null halt */
10875
-#define OP_Halt 21
10876
-#define OP_Integer 22 /* synopsis: r[P2]=P1 */
10877
-#define OP_Int64 23 /* synopsis: r[P2]=P4 */
10878
-#define OP_String 24 /* synopsis: r[P2]='P4' (len=P1) */
10879
-#define OP_Null 25 /* synopsis: r[P2..P3]=NULL */
10880
-#define OP_SoftNull 26 /* synopsis: r[P1]=NULL */
10881
-#define OP_Blob 27 /* synopsis: r[P2]=P4 (len=P1) */
10882
-#define OP_Variable 28 /* synopsis: r[P2]=parameter(P1,P4) */
10883
-#define OP_Move 29 /* synopsis: r[P2@P3]=r[P1@P3] */
10884
-#define OP_Copy 30 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
10885
-#define OP_SCopy 31 /* synopsis: r[P2]=r[P1] */
10886
-#define OP_IntCopy 32 /* synopsis: r[P2]=r[P1] */
10887
-#define OP_ResultRow 33 /* synopsis: output=r[P1@P2] */
10888
-#define OP_CollSeq 34
10889
-#define OP_Function0 35 /* synopsis: r[P3]=func(r[P2@P5]) */
10890
-#define OP_Function 36 /* synopsis: r[P3]=func(r[P2@P5]) */
10891
-#define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
10892
-#define OP_MustBeInt 38
10893
-#define OP_RealAffinity 39
10894
-#define OP_Cast 40 /* synopsis: affinity(r[P1]) */
10895
-#define OP_Permutation 41
10896
-#define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
10897
-#define OP_Jump 43
10898
-#define OP_Once 44
10899
-#define OP_If 45
10900
-#define OP_IfNot 46
10901
-#define OP_Column 47 /* synopsis: r[P3]=PX */
10902
-#define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
10903
-#define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
10904
-#define OP_Count 50 /* synopsis: r[P2]=count() */
10905
-#define OP_ReadCookie 51
10906
-#define OP_SetCookie 52
10907
-#define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
10908
-#define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
10909
-#define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
10910
-#define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
10911
-#define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
10912
-#define OP_SorterOpen 58
10913
-#define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
10914
-#define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
10915
-#define OP_Close 61
10916
-#define OP_ColumnsUsed 62
10917
-#define OP_SeekLT 63 /* synopsis: key=r[P3@P4] */
10918
-#define OP_SeekLE 64 /* synopsis: key=r[P3@P4] */
10919
-#define OP_SeekGE 65 /* synopsis: key=r[P3@P4] */
10920
-#define OP_SeekGT 66 /* synopsis: key=r[P3@P4] */
10921
-#define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
10922
-#define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
10923
-#define OP_Found 69 /* synopsis: key=r[P3@P4] */
10924
-#define OP_NotExists 70 /* synopsis: intkey=r[P3] */
10925
-#define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
10926
-#define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
10927
-#define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
10928
-#define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
10929
-#define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
10930
-#define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
10931
-#define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
10932
-#define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
10933
-#define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
10934
-#define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
10935
-#define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
10936
-#define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
10937
-#define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
10938
-#define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
10939
-#define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
10940
-#define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
10941
-#define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
10942
-#define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
10943
-#define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
10944
-#define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
10945
-#define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
10946
-#define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
10947
-#define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
10948
-#define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
10949
-#define OP_Delete 95
10950
-#define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12359
+#define OP_Once 20
12360
+#define OP_If 21
12361
+#define OP_IfNot 22
12362
+#define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12363
+#define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12364
+#define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12365
+#define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12366
+#define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12367
+#define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12368
+#define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12369
+#define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12370
+#define OP_Found 31 /* synopsis: key=r[P3@P4] */
12371
+#define OP_NotExists 32 /* synopsis: intkey=r[P3] */
12372
+#define OP_Last 33
12373
+#define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12374
+#define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12375
+#define OP_Ne 36 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
12376
+#define OP_Eq 37 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
12377
+#define OP_Gt 38 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
12378
+#define OP_Le 39 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
12379
+#define OP_Lt 40 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
12380
+#define OP_Ge 41 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
12381
+#define OP_SorterSort 42
12382
+#define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12383
+#define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12384
+#define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12385
+#define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12386
+#define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12387
+#define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12388
+#define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12389
+#define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12390
+#define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12391
+#define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12392
+#define OP_Sort 53
12393
+#define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12394
+#define OP_Rewind 55
12395
+#define OP_IdxLE 56 /* synopsis: key=r[P3@P4] */
12396
+#define OP_IdxGT 57 /* synopsis: key=r[P3@P4] */
12397
+#define OP_IdxLT 58 /* synopsis: key=r[P3@P4] */
12398
+#define OP_IdxGE 59 /* synopsis: key=r[P3@P4] */
12399
+#define OP_RowSetRead 60 /* synopsis: r[P3]=rowset(P1) */
12400
+#define OP_RowSetTest 61 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12401
+#define OP_Program 62
12402
+#define OP_FkIfZero 63 /* synopsis: if fkctr[P1]==0 goto P2 */
12403
+#define OP_IfPos 64 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12404
+#define OP_IfNotZero 65 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12405
+#define OP_DecrJumpZero 66 /* synopsis: if (--r[P1])==0 goto P2 */
12406
+#define OP_IncrVacuum 67
12407
+#define OP_VNext 68
12408
+#define OP_Init 69 /* synopsis: Start at P2 */
12409
+#define OP_Return 70
12410
+#define OP_EndCoroutine 71
12411
+#define OP_HaltIfNull 72 /* synopsis: if r[P3]=null halt */
12412
+#define OP_Halt 73
12413
+#define OP_Integer 74 /* synopsis: r[P2]=P1 */
12414
+#define OP_Int64 75 /* synopsis: r[P2]=P4 */
12415
+#define OP_String 76 /* synopsis: r[P2]='P4' (len=P1) */
12416
+#define OP_Null 77 /* synopsis: r[P2..P3]=NULL */
12417
+#define OP_SoftNull 78 /* synopsis: r[P1]=NULL */
12418
+#define OP_Blob 79 /* synopsis: r[P2]=P4 (len=P1) */
12419
+#define OP_Variable 80 /* synopsis: r[P2]=parameter(P1,P4) */
12420
+#define OP_Move 81 /* synopsis: r[P2@P3]=r[P1@P3] */
12421
+#define OP_Copy 82 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12422
+#define OP_SCopy 83 /* synopsis: r[P2]=r[P1] */
12423
+#define OP_IntCopy 84 /* synopsis: r[P2]=r[P1] */
12424
+#define OP_ResultRow 85 /* synopsis: output=r[P1@P2] */
12425
+#define OP_CollSeq 86
12426
+#define OP_Function0 87 /* synopsis: r[P3]=func(r[P2@P5]) */
12427
+#define OP_Function 88 /* synopsis: r[P3]=func(r[P2@P5]) */
12428
+#define OP_AddImm 89 /* synopsis: r[P1]=r[P1]+P2 */
12429
+#define OP_RealAffinity 90
12430
+#define OP_Cast 91 /* synopsis: affinity(r[P1]) */
12431
+#define OP_Permutation 92
12432
+#define OP_Compare 93 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12433
+#define OP_Column 94 /* synopsis: r[P3]=PX */
12434
+#define OP_Affinity 95 /* synopsis: affinity(r[P1@P2]) */
12435
+#define OP_MakeRecord 96 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
1095112436
#define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
10952
-#define OP_ResetCount 98
10953
-#define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
10954
-#define OP_SorterData 100 /* synopsis: r[P2]=data */
10955
-#define OP_RowKey 101 /* synopsis: r[P2]=key */
10956
-#define OP_RowData 102 /* synopsis: r[P2]=data */
10957
-#define OP_Rowid 103 /* synopsis: r[P2]=rowid */
10958
-#define OP_NullRow 104
10959
-#define OP_Last 105
10960
-#define OP_SorterSort 106
10961
-#define OP_Sort 107
10962
-#define OP_Rewind 108
10963
-#define OP_SorterInsert 109
10964
-#define OP_IdxInsert 110 /* synopsis: key=r[P2] */
10965
-#define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
10966
-#define OP_Seek 112 /* synopsis: Move P3 to P1.rowid */
10967
-#define OP_IdxRowid 113 /* synopsis: r[P2]=rowid */
10968
-#define OP_IdxLE 114 /* synopsis: key=r[P3@P4] */
10969
-#define OP_IdxGT 115 /* synopsis: key=r[P3@P4] */
10970
-#define OP_IdxLT 116 /* synopsis: key=r[P3@P4] */
10971
-#define OP_IdxGE 117 /* synopsis: key=r[P3@P4] */
10972
-#define OP_Destroy 118
10973
-#define OP_Clear 119
10974
-#define OP_ResetSorter 120
10975
-#define OP_CreateIndex 121 /* synopsis: r[P2]=root iDb=P1 */
10976
-#define OP_CreateTable 122 /* synopsis: r[P2]=root iDb=P1 */
10977
-#define OP_ParseSchema 123
10978
-#define OP_LoadAnalysis 124
10979
-#define OP_DropTable 125
10980
-#define OP_DropIndex 126
10981
-#define OP_DropTrigger 127
10982
-#define OP_IntegrityCk 128
10983
-#define OP_RowSetAdd 129 /* synopsis: rowset(P1)=r[P2] */
10984
-#define OP_RowSetRead 130 /* synopsis: r[P3]=rowset(P1) */
10985
-#define OP_RowSetTest 131 /* synopsis: if r[P3] in rowset(P1) goto P2 */
10986
-#define OP_Program 132
12437
+#define OP_Count 98 /* synopsis: r[P2]=count() */
12438
+#define OP_ReadCookie 99
12439
+#define OP_SetCookie 100
12440
+#define OP_ReopenIdx 101 /* synopsis: root=P2 iDb=P3 */
12441
+#define OP_OpenRead 102 /* synopsis: root=P2 iDb=P3 */
12442
+#define OP_OpenWrite 103 /* synopsis: root=P2 iDb=P3 */
12443
+#define OP_OpenAutoindex 104 /* synopsis: nColumn=P2 */
12444
+#define OP_OpenEphemeral 105 /* synopsis: nColumn=P2 */
12445
+#define OP_SorterOpen 106
12446
+#define OP_SequenceTest 107 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12447
+#define OP_OpenPseudo 108 /* synopsis: P3 columns in r[P2] */
12448
+#define OP_Close 109
12449
+#define OP_ColumnsUsed 110
12450
+#define OP_Sequence 111 /* synopsis: r[P2]=cursor[P1].ctr++ */
12451
+#define OP_NewRowid 112 /* synopsis: r[P2]=rowid */
12452
+#define OP_Insert 113 /* synopsis: intkey=r[P3] data=r[P2] */
12453
+#define OP_InsertInt 114 /* synopsis: intkey=P3 data=r[P2] */
12454
+#define OP_Delete 115
12455
+#define OP_ResetCount 116
12456
+#define OP_SorterCompare 117 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12457
+#define OP_SorterData 118 /* synopsis: r[P2]=data */
12458
+#define OP_RowKey 119 /* synopsis: r[P2]=key */
12459
+#define OP_RowData 120 /* synopsis: r[P2]=data */
12460
+#define OP_Rowid 121 /* synopsis: r[P2]=rowid */
12461
+#define OP_NullRow 122
12462
+#define OP_SorterInsert 123
12463
+#define OP_IdxInsert 124 /* synopsis: key=r[P2] */
12464
+#define OP_IdxDelete 125 /* synopsis: key=r[P2@P3] */
12465
+#define OP_Seek 126 /* synopsis: Move P3 to P1.rowid */
12466
+#define OP_IdxRowid 127 /* synopsis: r[P2]=rowid */
12467
+#define OP_Destroy 128
12468
+#define OP_Clear 129
12469
+#define OP_ResetSorter 130
12470
+#define OP_CreateIndex 131 /* synopsis: r[P2]=root iDb=P1 */
12471
+#define OP_CreateTable 132 /* synopsis: r[P2]=root iDb=P1 */
1098712472
#define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
10988
-#define OP_Param 134
10989
-#define OP_FkCounter 135 /* synopsis: fkctr[P1]+=P2 */
10990
-#define OP_FkIfZero 136 /* synopsis: if fkctr[P1]==0 goto P2 */
10991
-#define OP_MemMax 137 /* synopsis: r[P1]=max(r[P1],r[P2]) */
10992
-#define OP_IfPos 138 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
10993
-#define OP_OffsetLimit 139 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
10994
-#define OP_IfNotZero 140 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
10995
-#define OP_DecrJumpZero 141 /* synopsis: if (--r[P1])==0 goto P2 */
10996
-#define OP_JumpZeroIncr 142 /* synopsis: if (r[P1]++)==0 ) goto P2 */
10997
-#define OP_AggStep0 143 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10998
-#define OP_AggStep 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10999
-#define OP_AggFinal 145 /* synopsis: accum=r[P1] N=P2 */
11000
-#define OP_IncrVacuum 146
11001
-#define OP_Expire 147
11002
-#define OP_TableLock 148 /* synopsis: iDb=P1 root=P2 write=P3 */
11003
-#define OP_VBegin 149
11004
-#define OP_VCreate 150
11005
-#define OP_VDestroy 151
11006
-#define OP_VOpen 152
11007
-#define OP_VColumn 153 /* synopsis: r[P3]=vcolumn(P2) */
11008
-#define OP_VNext 154
12473
+#define OP_ParseSchema 134
12474
+#define OP_LoadAnalysis 135
12475
+#define OP_DropTable 136
12476
+#define OP_DropIndex 137
12477
+#define OP_DropTrigger 138
12478
+#define OP_IntegrityCk 139
12479
+#define OP_RowSetAdd 140 /* synopsis: rowset(P1)=r[P2] */
12480
+#define OP_Param 141
12481
+#define OP_FkCounter 142 /* synopsis: fkctr[P1]+=P2 */
12482
+#define OP_MemMax 143 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12483
+#define OP_OffsetLimit 144 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12484
+#define OP_AggStep0 145 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12485
+#define OP_AggStep 146 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12486
+#define OP_AggFinal 147 /* synopsis: accum=r[P1] N=P2 */
12487
+#define OP_Expire 148
12488
+#define OP_TableLock 149 /* synopsis: iDb=P1 root=P2 write=P3 */
12489
+#define OP_VBegin 150
12490
+#define OP_VCreate 151
12491
+#define OP_VDestroy 152
12492
+#define OP_VOpen 153
12493
+#define OP_VColumn 154 /* synopsis: r[P3]=vcolumn(P2) */
1100912494
#define OP_VRename 155
1101012495
#define OP_Pagecount 156
1101112496
#define OP_MaxPgcnt 157
11012
-#define OP_Init 158 /* synopsis: Start at P2 */
11013
-#define OP_CursorHint 159
11014
-#define OP_Noop 160
11015
-#define OP_Explain 161
12497
+#define OP_CursorHint 158
12498
+#define OP_Noop 159
12499
+#define OP_Explain 160
1101612500
1101712501
/* Properties such as "out2" or "jump" that are specified in
1101812502
** comments following the "case" for each opcode in the vdbe.c
1101912503
** are encoded into bitvectors as follows:
1102012504
*/
@@ -11024,30 +12508,38 @@
1102412508
#define OPFLG_IN3 0x08 /* in3: P3 is an input */
1102512509
#define OPFLG_OUT2 0x10 /* out2: P2 is an output */
1102612510
#define OPFLG_OUT3 0x20 /* out3: P3 is an output */
1102712511
#define OPFLG_INITIALIZER {\
1102812512
/* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
11029
-/* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x02,\
11030
-/* 16 */ 0x01, 0x02, 0x03, 0x12, 0x08, 0x00, 0x10, 0x10,\
11031
-/* 24 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
11032
-/* 32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
11033
-/* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
11034
-/* 48 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
11035
-/* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
11036
-/* 64 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x26,\
11037
-/* 72 */ 0x26, 0x10, 0x10, 0x00, 0x03, 0x03, 0x0b, 0x0b,\
11038
-/* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
11039
-/* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
11040
-/* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
11041
-/* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x00,\
11042
-/* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
11043
-/* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
11044
-/* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
11045
-/* 136 */ 0x01, 0x04, 0x03, 0x1a, 0x03, 0x03, 0x03, 0x00,\
11046
-/* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
11047
-/* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
11048
-/* 160 */ 0x00, 0x00,}
12513
+/* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12514
+/* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12515
+/* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12516
+/* 32 */ 0x09, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12517
+/* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12518
+/* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12519
+/* 56 */ 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01,\
12520
+/* 64 */ 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02, 0x02,\
12521
+/* 72 */ 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10,\
12522
+/* 80 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12523
+/* 88 */ 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
12524
+/* 96 */ 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
12525
+/* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
12526
+/* 112 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12527
+/* 120 */ 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
12528
+/* 128 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
12529
+/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
12530
+/* 144 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12531
+/* 152 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12532
+/* 160 */ 0x00,}
12533
+
12534
+/* The sqlite3P2Values() routine is able to run faster if it knows
12535
+** the value of the largest JUMP opcode. The smaller the maximum
12536
+** JUMP opcode the better, so the mkopcodeh.tcl script that
12537
+** generated this include file strives to group all JUMP opcodes
12538
+** together near the beginning of the list.
12539
+*/
12540
+#define SQLITE_MX_JUMP_OPCODE 69 /* Maximum JUMP opcode */
1104912541
1105012542
/************** End of opcodes.h *********************************************/
1105112543
/************** Continuing where we left off in vdbe.h ***********************/
1105212544
1105312545
/*
@@ -11266,11 +12758,15 @@
1126612758
#define PAGER_LOCKINGMODE_QUERY -1
1126712759
#define PAGER_LOCKINGMODE_NORMAL 0
1126812760
#define PAGER_LOCKINGMODE_EXCLUSIVE 1
1126912761
1127012762
/*
11271
-** Numeric constants that encode the journalmode.
12763
+** Numeric constants that encode the journalmode.
12764
+**
12765
+** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12766
+** are exposed in the API via the "PRAGMA journal_mode" command and
12767
+** therefore cannot be changed without a compatibility break.
1127212768
*/
1127312769
#define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
1127412770
#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
1127512771
#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
1127612772
#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
@@ -11284,10 +12780,15 @@
1128412780
#define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
1128512781
#define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
1128612782
1128712783
/*
1128812784
** Flags for sqlite3PagerSetFlags()
12785
+**
12786
+** Value constraints (enforced via assert()):
12787
+** PAGER_FULLFSYNC == SQLITE_FullFSync
12788
+** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12789
+** PAGER_CACHE_SPILL == SQLITE_CacheSpill
1128912790
*/
1129012791
#define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
1129112792
#define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
1129212793
#define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
1129312794
#define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
@@ -11453,11 +12954,11 @@
1145312954
*/
1145412955
struct PgHdr {
1145512956
sqlite3_pcache_page *pPage; /* Pcache object page handle */
1145612957
void *pData; /* Page data */
1145712958
void *pExtra; /* Extra content */
11458
- PgHdr *pDirty; /* Transient list of dirty pages */
12959
+ PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
1145912960
Pager *pPager; /* The pager this page is part of */
1146012961
Pgno pgno; /* Page number for this page */
1146112962
#ifdef SQLITE_CHECK_PAGES
1146212963
u32 pageHash; /* Hash of page content */
1146312964
#endif
@@ -11478,15 +12979,14 @@
1147812979
#define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
1147912980
#define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
1148012981
#define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
1148112982
#define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
1148212983
** writing this page to the database */
11483
-#define PGHDR_NEED_READ 0x010 /* Content is unread */
11484
-#define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
11485
-#define PGHDR_MMAP 0x040 /* This is an mmap page object */
12984
+#define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
12985
+#define PGHDR_MMAP 0x020 /* This is an mmap page object */
1148612986
11487
-#define PGHDR_WAL_APPEND 0x080 /* Appended to wal file */
12987
+#define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
1148812988
1148912989
/* Initialize and shutdown the page cache subsystem */
1149012990
SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
1149112991
SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
1149212992
@@ -11526,10 +13026,11 @@
1152613026
1152713027
SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
1152813028
SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
1152913029
SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
1153013030
SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13031
+SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
1153113032
1153213033
/* Change a page number. Used by incr-vacuum. */
1153313034
SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
1153413035
1153513036
/* Remove all pages with pgno>x. Reset the cache if x==0 */
@@ -11563,10 +13064,15 @@
1156313064
** interface is only available if SQLITE_CHECK_PAGES is defined when the
1156413065
** library is built.
1156513066
*/
1156613067
SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
1156713068
#endif
13069
+
13070
+#if defined(SQLITE_DEBUG)
13071
+/* Check invariants on a PgHdr object */
13072
+SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13073
+#endif
1156813074
1156913075
/* Set and get the suggested cache-size for the specified pager-cache.
1157013076
**
1157113077
** If no global maximum is configured, then the system attempts to limit
1157213078
** the total number of pages cached by purgeable pager-caches to the sum
@@ -11599,10 +13105,13 @@
1159913105
SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
1160013106
1160113107
/* Return the header size */
1160213108
SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
1160313109
SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13110
+
13111
+/* Number of dirty pages as a percentage of the configured cache size */
13112
+SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
1160413113
1160513114
#endif /* _PCACHE_H_ */
1160613115
1160713116
/************** End of pcache.h **********************************************/
1160813117
/************** Continuing where we left off in sqliteInt.h ******************/
@@ -11829,11 +13338,11 @@
1182913338
SQLITE_PRIVATE int sqlite3OsInit(void);
1183013339
1183113340
/*
1183213341
** Functions for accessing sqlite3_file methods
1183313342
*/
11834
-SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
13343
+SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
1183513344
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
1183613345
SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
1183713346
SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
1183813347
SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
1183913348
SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
@@ -11874,11 +13383,11 @@
1187413383
/*
1187513384
** Convenience functions for opening and closing files using
1187613385
** sqlite3_malloc() to obtain space for the file-handle structure.
1187713386
*/
1187813387
SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
11879
-SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
13388
+SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
1188013389
1188113390
#endif /* _SQLITE_OS_H_ */
1188213391
1188313392
/************** End of os.h **************************************************/
1188413393
/************** Continuing where we left off in sqliteInt.h ******************/
@@ -12206,10 +13715,17 @@
1220613715
int (*xCommitCallback)(void*); /* Invoked at every commit. */
1220713716
void *pRollbackArg; /* Argument to xRollbackCallback() */
1220813717
void (*xRollbackCallback)(void*); /* Invoked at every commit. */
1220913718
void *pUpdateArg;
1221013719
void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13720
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13721
+ void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13722
+ void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13723
+ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13724
+ );
13725
+ PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13726
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
1221113727
#ifndef SQLITE_OMIT_WAL
1221213728
int (*xWalCallback)(void *, sqlite3 *, const char *, int);
1221313729
void *pWalArg;
1221413730
#endif
1221513731
void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
@@ -12276,10 +13792,15 @@
1227613792
#define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
1227713793
#define ENC(db) ((db)->enc)
1227813794
1227913795
/*
1228013796
** Possible values for the sqlite3.flags.
13797
+**
13798
+** Value constraints (enforced via assert()):
13799
+** SQLITE_FullFSync == PAGER_FULLFSYNC
13800
+** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
13801
+** SQLITE_CacheSpill == PAGER_CACHE_SPILL
1228113802
*/
1228213803
#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
1228313804
#define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
1228413805
#define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
1228513806
#define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
@@ -12303,17 +13824,18 @@
1230313824
#define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
1230413825
#define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
1230513826
#define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
1230613827
#define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
1230713828
#define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
12308
-#define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
12309
-#define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
12310
-#define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
12311
-#define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
12312
-#define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
12313
-#define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
12314
-#define SQLITE_Fts3Tokenizer 0x20000000 /* Enable fts3_tokenizer(2) */
13829
+#define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
13830
+#define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
13831
+#define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
13832
+#define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
13833
+#define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
13834
+#define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
13835
+#define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
13836
+#define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
1231513837
1231613838
1231713839
/*
1231813840
** Bits of the sqlite3.dbOptFlags field that are used by the
1231913841
** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
@@ -12410,10 +13932,17 @@
1241013932
/*
1241113933
** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
1241213934
** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
1241313935
** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
1241413936
** are assert() statements in the code to verify this.
13937
+**
13938
+** Value constraints (enforced via assert()):
13939
+** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
13940
+** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
13941
+** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
13942
+** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
13943
+** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
1241513944
*/
1241613945
#define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
1241713946
#define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
1241813947
#define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
1241913948
#define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
@@ -13409,10 +14938,13 @@
1340914938
1341014939
1341114940
/*
1341214941
** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
1341314942
** and the WhereInfo.wctrlFlags member.
14943
+**
14944
+** Value constraints (enforced via assert()):
14945
+** WHERE_USE_LIMIT == SF_FixedLimit
1341414946
*/
1341514947
#define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
1341614948
#define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
1341714949
#define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
1341814950
#define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
@@ -13426,10 +14958,11 @@
1342614958
#define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
1342714959
#define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
1342814960
#define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
1342914961
#define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
1343014962
#define WHERE_USE_LIMIT 0x4000 /* There is a constant LIMIT clause */
14963
+#define WHERE_SEEK_TABLE 0x8000 /* Do not defer seeks on main table */
1343114964
1343214965
/* Allowed return values from sqlite3WhereIsDistinct()
1343314966
*/
1343414967
#define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
1343514968
#define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
@@ -13469,20 +15002,22 @@
1346915002
};
1347015003
1347115004
/*
1347215005
** Allowed values for the NameContext, ncFlags field.
1347315006
**
13474
-** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
13475
-** SQLITE_FUNC_MINMAX.
15007
+** Value constraints (all checked via assert()):
15008
+** NC_HasAgg == SF_HasAgg
15009
+** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
1347615010
**
1347715011
*/
1347815012
#define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
13479
-#define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
15013
+#define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
1348015014
#define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
1348115015
#define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
13482
-#define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
15016
+#define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
1348315017
#define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15018
+#define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
1348415019
#define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
1348515020
1348615021
/*
1348715022
** An instance of the following structure contains all information
1348815023
** needed to generate code for a single SELECT statement.
@@ -13526,28 +15061,34 @@
1352615061
};
1352715062
1352815063
/*
1352915064
** Allowed values for Select.selFlags. The "SF" prefix stands for
1353015065
** "Select Flag".
15066
+**
15067
+** Value constraints (all checked via assert())
15068
+** SF_HasAgg == NC_HasAgg
15069
+** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15070
+** SF_FixedLimit == WHERE_USE_LIMIT
1353115071
*/
1353215072
#define SF_Distinct 0x00001 /* Output should be DISTINCT */
1353315073
#define SF_All 0x00002 /* Includes the ALL keyword */
1353415074
#define SF_Resolved 0x00004 /* Identifiers have been resolved */
13535
-#define SF_Aggregate 0x00008 /* Contains aggregate functions */
13536
-#define SF_UsesEphemeral 0x00010 /* Uses the OpenEphemeral opcode */
13537
-#define SF_Expanded 0x00020 /* sqlite3SelectExpand() called on this */
13538
-#define SF_HasTypeInfo 0x00040 /* FROM subqueries have Table metadata */
13539
-#define SF_Compound 0x00080 /* Part of a compound query */
13540
-#define SF_Values 0x00100 /* Synthesized from VALUES clause */
13541
-#define SF_MultiValue 0x00200 /* Single VALUES term with multiple rows */
13542
-#define SF_NestedFrom 0x00400 /* Part of a parenthesized FROM clause */
13543
-#define SF_MaybeConvert 0x00800 /* Need convertCompoundSelectToSubquery() */
15075
+#define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15076
+#define SF_HasAgg 0x00010 /* Contains aggregate functions */
15077
+#define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15078
+#define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15079
+#define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15080
+#define SF_Compound 0x00100 /* Part of a compound query */
15081
+#define SF_Values 0x00200 /* Synthesized from VALUES clause */
15082
+#define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15083
+#define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
1354415084
#define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
1354515085
#define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
1354615086
#define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
13547
-#define SF_Converted 0x08000 /* By convertCompoundSelectToSubquery() */
13548
-#define SF_IncludeHidden 0x10000 /* Include hidden columns in output */
15087
+#define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15088
+#define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15089
+#define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
1354915090
1355015091
1355115092
/*
1355215093
** The results of a SELECT can be distributed in several ways, as defined
1355315094
** by one of the following macros. The "SRT" prefix means "SELECT Result
@@ -13740,10 +15281,11 @@
1374015281
u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
1374115282
u8 mayAbort; /* True if statement may throw an ABORT exception */
1374215283
u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
1374315284
u8 okConstFactor; /* OK to factor out constants */
1374415285
u8 disableLookaside; /* Number of times lookaside has been disabled */
15286
+ u8 nColCache; /* Number of entries in aColCache[] */
1374515287
int aTempReg[8]; /* Holding area for temporary registers */
1374615288
int nRangeReg; /* Size of the temporary register block */
1374715289
int iRangeReg; /* First register in temporary register block */
1374815290
int nErr; /* Number of errors seen */
1374915291
int nTab; /* Number of previously allocated VDBE cursors */
@@ -13853,18 +15395,30 @@
1385315395
Parse *pParse; /* The Parse structure */
1385415396
};
1385515397
1385615398
/*
1385715399
** Bitfield flags for P5 value in various opcodes.
15400
+**
15401
+** Value constraints (enforced via assert()):
15402
+** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15403
+** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15404
+** OPFLAG_BULKCSR == BTREE_BULKLOAD
15405
+** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15406
+** OPFLAG_FORDELETE == BTREE_FORDELETE
15407
+** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15408
+** OPFLAG_AUXDELETE == BTREE_AUXDELETE
1385815409
*/
1385915410
#define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
1386015411
/* Also used in P2 (not P5) of OP_Delete */
1386115412
#define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
1386215413
#define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
1386315414
#define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
1386415415
#define OPFLAG_APPEND 0x08 /* This is likely to be an append */
1386515416
#define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15417
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15418
+#define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15419
+#endif
1386615420
#define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
1386715421
#define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
1386815422
#define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
1386915423
#define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
1387015424
#define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
@@ -14224,18 +15778,20 @@
1422415778
# define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
1422515779
# define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
1422615780
# define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
1422715781
# define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
1422815782
# define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
15783
+# define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
1422915784
#else
1423015785
# define sqlite3Toupper(x) toupper((unsigned char)(x))
1423115786
# define sqlite3Isspace(x) isspace((unsigned char)(x))
1423215787
# define sqlite3Isalnum(x) isalnum((unsigned char)(x))
1423315788
# define sqlite3Isalpha(x) isalpha((unsigned char)(x))
1423415789
# define sqlite3Isdigit(x) isdigit((unsigned char)(x))
1423515790
# define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
1423615791
# define sqlite3Tolower(x) tolower((unsigned char)(x))
15792
+# define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
1423715793
#endif
1423815794
#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
1423915795
SQLITE_PRIVATE int sqlite3IsIdChar(u8);
1424015796
#endif
1424115797
@@ -14355,11 +15911,11 @@
1435515911
#endif
1435615912
1435715913
1435815914
SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
1435915915
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
14360
-SQLITE_PRIVATE int sqlite3Dequote(char*);
15916
+SQLITE_PRIVATE void sqlite3Dequote(char*);
1436115917
SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
1436215918
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
1436315919
SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
1436415920
SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
1436515921
SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
@@ -14372,10 +15928,11 @@
1437215928
#endif
1437315929
SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
1437415930
SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
1437515931
SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
1437615932
SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
15933
+SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
1437715934
SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
1437815935
SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
1437915936
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
1438015937
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
1438115938
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
@@ -15167,10 +16724,11 @@
1516716724
** isdigit() 0x04
1516816725
** isalnum() 0x06
1516916726
** isxdigit() 0x08
1517016727
** toupper() 0x20
1517116728
** SQLite identifier character 0x40
16729
+** Quote character 0x80
1517216730
**
1517316731
** Bit 0x20 is set if the mapped character requires translation to upper
1517416732
** case. i.e. if the character is a lower-case ASCII character.
1517516733
** If x is a lower-case ASCII character, then its upper-case equivalent
1517616734
** is (x - 0x20). Therefore toupper() can be implemented as:
@@ -15192,20 +16750,20 @@
1519216750
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
1519316751
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
1519416752
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
1519516753
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
1519616754
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
15197
- 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
16755
+ 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
1519816756
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
1519916757
0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
1520016758
0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
1520116759
1520216760
0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
1520316761
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
1520416762
0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
15205
- 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
15206
- 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
16763
+ 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
16764
+ 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
1520716765
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
1520816766
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
1520916767
0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
1521016768
1521116769
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
@@ -16271,10 +17829,29 @@
1627117829
#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
1627217830
#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
1627317831
#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
1627417832
#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
1627517833
17834
+/*
17835
+** Structure used to store the context required by the
17836
+** sqlite3_preupdate_*() API functions.
17837
+*/
17838
+struct PreUpdate {
17839
+ Vdbe *v;
17840
+ VdbeCursor *pCsr; /* Cursor to read old values from */
17841
+ int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
17842
+ u8 *aRecord; /* old.* database record */
17843
+ KeyInfo keyinfo;
17844
+ UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
17845
+ UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
17846
+ int iNewReg; /* Register for new.* values */
17847
+ i64 iKey1; /* First key value passed to hook */
17848
+ i64 iKey2; /* Second key value passed to hook */
17849
+ int iPKey; /* If not negative index of IPK column */
17850
+ Mem *aNew; /* Array of new.* values */
17851
+};
17852
+
1627617853
/*
1627717854
** Function prototypes
1627817855
*/
1627917856
SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
1628017857
SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
@@ -16330,10 +17907,13 @@
1633017907
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
1633117908
SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
1633217909
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
1633317910
SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
1633417911
SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17912
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
17913
+SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
17914
+#endif
1633517915
SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
1633617916
1633717917
SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
1633817918
SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
1633917919
SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
@@ -16767,10 +18347,19 @@
1676718347
/* #include <assert.h> */
1676818348
#include <time.h>
1676918349
1677018350
#ifndef SQLITE_OMIT_DATETIME_FUNCS
1677118351
18352
+/*
18353
+** The MSVC CRT on Windows CE may not have a localtime() function.
18354
+** So declare a substitute. The substitute function itself is
18355
+** defined in "os_win.c".
18356
+*/
18357
+#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18358
+ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18359
+struct tm *__cdecl localtime(const time_t *);
18360
+#endif
1677218361
1677318362
/*
1677418363
** A structure for holding a single date and time.
1677518364
*/
1677618365
typedef struct DateTime DateTime;
@@ -17135,10 +18724,11 @@
1713518724
p->validYMD = 0;
1713618725
p->validHMS = 0;
1713718726
p->validTZ = 0;
1713818727
}
1713918728
18729
+#ifndef SQLITE_OMIT_LOCALTIME
1714018730
/*
1714118731
** On recent Windows platforms, the localtime_s() function is available
1714218732
** as part of the "Secure CRT". It is essentially equivalent to
1714318733
** localtime_r() available under most POSIX platforms, except that the
1714418734
** order of the parameters is reversed.
@@ -17153,11 +18743,10 @@
1715318743
&& defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
1715418744
#undef HAVE_LOCALTIME_S
1715518745
#define HAVE_LOCALTIME_S 1
1715618746
#endif
1715718747
17158
-#ifndef SQLITE_OMIT_LOCALTIME
1715918748
/*
1716018749
** The following routine implements the rough equivalent of localtime_r()
1716118750
** using whatever operating-system specific localtime facility that
1716218751
** is available. This routine returns 0 on success and
1716318752
** non-zero on any kind of error.
@@ -17957,17 +19546,15 @@
1795719546
** The following routines are convenience wrappers around methods
1795819547
** of the sqlite3_file object. This is mostly just syntactic sugar. All
1795919548
** of this would be completely automatic if SQLite were coded using
1796019549
** C++ instead of plain old C.
1796119550
*/
17962
-SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
17963
- int rc = SQLITE_OK;
19551
+SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
1796419552
if( pId->pMethods ){
17965
- rc = pId->pMethods->xClose(pId);
19553
+ pId->pMethods->xClose(pId);
1796619554
pId->pMethods = 0;
1796719555
}
17968
- return rc;
1796919556
}
1797019557
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
1797119558
DO_OS_MALLOC_TEST(id);
1797219559
return id->pMethods->xRead(id, pBuf, amt, offset);
1797319560
}
@@ -18181,16 +19768,14 @@
1818119768
}else{
1818219769
rc = SQLITE_NOMEM_BKPT;
1818319770
}
1818419771
return rc;
1818519772
}
18186
-SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
18187
- int rc = SQLITE_OK;
19773
+SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
1818819774
assert( pFile );
18189
- rc = sqlite3OsClose(pFile);
19775
+ sqlite3OsClose(pFile);
1819019776
sqlite3_free(pFile);
18191
- return rc;
1819219777
}
1819319778
1819419779
/*
1819519780
** This function is a wrapper around the OS specific implementation of
1819619781
** sqlite3_os_init(). The purpose of the wrapper is to provide the
@@ -22866,30 +24451,30 @@
2286624451
2286724452
/*
2286824453
** Conversion types fall into various categories as defined by the
2286924454
** following enumeration.
2287024455
*/
22871
-#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
22872
-#define etFLOAT 2 /* Floating point. %f */
22873
-#define etEXP 3 /* Exponentional notation. %e and %E */
22874
-#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
22875
-#define etSIZE 5 /* Return number of characters processed so far. %n */
22876
-#define etSTRING 6 /* Strings. %s */
22877
-#define etDYNSTRING 7 /* Dynamically allocated strings. %z */
22878
-#define etPERCENT 8 /* Percent symbol. %% */
22879
-#define etCHARX 9 /* Characters. %c */
24456
+#define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24457
+#define etFLOAT 1 /* Floating point. %f */
24458
+#define etEXP 2 /* Exponentional notation. %e and %E */
24459
+#define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24460
+#define etSIZE 4 /* Return number of characters processed so far. %n */
24461
+#define etSTRING 5 /* Strings. %s */
24462
+#define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24463
+#define etPERCENT 7 /* Percent symbol. %% */
24464
+#define etCHARX 8 /* Characters. %c */
2288024465
/* The rest are extensions, not normally found in printf() */
22881
-#define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
22882
-#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
24466
+#define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24467
+#define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
2288324468
NULL pointers replaced by SQL NULL. %Q */
22884
-#define etTOKEN 12 /* a pointer to a Token structure */
22885
-#define etSRCLIST 13 /* a pointer to a SrcList */
22886
-#define etPOINTER 14 /* The %p conversion */
22887
-#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
22888
-#define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24469
+#define etTOKEN 11 /* a pointer to a Token structure */
24470
+#define etSRCLIST 12 /* a pointer to a SrcList */
24471
+#define etPOINTER 13 /* The %p conversion */
24472
+#define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24473
+#define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
2288924474
22890
-#define etINVALID 0 /* Any unrecognized conversion type */
24475
+#define etINVALID 16 /* Any unrecognized conversion type */
2289124476
2289224477
2289324478
/*
2289424479
** An "etByte" is an 8-bit unsigned value.
2289524480
*/
@@ -23040,11 +24625,11 @@
2304024625
etByte flag_altform2; /* True if "!" flag is present */
2304124626
etByte flag_zeropad; /* True if field width constant starts with zero */
2304224627
etByte flag_long; /* True if "l" flag is present */
2304324628
etByte flag_longlong; /* True if the "ll" flag is present */
2304424629
etByte done; /* Loop termination flag */
23045
- etByte xtype = 0; /* Conversion paradigm */
24630
+ etByte xtype = etINVALID; /* Conversion paradigm */
2304624631
u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
2304724632
u8 useIntern; /* Ok to use internal conversions (ex: %T) */
2304824633
char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
2304924634
sqlite_uint64 longvalue; /* Value for integer types */
2305024635
LONGDOUBLE_TYPE realvalue; /* Value for real types */
@@ -25631,22 +27216,17 @@
2563127216
**
2563227217
** 2002-Feb-14: This routine is extended to remove MS-Access style
2563327218
** brackets from around identifiers. For example: "[a-b-c]" becomes
2563427219
** "a-b-c".
2563527220
*/
25636
-SQLITE_PRIVATE int sqlite3Dequote(char *z){
27221
+SQLITE_PRIVATE void sqlite3Dequote(char *z){
2563727222
char quote;
2563827223
int i, j;
25639
- if( z==0 ) return -1;
27224
+ if( z==0 ) return;
2564027225
quote = z[0];
25641
- switch( quote ){
25642
- case '\'': break;
25643
- case '"': break;
25644
- case '`': break; /* For MySQL compatibility */
25645
- case '[': quote = ']'; break; /* For MS SqlServer compatibility */
25646
- default: return -1;
25647
- }
27226
+ if( !sqlite3Isquote(quote) ) return;
27227
+ if( quote=='[' ) quote = ']';
2564827228
for(i=1, j=0;; i++){
2564927229
assert( z[i] );
2565027230
if( z[i]==quote ){
2565127231
if( z[i+1]==quote ){
2565227232
z[j++] = quote;
@@ -25657,11 +27237,10 @@
2565727237
}else{
2565827238
z[j++] = z[i];
2565927239
}
2566027240
}
2566127241
z[j] = 0;
25662
- return j;
2566327242
}
2566427243
2566527244
/*
2566627245
** Generate a Token object from a string
2566727246
*/
@@ -25750,11 +27329,11 @@
2575027329
int esign = 1; /* sign of exponent */
2575127330
int e = 0; /* exponent */
2575227331
int eValid = 1; /* True exponent is either not used or is well-formed */
2575327332
double result;
2575427333
int nDigits = 0;
25755
- int nonNum = 0;
27334
+ int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
2575627335
2575727336
assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
2575827337
*pResult = 0.0; /* Default return value, in case of an error */
2575927338
2576027339
if( enc==SQLITE_UTF8 ){
@@ -25763,11 +27342,11 @@
2576327342
int i;
2576427343
incr = 2;
2576527344
assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
2576627345
for(i=3-enc; i<length && z[i]==0; i+=2){}
2576727346
nonNum = i<length;
25768
- zEnd = z+i+enc-3;
27347
+ zEnd = &z[i^1];
2576927348
z += (enc&1);
2577027349
}
2577127350
2577227351
/* skip leading spaces */
2577327352
while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
@@ -25779,13 +27358,10 @@
2577927358
z+=incr;
2578027359
}else if( *z=='+' ){
2578127360
z+=incr;
2578227361
}
2578327362
25784
- /* skip leading zeroes */
25785
- while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
25786
-
2578727363
/* copy max significant digits to significand */
2578827364
while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
2578927365
s = s*10 + (*z - '0');
2579027366
z+=incr, nDigits++;
2579127367
}
@@ -25798,24 +27374,30 @@
2579827374
/* if decimal point is present */
2579927375
if( *z=='.' ){
2580027376
z+=incr;
2580127377
/* copy digits from after decimal to significand
2580227378
** (decrease exponent by d to shift decimal right) */
25803
- while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
25804
- s = s*10 + (*z - '0');
25805
- z+=incr, nDigits++, d--;
27379
+ while( z<zEnd && sqlite3Isdigit(*z) ){
27380
+ if( s<((LARGEST_INT64-9)/10) ){
27381
+ s = s*10 + (*z - '0');
27382
+ d--;
27383
+ }
27384
+ z+=incr, nDigits++;
2580627385
}
25807
- /* skip non-significant digits */
25808
- while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
2580927386
}
2581027387
if( z>=zEnd ) goto do_atof_calc;
2581127388
2581227389
/* if exponent is present */
2581327390
if( *z=='e' || *z=='E' ){
2581427391
z+=incr;
2581527392
eValid = 0;
25816
- if( z>=zEnd ) goto do_atof_calc;
27393
+
27394
+ /* This branch is needed to avoid a (harmless) buffer overread. The
27395
+ ** special comment alerts the mutation tester that the correct answer
27396
+ ** is obtained even if the branch is omitted */
27397
+ if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27398
+
2581727399
/* get sign of exponent */
2581827400
if( *z=='-' ){
2581927401
esign = -1;
2582027402
z+=incr;
2582127403
}else if( *z=='+' ){
@@ -25828,13 +27410,11 @@
2582827410
eValid = 1;
2582927411
}
2583027412
}
2583127413
2583227414
/* skip trailing spaces */
25833
- if( nDigits && eValid ){
25834
- while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
25835
- }
27415
+ while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
2583627416
2583727417
do_atof_calc:
2583827418
/* adjust exponent by d, and update sign */
2583927419
e = (e*esign) + d;
2584027420
if( e<0 ) {
@@ -25842,45 +27422,55 @@
2584227422
e *= -1;
2584327423
} else {
2584427424
esign = 1;
2584527425
}
2584627426
25847
- /* if 0 significand */
25848
- if( !s ) {
25849
- /* In the IEEE 754 standard, zero is signed.
25850
- ** Add the sign if we've seen at least one digit */
25851
- result = (sign<0 && nDigits) ? -(double)0 : (double)0;
27427
+ if( s==0 ) {
27428
+ /* In the IEEE 754 standard, zero is signed. */
27429
+ result = sign<0 ? -(double)0 : (double)0;
2585227430
} else {
25853
- /* attempt to reduce exponent */
25854
- if( esign>0 ){
25855
- while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
25856
- }else{
25857
- while( !(s%10) && e>0 ) e--,s/=10;
27431
+ /* Attempt to reduce exponent.
27432
+ **
27433
+ ** Branches that are not required for the correct answer but which only
27434
+ ** help to obtain the correct answer faster are marked with special
27435
+ ** comments, as a hint to the mutation tester.
27436
+ */
27437
+ while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27438
+ if( esign>0 ){
27439
+ if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27440
+ s *= 10;
27441
+ }else{
27442
+ if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27443
+ s /= 10;
27444
+ }
27445
+ e--;
2585827446
}
2585927447
2586027448
/* adjust the sign of significand */
2586127449
s = sign<0 ? -s : s;
2586227450
25863
- /* if exponent, scale significand as appropriate
25864
- ** and store in result. */
25865
- if( e ){
27451
+ if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27452
+ result = (double)s;
27453
+ }else{
2586627454
LONGDOUBLE_TYPE scale = 1.0;
2586727455
/* attempt to handle extremely small/large numbers better */
25868
- if( e>307 && e<342 ){
25869
- while( e%308 ) { scale *= 1.0e+1; e -= 1; }
25870
- if( esign<0 ){
25871
- result = s / scale;
25872
- result /= 1.0e+308;
25873
- }else{
25874
- result = s * scale;
25875
- result *= 1.0e+308;
25876
- }
25877
- }else if( e>=342 ){
25878
- if( esign<0 ){
25879
- result = 0.0*s;
25880
- }else{
25881
- result = 1e308*1e308*s; /* Infinity */
27456
+ if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27457
+ if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27458
+ while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27459
+ if( esign<0 ){
27460
+ result = s / scale;
27461
+ result /= 1.0e+308;
27462
+ }else{
27463
+ result = s * scale;
27464
+ result *= 1.0e+308;
27465
+ }
27466
+ }else{ assert( e>=342 );
27467
+ if( esign<0 ){
27468
+ result = 0.0*s;
27469
+ }else{
27470
+ result = 1e308*1e308*s; /* Infinity */
27471
+ }
2588227472
}
2588327473
}else{
2588427474
/* 1.0e+22 is the largest power of 10 than can be
2588527475
** represented exactly. */
2588627476
while( e%22 ) { scale *= 1.0e+1; e -= 1; }
@@ -25889,20 +27479,18 @@
2588927479
result = s / scale;
2589027480
}else{
2589127481
result = s * scale;
2589227482
}
2589327483
}
25894
- } else {
25895
- result = (double)s;
2589627484
}
2589727485
}
2589827486
2589927487
/* store the result */
2590027488
*pResult = result;
2590127489
2590227490
/* return true if number and no extra non-whitespace chracters after */
25903
- return z>=zEnd && nDigits>0 && eValid && nonNum==0;
27491
+ return z==zEnd && nDigits>0 && eValid && nonNum==0;
2590427492
#else
2590527493
return !sqlite3Atoi64(z, pResult, length, enc);
2590627494
#endif /* SQLITE_OMIT_FLOATING_POINT */
2590727495
}
2590827496
@@ -25960,11 +27548,11 @@
2596027548
int incr;
2596127549
u64 u = 0;
2596227550
int neg = 0; /* assume positive */
2596327551
int i;
2596427552
int c = 0;
25965
- int nonNum = 0;
27553
+ int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
2596627554
const char *zStart;
2596727555
const char *zEnd = zNum + length;
2596827556
assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
2596927557
if( enc==SQLITE_UTF8 ){
2597027558
incr = 1;
@@ -25971,11 +27559,11 @@
2597127559
}else{
2597227560
incr = 2;
2597327561
assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
2597427562
for(i=3-enc; i<length && zNum[i]==0; i+=2){}
2597527563
nonNum = i<length;
25976
- zEnd = zNum+i+enc-3;
27564
+ zEnd = &zNum[i^1];
2597727565
zNum += (enc&1);
2597827566
}
2597927567
while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
2598027568
if( zNum<zEnd ){
2598127569
if( *zNum=='-' ){
@@ -25998,12 +27586,15 @@
2599827586
*pNum = (i64)u;
2599927587
}
2600027588
testcase( i==18 );
2600127589
testcase( i==19 );
2600227590
testcase( i==20 );
26003
- if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
26004
- || i>19*incr || nonNum ){
27591
+ if( &zNum[i]<zEnd /* Extra bytes at the end */
27592
+ || (i==0 && zStart==zNum) /* No digits */
27593
+ || i>19*incr /* Too many digits */
27594
+ || nonNum /* UTF16 with high-order bytes non-zero */
27595
+ ){
2600527596
/* zNum is empty or contains non-numeric text or is longer
2600627597
** than 19 digits (thus guaranteeing that it is too large) */
2600727598
return 1;
2600827599
}else if( i<19*incr ){
2600927600
/* Less than 19 digits, so we know that it fits in 64 bits */
@@ -26041,11 +27632,10 @@
2604127632
*/
2604227633
SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
2604327634
#ifndef SQLITE_OMIT_HEX_INTEGER
2604427635
if( z[0]=='0'
2604527636
&& (z[1]=='x' || z[1]=='X')
26046
- && sqlite3Isxdigit(z[2])
2604727637
){
2604827638
u64 u = 0;
2604927639
int i, k;
2605027640
for(i=2; z[i]=='0'; i++){}
2605127641
for(k=i; sqlite3Isxdigit(z[k]); k++){
@@ -26803,11 +28393,11 @@
2680328393
LogEst y = 40;
2680428394
if( x<8 ){
2680528395
if( x<2 ) return 0;
2680628396
while( x<8 ){ y -= 10; x <<= 1; }
2680728397
}else{
26808
- while( x>255 ){ y += 40; x >>= 4; }
28398
+ while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
2680928399
while( x>15 ){ y += 10; x >>= 1; }
2681028400
}
2681128401
return a[x&7] + y - 10;
2681228402
}
2681328403
@@ -26837,11 +28427,10 @@
2683728427
** Note that this routine is only used when one or more of various
2683828428
** non-standard compile-time options is enabled.
2683928429
*/
2684028430
SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
2684128431
u64 n;
26842
- if( x<10 ) return 1;
2684328432
n = x%10;
2684428433
x /= 10;
2684528434
if( n>=5 ) n -= 2;
2684628435
else if( n>=1 ) n -= 1;
2684728436
#if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
@@ -26913,11 +28502,11 @@
2691328502
** The hashing function.
2691428503
*/
2691528504
static unsigned int strHash(const char *z){
2691628505
unsigned int h = 0;
2691728506
unsigned char c;
26918
- while( (c = (unsigned char)*z++)!=0 ){
28507
+ while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
2691928508
h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
2692028509
}
2692128510
return h;
2692228511
}
2692328512
@@ -27006,11 +28595,11 @@
2700628595
){
2700728596
HashElem *elem; /* Used to loop thru the element list */
2700828597
int count; /* Number of elements left to test */
2700928598
unsigned int h; /* The computed hash */
2701028599
27011
- if( pH->ht ){
28600
+ if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
2701228601
struct _ht *pEntry;
2701328602
h = strHash(pKey) % pH->htsize;
2701428603
pEntry = &pH->ht[h];
2701528604
elem = pEntry->chain;
2701628605
count = pEntry->count;
@@ -27153,157 +28742,156 @@
2715328742
/* 10 */ "Vacuum" OpHelp(""),
2715428743
/* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
2715528744
/* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
2715628745
/* 13 */ "Goto" OpHelp(""),
2715728746
/* 14 */ "Gosub" OpHelp(""),
27158
- /* 15 */ "Return" OpHelp(""),
27159
- /* 16 */ "InitCoroutine" OpHelp(""),
27160
- /* 17 */ "EndCoroutine" OpHelp(""),
27161
- /* 18 */ "Yield" OpHelp(""),
28747
+ /* 15 */ "InitCoroutine" OpHelp(""),
28748
+ /* 16 */ "Yield" OpHelp(""),
28749
+ /* 17 */ "MustBeInt" OpHelp(""),
28750
+ /* 18 */ "Jump" OpHelp(""),
2716228751
/* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
27163
- /* 20 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
27164
- /* 21 */ "Halt" OpHelp(""),
27165
- /* 22 */ "Integer" OpHelp("r[P2]=P1"),
27166
- /* 23 */ "Int64" OpHelp("r[P2]=P4"),
27167
- /* 24 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
27168
- /* 25 */ "Null" OpHelp("r[P2..P3]=NULL"),
27169
- /* 26 */ "SoftNull" OpHelp("r[P1]=NULL"),
27170
- /* 27 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
27171
- /* 28 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
27172
- /* 29 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
27173
- /* 30 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
27174
- /* 31 */ "SCopy" OpHelp("r[P2]=r[P1]"),
27175
- /* 32 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
27176
- /* 33 */ "ResultRow" OpHelp("output=r[P1@P2]"),
27177
- /* 34 */ "CollSeq" OpHelp(""),
27178
- /* 35 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
27179
- /* 36 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
27180
- /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
27181
- /* 38 */ "MustBeInt" OpHelp(""),
27182
- /* 39 */ "RealAffinity" OpHelp(""),
27183
- /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
27184
- /* 41 */ "Permutation" OpHelp(""),
27185
- /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
27186
- /* 43 */ "Jump" OpHelp(""),
27187
- /* 44 */ "Once" OpHelp(""),
27188
- /* 45 */ "If" OpHelp(""),
27189
- /* 46 */ "IfNot" OpHelp(""),
27190
- /* 47 */ "Column" OpHelp("r[P3]=PX"),
27191
- /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
27192
- /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
27193
- /* 50 */ "Count" OpHelp("r[P2]=count()"),
27194
- /* 51 */ "ReadCookie" OpHelp(""),
27195
- /* 52 */ "SetCookie" OpHelp(""),
27196
- /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
27197
- /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
27198
- /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
27199
- /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
27200
- /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
27201
- /* 58 */ "SorterOpen" OpHelp(""),
27202
- /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
27203
- /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
27204
- /* 61 */ "Close" OpHelp(""),
27205
- /* 62 */ "ColumnsUsed" OpHelp(""),
27206
- /* 63 */ "SeekLT" OpHelp("key=r[P3@P4]"),
27207
- /* 64 */ "SeekLE" OpHelp("key=r[P3@P4]"),
27208
- /* 65 */ "SeekGE" OpHelp("key=r[P3@P4]"),
27209
- /* 66 */ "SeekGT" OpHelp("key=r[P3@P4]"),
27210
- /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
27211
- /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
27212
- /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
27213
- /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
27214
- /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
27215
- /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
27216
- /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
27217
- /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
27218
- /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
27219
- /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
27220
- /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
27221
- /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
27222
- /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
27223
- /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
27224
- /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
27225
- /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
27226
- /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
27227
- /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
27228
- /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
27229
- /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
27230
- /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
27231
- /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
27232
- /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
27233
- /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
27234
- /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
27235
- /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
27236
- /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
27237
- /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
27238
- /* 95 */ "Delete" OpHelp(""),
27239
- /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
28752
+ /* 20 */ "Once" OpHelp(""),
28753
+ /* 21 */ "If" OpHelp(""),
28754
+ /* 22 */ "IfNot" OpHelp(""),
28755
+ /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
28756
+ /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
28757
+ /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
28758
+ /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
28759
+ /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
28760
+ /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
28761
+ /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
28762
+ /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
28763
+ /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
28764
+ /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
28765
+ /* 33 */ "Last" OpHelp(""),
28766
+ /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
28767
+ /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
28768
+ /* 36 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
28769
+ /* 37 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
28770
+ /* 38 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
28771
+ /* 39 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
28772
+ /* 40 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
28773
+ /* 41 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
28774
+ /* 42 */ "SorterSort" OpHelp(""),
28775
+ /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
28776
+ /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
28777
+ /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
28778
+ /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
28779
+ /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
28780
+ /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
28781
+ /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
28782
+ /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
28783
+ /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
28784
+ /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
28785
+ /* 53 */ "Sort" OpHelp(""),
28786
+ /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
28787
+ /* 55 */ "Rewind" OpHelp(""),
28788
+ /* 56 */ "IdxLE" OpHelp("key=r[P3@P4]"),
28789
+ /* 57 */ "IdxGT" OpHelp("key=r[P3@P4]"),
28790
+ /* 58 */ "IdxLT" OpHelp("key=r[P3@P4]"),
28791
+ /* 59 */ "IdxGE" OpHelp("key=r[P3@P4]"),
28792
+ /* 60 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
28793
+ /* 61 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
28794
+ /* 62 */ "Program" OpHelp(""),
28795
+ /* 63 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
28796
+ /* 64 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
28797
+ /* 65 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
28798
+ /* 66 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
28799
+ /* 67 */ "IncrVacuum" OpHelp(""),
28800
+ /* 68 */ "VNext" OpHelp(""),
28801
+ /* 69 */ "Init" OpHelp("Start at P2"),
28802
+ /* 70 */ "Return" OpHelp(""),
28803
+ /* 71 */ "EndCoroutine" OpHelp(""),
28804
+ /* 72 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
28805
+ /* 73 */ "Halt" OpHelp(""),
28806
+ /* 74 */ "Integer" OpHelp("r[P2]=P1"),
28807
+ /* 75 */ "Int64" OpHelp("r[P2]=P4"),
28808
+ /* 76 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
28809
+ /* 77 */ "Null" OpHelp("r[P2..P3]=NULL"),
28810
+ /* 78 */ "SoftNull" OpHelp("r[P1]=NULL"),
28811
+ /* 79 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
28812
+ /* 80 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
28813
+ /* 81 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
28814
+ /* 82 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
28815
+ /* 83 */ "SCopy" OpHelp("r[P2]=r[P1]"),
28816
+ /* 84 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
28817
+ /* 85 */ "ResultRow" OpHelp("output=r[P1@P2]"),
28818
+ /* 86 */ "CollSeq" OpHelp(""),
28819
+ /* 87 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
28820
+ /* 88 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
28821
+ /* 89 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
28822
+ /* 90 */ "RealAffinity" OpHelp(""),
28823
+ /* 91 */ "Cast" OpHelp("affinity(r[P1])"),
28824
+ /* 92 */ "Permutation" OpHelp(""),
28825
+ /* 93 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
28826
+ /* 94 */ "Column" OpHelp("r[P3]=PX"),
28827
+ /* 95 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
28828
+ /* 96 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
2724028829
/* 97 */ "String8" OpHelp("r[P2]='P4'"),
27241
- /* 98 */ "ResetCount" OpHelp(""),
27242
- /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
27243
- /* 100 */ "SorterData" OpHelp("r[P2]=data"),
27244
- /* 101 */ "RowKey" OpHelp("r[P2]=key"),
27245
- /* 102 */ "RowData" OpHelp("r[P2]=data"),
27246
- /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
27247
- /* 104 */ "NullRow" OpHelp(""),
27248
- /* 105 */ "Last" OpHelp(""),
27249
- /* 106 */ "SorterSort" OpHelp(""),
27250
- /* 107 */ "Sort" OpHelp(""),
27251
- /* 108 */ "Rewind" OpHelp(""),
27252
- /* 109 */ "SorterInsert" OpHelp(""),
27253
- /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
27254
- /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
27255
- /* 112 */ "Seek" OpHelp("Move P3 to P1.rowid"),
27256
- /* 113 */ "IdxRowid" OpHelp("r[P2]=rowid"),
27257
- /* 114 */ "IdxLE" OpHelp("key=r[P3@P4]"),
27258
- /* 115 */ "IdxGT" OpHelp("key=r[P3@P4]"),
27259
- /* 116 */ "IdxLT" OpHelp("key=r[P3@P4]"),
27260
- /* 117 */ "IdxGE" OpHelp("key=r[P3@P4]"),
27261
- /* 118 */ "Destroy" OpHelp(""),
27262
- /* 119 */ "Clear" OpHelp(""),
27263
- /* 120 */ "ResetSorter" OpHelp(""),
27264
- /* 121 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
27265
- /* 122 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
27266
- /* 123 */ "ParseSchema" OpHelp(""),
27267
- /* 124 */ "LoadAnalysis" OpHelp(""),
27268
- /* 125 */ "DropTable" OpHelp(""),
27269
- /* 126 */ "DropIndex" OpHelp(""),
27270
- /* 127 */ "DropTrigger" OpHelp(""),
27271
- /* 128 */ "IntegrityCk" OpHelp(""),
27272
- /* 129 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
27273
- /* 130 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
27274
- /* 131 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
27275
- /* 132 */ "Program" OpHelp(""),
28830
+ /* 98 */ "Count" OpHelp("r[P2]=count()"),
28831
+ /* 99 */ "ReadCookie" OpHelp(""),
28832
+ /* 100 */ "SetCookie" OpHelp(""),
28833
+ /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
28834
+ /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
28835
+ /* 103 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
28836
+ /* 104 */ "OpenAutoindex" OpHelp("nColumn=P2"),
28837
+ /* 105 */ "OpenEphemeral" OpHelp("nColumn=P2"),
28838
+ /* 106 */ "SorterOpen" OpHelp(""),
28839
+ /* 107 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
28840
+ /* 108 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
28841
+ /* 109 */ "Close" OpHelp(""),
28842
+ /* 110 */ "ColumnsUsed" OpHelp(""),
28843
+ /* 111 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
28844
+ /* 112 */ "NewRowid" OpHelp("r[P2]=rowid"),
28845
+ /* 113 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
28846
+ /* 114 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
28847
+ /* 115 */ "Delete" OpHelp(""),
28848
+ /* 116 */ "ResetCount" OpHelp(""),
28849
+ /* 117 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
28850
+ /* 118 */ "SorterData" OpHelp("r[P2]=data"),
28851
+ /* 119 */ "RowKey" OpHelp("r[P2]=key"),
28852
+ /* 120 */ "RowData" OpHelp("r[P2]=data"),
28853
+ /* 121 */ "Rowid" OpHelp("r[P2]=rowid"),
28854
+ /* 122 */ "NullRow" OpHelp(""),
28855
+ /* 123 */ "SorterInsert" OpHelp(""),
28856
+ /* 124 */ "IdxInsert" OpHelp("key=r[P2]"),
28857
+ /* 125 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
28858
+ /* 126 */ "Seek" OpHelp("Move P3 to P1.rowid"),
28859
+ /* 127 */ "IdxRowid" OpHelp("r[P2]=rowid"),
28860
+ /* 128 */ "Destroy" OpHelp(""),
28861
+ /* 129 */ "Clear" OpHelp(""),
28862
+ /* 130 */ "ResetSorter" OpHelp(""),
28863
+ /* 131 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
28864
+ /* 132 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
2727628865
/* 133 */ "Real" OpHelp("r[P2]=P4"),
27277
- /* 134 */ "Param" OpHelp(""),
27278
- /* 135 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
27279
- /* 136 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
27280
- /* 137 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
27281
- /* 138 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
27282
- /* 139 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
27283
- /* 140 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
27284
- /* 141 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
27285
- /* 142 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
27286
- /* 143 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
27287
- /* 144 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
27288
- /* 145 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
27289
- /* 146 */ "IncrVacuum" OpHelp(""),
27290
- /* 147 */ "Expire" OpHelp(""),
27291
- /* 148 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
27292
- /* 149 */ "VBegin" OpHelp(""),
27293
- /* 150 */ "VCreate" OpHelp(""),
27294
- /* 151 */ "VDestroy" OpHelp(""),
27295
- /* 152 */ "VOpen" OpHelp(""),
27296
- /* 153 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
27297
- /* 154 */ "VNext" OpHelp(""),
28866
+ /* 134 */ "ParseSchema" OpHelp(""),
28867
+ /* 135 */ "LoadAnalysis" OpHelp(""),
28868
+ /* 136 */ "DropTable" OpHelp(""),
28869
+ /* 137 */ "DropIndex" OpHelp(""),
28870
+ /* 138 */ "DropTrigger" OpHelp(""),
28871
+ /* 139 */ "IntegrityCk" OpHelp(""),
28872
+ /* 140 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
28873
+ /* 141 */ "Param" OpHelp(""),
28874
+ /* 142 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
28875
+ /* 143 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
28876
+ /* 144 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
28877
+ /* 145 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
28878
+ /* 146 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
28879
+ /* 147 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
28880
+ /* 148 */ "Expire" OpHelp(""),
28881
+ /* 149 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
28882
+ /* 150 */ "VBegin" OpHelp(""),
28883
+ /* 151 */ "VCreate" OpHelp(""),
28884
+ /* 152 */ "VDestroy" OpHelp(""),
28885
+ /* 153 */ "VOpen" OpHelp(""),
28886
+ /* 154 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
2729828887
/* 155 */ "VRename" OpHelp(""),
2729928888
/* 156 */ "Pagecount" OpHelp(""),
2730028889
/* 157 */ "MaxPgcnt" OpHelp(""),
27301
- /* 158 */ "Init" OpHelp("Start at P2"),
27302
- /* 159 */ "CursorHint" OpHelp(""),
27303
- /* 160 */ "Noop" OpHelp(""),
27304
- /* 161 */ "Explain" OpHelp(""),
28890
+ /* 158 */ "CursorHint" OpHelp(""),
28891
+ /* 159 */ "Noop" OpHelp(""),
28892
+ /* 160 */ "Explain" OpHelp(""),
2730528893
};
2730628894
return azName[i];
2730728895
}
2730828896
#endif
2730928897
@@ -27912,11 +29500,11 @@
2791229500
#if defined(USE_PREAD64)
2791329501
{ "pread64", (sqlite3_syscall_ptr)pread64, 0 },
2791429502
#else
2791529503
{ "pread64", (sqlite3_syscall_ptr)0, 0 },
2791629504
#endif
27917
-#define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
29505
+#define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
2791829506
2791929507
{ "write", (sqlite3_syscall_ptr)write, 0 },
2792029508
#define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
2792129509
2792229510
#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
@@ -27930,11 +29518,11 @@
2793029518
#if defined(USE_PREAD64)
2793129519
{ "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
2793229520
#else
2793329521
{ "pwrite64", (sqlite3_syscall_ptr)0, 0 },
2793429522
#endif
27935
-#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
29523
+#define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
2793629524
aSyscall[13].pCurrent)
2793729525
2793829526
{ "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
2793929527
#define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
2794029528
@@ -29009,20 +30597,26 @@
2900930597
static int unixLock(sqlite3_file *id, int eFileLock){
2901030598
/* The following describes the implementation of the various locks and
2901130599
** lock transitions in terms of the POSIX advisory shared and exclusive
2901230600
** lock primitives (called read-locks and write-locks below, to avoid
2901330601
** confusion with SQLite lock names). The algorithms are complicated
29014
- ** slightly in order to be compatible with windows systems simultaneously
30602
+ ** slightly in order to be compatible with Windows95 systems simultaneously
2901530603
** accessing the same database file, in case that is ever required.
2901630604
**
2901730605
** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
2901830606
** byte', each single bytes at well known offsets, and the 'shared byte
2901930607
** range', a range of 510 bytes at a well known offset.
2902030608
**
2902130609
** To obtain a SHARED lock, a read-lock is obtained on the 'pending
29022
- ** byte'. If this is successful, a random byte from the 'shared byte
29023
- ** range' is read-locked and the lock on the 'pending byte' released.
30610
+ ** byte'. If this is successful, 'shared byte range' is read-locked
30611
+ ** and the lock on the 'pending byte' released. (Legacy note: When
30612
+ ** SQLite was first developed, Windows95 systems were still very common,
30613
+ ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30614
+ ** single randomly selected by from the 'shared byte range' is locked.
30615
+ ** Windows95 is now pretty much extinct, but this work-around for the
30616
+ ** lack of shared-locks on Windows95 lives on, for backwards
30617
+ ** compatibility.)
2902430618
**
2902530619
** A process may only obtain a RESERVED lock after it has a SHARED lock.
2902630620
** A RESERVED lock is implemented by grabbing a write-lock on the
2902730621
** 'reserved byte'.
2902830622
**
@@ -29037,15 +30631,10 @@
2903730631
** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
2903830632
** implemented by obtaining a write-lock on the entire 'shared byte
2903930633
** range'. Since all other locks require a read-lock on one of the bytes
2904030634
** within this range, this ensures that no other locks are held on the
2904130635
** database.
29042
- **
29043
- ** The reason a single byte cannot be used instead of the 'shared byte
29044
- ** range' is that some versions of windows do not support read-locks. By
29045
- ** locking a random byte from a range, concurrent SHARED locks may exist
29046
- ** even if the locking primitive used is always a write-lock.
2904730636
*/
2904830637
int rc = SQLITE_OK;
2904930638
unixFile *pFile = (unixFile*)id;
2905030639
unixInodeInfo *pInode;
2905130640
struct flock lock;
@@ -31794,14 +33383,16 @@
3179433383
sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
3179533384
#endif
3179633385
pShmNode->h = -1;
3179733386
pDbFd->pInode->pShmNode = pShmNode;
3179833387
pShmNode->pInode = pDbFd->pInode;
31799
- pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
31800
- if( pShmNode->mutex==0 ){
31801
- rc = SQLITE_NOMEM_BKPT;
31802
- goto shm_open_err;
33388
+ if( sqlite3GlobalConfig.bCoreMutex ){
33389
+ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33390
+ if( pShmNode->mutex==0 ){
33391
+ rc = SQLITE_NOMEM_BKPT;
33392
+ goto shm_open_err;
33393
+ }
3180333394
}
3180433395
3180533396
if( pInode->bProcessLock==0 ){
3180633397
int openFlags = O_RDWR | O_CREAT;
3180733398
if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
@@ -32916,24 +34507,28 @@
3291634507
"/var/tmp",
3291734508
"/usr/tmp",
3291834509
"/tmp",
3291934510
"."
3292034511
};
32921
- unsigned int i;
34512
+ unsigned int i = 0;
3292234513
struct stat buf;
3292334514
const char *zDir = sqlite3_temp_directory;
3292434515
3292534516
if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
3292634517
if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
32927
- for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
32928
- if( zDir==0 ) continue;
32929
- if( osStat(zDir, &buf) ) continue;
32930
- if( !S_ISDIR(buf.st_mode) ) continue;
32931
- if( osAccess(zDir, 07) ) continue;
32932
- break;
32933
- }
32934
- return zDir;
34518
+ while(1){
34519
+ if( zDir!=0
34520
+ && osStat(zDir, &buf)==0
34521
+ && S_ISDIR(buf.st_mode)
34522
+ && osAccess(zDir, 03)==0
34523
+ ){
34524
+ return zDir;
34525
+ }
34526
+ if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34527
+ zDir = azDirs[i++];
34528
+ }
34529
+ return 0;
3293534530
}
3293634531
3293734532
/*
3293834533
** Create a temporary file name in zBuf. zBuf must be allocated
3293934534
** by the calling process and must be big enough to hold at least
@@ -32945,13 +34540,15 @@
3294534540
3294634541
/* It's odd to simulate an io-error here, but really this is just
3294734542
** using the io-error infrastructure to test that SQLite handles this
3294834543
** function failing.
3294934544
*/
34545
+ zBuf[0] = 0;
3295034546
SimulateIOError( return SQLITE_IOERR );
3295134547
3295234548
zDir = unixTempFileDir();
34549
+ if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
3295334550
do{
3295434551
u64 r;
3295534552
sqlite3_randomness(sizeof(r), &r);
3295634553
assert( nBuf>2 );
3295734554
zBuf[nBuf-2] = 0;
@@ -36549,12 +38146,12 @@
3654938146
*/
3655038147
SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
3655138148
int rc;
3655238149
MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
3655338150
MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
36554
- MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
36555
- MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
38151
+ MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38152
+ MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
3655638153
sqlite3_mutex_enter(pMaster);
3655738154
sqlite3_mutex_enter(pMem);
3655838155
winMemAssertMagic();
3655938156
if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
3656038157
/*
@@ -36595,10 +38192,16 @@
3659538192
SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
3659638193
char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
3659738194
int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
3659838195
if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
3659938196
assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38197
+#ifdef SQLITE_ENABLE_API_ARMOR
38198
+ if( !zBuf ){
38199
+ (void)SQLITE_MISUSE_BKPT;
38200
+ return;
38201
+ }
38202
+#endif
3660038203
#if defined(SQLITE_WIN32_HAS_ANSI)
3660138204
if( nMin>0 ){
3660238205
memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
3660338206
memcpy(zDbgBuf, zBuf, nMin);
3660438207
osOutputDebugStringA(zDbgBuf);
@@ -36920,151 +38523,248 @@
3692038523
sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
3692138524
}
3692238525
#endif /* SQLITE_WIN32_MALLOC */
3692338526
3692438527
/*
36925
-** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
38528
+** Convert a UTF-8 string to Microsoft Unicode.
3692638529
**
36927
-** Space to hold the returned string is obtained from malloc.
38530
+** Space to hold the returned string is obtained from sqlite3_malloc().
3692838531
*/
36929
-static LPWSTR winUtf8ToUnicode(const char *zFilename){
38532
+static LPWSTR winUtf8ToUnicode(const char *zText){
3693038533
int nChar;
36931
- LPWSTR zWideFilename;
38534
+ LPWSTR zWideText;
3693238535
36933
- nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
38536
+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
3693438537
if( nChar==0 ){
3693538538
return 0;
3693638539
}
36937
- zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
36938
- if( zWideFilename==0 ){
38540
+ zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38541
+ if( zWideText==0 ){
3693938542
return 0;
3694038543
}
36941
- nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
38544
+ nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
3694238545
nChar);
3694338546
if( nChar==0 ){
36944
- sqlite3_free(zWideFilename);
36945
- zWideFilename = 0;
38547
+ sqlite3_free(zWideText);
38548
+ zWideText = 0;
3694638549
}
36947
- return zWideFilename;
38550
+ return zWideText;
3694838551
}
3694938552
3695038553
/*
36951
-** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
36952
-** obtained from sqlite3_malloc().
38554
+** Convert a Microsoft Unicode string to UTF-8.
38555
+**
38556
+** Space to hold the returned string is obtained from sqlite3_malloc().
3695338557
*/
36954
-static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
38558
+static char *winUnicodeToUtf8(LPCWSTR zWideText){
3695538559
int nByte;
36956
- char *zFilename;
38560
+ char *zText;
3695738561
36958
- nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
38562
+ nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
3695938563
if( nByte == 0 ){
3696038564
return 0;
3696138565
}
36962
- zFilename = sqlite3MallocZero( nByte );
36963
- if( zFilename==0 ){
38566
+ zText = sqlite3MallocZero( nByte );
38567
+ if( zText==0 ){
3696438568
return 0;
3696538569
}
36966
- nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
38570
+ nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
3696738571
0, 0);
3696838572
if( nByte == 0 ){
36969
- sqlite3_free(zFilename);
36970
- zFilename = 0;
38573
+ sqlite3_free(zText);
38574
+ zText = 0;
3697138575
}
36972
- return zFilename;
38576
+ return zText;
3697338577
}
3697438578
3697538579
/*
36976
-** Convert an ANSI string to Microsoft Unicode, based on the
36977
-** current codepage settings for file apis.
38580
+** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38581
+** code page.
3697838582
**
36979
-** Space to hold the returned string is obtained
36980
-** from sqlite3_malloc.
38583
+** Space to hold the returned string is obtained from sqlite3_malloc().
3698138584
*/
36982
-static LPWSTR winMbcsToUnicode(const char *zFilename){
38585
+static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
3698338586
int nByte;
36984
- LPWSTR zMbcsFilename;
36985
- int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
38587
+ LPWSTR zMbcsText;
38588
+ int codepage = useAnsi ? CP_ACP : CP_OEMCP;
3698638589
36987
- nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
38590
+ nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
3698838591
0)*sizeof(WCHAR);
3698938592
if( nByte==0 ){
3699038593
return 0;
3699138594
}
36992
- zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
36993
- if( zMbcsFilename==0 ){
36994
- return 0;
36995
- }
36996
- nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
36997
- nByte);
36998
- if( nByte==0 ){
36999
- sqlite3_free(zMbcsFilename);
37000
- zMbcsFilename = 0;
37001
- }
37002
- return zMbcsFilename;
37003
-}
37004
-
37005
-/*
37006
-** Convert Microsoft Unicode to multi-byte character string, based on the
37007
-** user's ANSI codepage.
37008
-**
37009
-** Space to hold the returned string is obtained from
37010
-** sqlite3_malloc().
37011
-*/
37012
-static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
37013
- int nByte;
37014
- char *zFilename;
37015
- int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
37016
-
37017
- nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
37018
- if( nByte == 0 ){
37019
- return 0;
37020
- }
37021
- zFilename = sqlite3MallocZero( nByte );
37022
- if( zFilename==0 ){
37023
- return 0;
37024
- }
37025
- nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
37026
- nByte, 0, 0);
37027
- if( nByte == 0 ){
37028
- sqlite3_free(zFilename);
37029
- zFilename = 0;
37030
- }
37031
- return zFilename;
37032
-}
37033
-
37034
-/*
37035
-** Convert multibyte character string to UTF-8. Space to hold the
37036
-** returned string is obtained from sqlite3_malloc().
37037
-*/
37038
-SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
37039
- char *zFilenameUtf8;
37040
- LPWSTR zTmpWide;
37041
-
37042
- zTmpWide = winMbcsToUnicode(zFilename);
37043
- if( zTmpWide==0 ){
37044
- return 0;
37045
- }
37046
- zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
37047
- sqlite3_free(zTmpWide);
37048
- return zFilenameUtf8;
37049
-}
37050
-
37051
-/*
37052
-** Convert UTF-8 to multibyte character string. Space to hold the
37053
-** returned string is obtained from sqlite3_malloc().
37054
-*/
37055
-SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
37056
- char *zFilenameMbcs;
37057
- LPWSTR zTmpWide;
37058
-
37059
- zTmpWide = winUtf8ToUnicode(zFilename);
37060
- if( zTmpWide==0 ){
37061
- return 0;
37062
- }
37063
- zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
37064
- sqlite3_free(zTmpWide);
37065
- return zFilenameMbcs;
38595
+ zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38596
+ if( zMbcsText==0 ){
38597
+ return 0;
38598
+ }
38599
+ nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38600
+ nByte);
38601
+ if( nByte==0 ){
38602
+ sqlite3_free(zMbcsText);
38603
+ zMbcsText = 0;
38604
+ }
38605
+ return zMbcsText;
38606
+}
38607
+
38608
+/*
38609
+** Convert a Microsoft Unicode string to a multi-byte character string,
38610
+** using the ANSI or OEM code page.
38611
+**
38612
+** Space to hold the returned string is obtained from sqlite3_malloc().
38613
+*/
38614
+static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38615
+ int nByte;
38616
+ char *zText;
38617
+ int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38618
+
38619
+ nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38620
+ if( nByte == 0 ){
38621
+ return 0;
38622
+ }
38623
+ zText = sqlite3MallocZero( nByte );
38624
+ if( zText==0 ){
38625
+ return 0;
38626
+ }
38627
+ nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38628
+ nByte, 0, 0);
38629
+ if( nByte == 0 ){
38630
+ sqlite3_free(zText);
38631
+ zText = 0;
38632
+ }
38633
+ return zText;
38634
+}
38635
+
38636
+/*
38637
+** Convert a multi-byte character string to UTF-8.
38638
+**
38639
+** Space to hold the returned string is obtained from sqlite3_malloc().
38640
+*/
38641
+static char *winMbcsToUtf8(const char *zText, int useAnsi){
38642
+ char *zTextUtf8;
38643
+ LPWSTR zTmpWide;
38644
+
38645
+ zTmpWide = winMbcsToUnicode(zText, useAnsi);
38646
+ if( zTmpWide==0 ){
38647
+ return 0;
38648
+ }
38649
+ zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38650
+ sqlite3_free(zTmpWide);
38651
+ return zTextUtf8;
38652
+}
38653
+
38654
+/*
38655
+** Convert a UTF-8 string to a multi-byte character string.
38656
+**
38657
+** Space to hold the returned string is obtained from sqlite3_malloc().
38658
+*/
38659
+static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38660
+ char *zTextMbcs;
38661
+ LPWSTR zTmpWide;
38662
+
38663
+ zTmpWide = winUtf8ToUnicode(zText);
38664
+ if( zTmpWide==0 ){
38665
+ return 0;
38666
+ }
38667
+ zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38668
+ sqlite3_free(zTmpWide);
38669
+ return zTextMbcs;
38670
+}
38671
+
38672
+/*
38673
+** This is a public wrapper for the winUtf8ToUnicode() function.
38674
+*/
38675
+SQLITE_API LPWSTR SQLITE_STDCALL sqlite3_win32_utf8_to_unicode(const char *zText){
38676
+#ifdef SQLITE_ENABLE_API_ARMOR
38677
+ if( !zText ){
38678
+ (void)SQLITE_MISUSE_BKPT;
38679
+ return 0;
38680
+ }
38681
+#endif
38682
+#ifndef SQLITE_OMIT_AUTOINIT
38683
+ if( sqlite3_initialize() ) return 0;
38684
+#endif
38685
+ return winUtf8ToUnicode(zText);
38686
+}
38687
+
38688
+/*
38689
+** This is a public wrapper for the winUnicodeToUtf8() function.
38690
+*/
38691
+SQLITE_API char *SQLITE_STDCALL sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
38692
+#ifdef SQLITE_ENABLE_API_ARMOR
38693
+ if( !zWideText ){
38694
+ (void)SQLITE_MISUSE_BKPT;
38695
+ return 0;
38696
+ }
38697
+#endif
38698
+#ifndef SQLITE_OMIT_AUTOINIT
38699
+ if( sqlite3_initialize() ) return 0;
38700
+#endif
38701
+ return winUnicodeToUtf8(zWideText);
38702
+}
38703
+
38704
+/*
38705
+** This is a public wrapper for the winMbcsToUtf8() function.
38706
+*/
38707
+SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zText){
38708
+#ifdef SQLITE_ENABLE_API_ARMOR
38709
+ if( !zText ){
38710
+ (void)SQLITE_MISUSE_BKPT;
38711
+ return 0;
38712
+ }
38713
+#endif
38714
+#ifndef SQLITE_OMIT_AUTOINIT
38715
+ if( sqlite3_initialize() ) return 0;
38716
+#endif
38717
+ return winMbcsToUtf8(zText, osAreFileApisANSI());
38718
+}
38719
+
38720
+/*
38721
+** This is a public wrapper for the winMbcsToUtf8() function.
38722
+*/
38723
+SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
38724
+#ifdef SQLITE_ENABLE_API_ARMOR
38725
+ if( !zText ){
38726
+ (void)SQLITE_MISUSE_BKPT;
38727
+ return 0;
38728
+ }
38729
+#endif
38730
+#ifndef SQLITE_OMIT_AUTOINIT
38731
+ if( sqlite3_initialize() ) return 0;
38732
+#endif
38733
+ return winMbcsToUtf8(zText, useAnsi);
38734
+}
38735
+
38736
+/*
38737
+** This is a public wrapper for the winUtf8ToMbcs() function.
38738
+*/
38739
+SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zText){
38740
+#ifdef SQLITE_ENABLE_API_ARMOR
38741
+ if( !zText ){
38742
+ (void)SQLITE_MISUSE_BKPT;
38743
+ return 0;
38744
+ }
38745
+#endif
38746
+#ifndef SQLITE_OMIT_AUTOINIT
38747
+ if( sqlite3_initialize() ) return 0;
38748
+#endif
38749
+ return winUtf8ToMbcs(zText, osAreFileApisANSI());
38750
+}
38751
+
38752
+/*
38753
+** This is a public wrapper for the winUtf8ToMbcs() function.
38754
+*/
38755
+SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
38756
+#ifdef SQLITE_ENABLE_API_ARMOR
38757
+ if( !zText ){
38758
+ (void)SQLITE_MISUSE_BKPT;
38759
+ return 0;
38760
+ }
38761
+#endif
38762
+#ifndef SQLITE_OMIT_AUTOINIT
38763
+ if( sqlite3_initialize() ) return 0;
38764
+#endif
38765
+ return winUtf8ToMbcs(zText, useAnsi);
3706638766
}
3706738767
3706838768
/*
3706938769
** This function sets the data directory or the temporary directory based on
3707038770
** the provided arguments. The type argument must be 1 in order to set the
@@ -37162,11 +38862,11 @@
3716238862
0,
3716338863
0);
3716438864
if( dwLen > 0 ){
3716538865
/* allocate a buffer and convert to UTF8 */
3716638866
sqlite3BeginBenignMalloc();
37167
- zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
38867
+ zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
3716838868
sqlite3EndBenignMalloc();
3716938869
/* free the system buffer allocated by FormatMessage */
3717038870
osLocalFree(zTemp);
3717138871
}
3717238872
}
@@ -37304,20 +39004,21 @@
3730439004
winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
3730539005
);
3730639006
}
3730739007
}
3730839008
37309
-#if SQLITE_OS_WINCE
37310
-/*************************************************************************
37311
-** This section contains code for WinCE only.
37312
-*/
37313
-#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
37314
-/*
37315
-** The MSVC CRT on Windows CE may not have a localtime() function. So
37316
-** create a substitute.
37317
-*/
37318
-/* #include <time.h> */
39009
+/*
39010
+** This #if does not rely on the SQLITE_OS_WINCE define because the
39011
+** corresponding section in "date.c" cannot use it.
39012
+*/
39013
+#if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39014
+ (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39015
+/*
39016
+** The MSVC CRT on Windows CE may not have a localtime() function.
39017
+** So define a substitute.
39018
+*/
39019
+/* # include <time.h> */
3731939020
struct tm *__cdecl localtime(const time_t *t)
3732039021
{
3732139022
static struct tm y;
3732239023
FILETIME uTm, lTm;
3732339024
SYSTEMTIME pTm;
@@ -37337,10 +39038,14 @@
3733739038
y.tm_sec = pTm.wSecond;
3733839039
return &y;
3733939040
}
3734039041
#endif
3734139042
39043
+#if SQLITE_OS_WINCE
39044
+/*************************************************************************
39045
+** This section contains code for WinCE only.
39046
+*/
3734239047
#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
3734339048
3734439049
/*
3734539050
** Acquire a lock on the handle h
3734639051
*/
@@ -38350,13 +40055,12 @@
3835040055
/* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
3835140056
** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
3835240057
** the PENDING_LOCK byte is temporary.
3835340058
*/
3835440059
newLocktype = pFile->locktype;
38355
- if( (pFile->locktype==NO_LOCK)
38356
- || ( (locktype==EXCLUSIVE_LOCK)
38357
- && (pFile->locktype==RESERVED_LOCK))
40060
+ if( pFile->locktype==NO_LOCK
40061
+ || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
3835840062
){
3835940063
int cnt = 3;
3836040064
while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
3836140065
PENDING_BYTE, 0, 1, 0))==0 ){
3836240066
/* Try 3 times to get the pending lock. This is needed to work
@@ -38946,14 +40650,16 @@
3894640650
pNew = 0;
3894740651
((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
3894840652
pShmNode->pNext = winShmNodeList;
3894940653
winShmNodeList = pShmNode;
3895040654
38951
- pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
38952
- if( pShmNode->mutex==0 ){
38953
- rc = SQLITE_IOERR_NOMEM_BKPT;
38954
- goto shm_open_err;
40655
+ if( sqlite3GlobalConfig.bCoreMutex ){
40656
+ pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
40657
+ if( pShmNode->mutex==0 ){
40658
+ rc = SQLITE_IOERR_NOMEM_BKPT;
40659
+ goto shm_open_err;
40660
+ }
3895540661
}
3895640662
3895740663
rc = winOpen(pDbFd->pVfs,
3895840664
pShmNode->zFilename, /* Name of the file (UTF-8) */
3895940665
(sqlite3_file*)&pShmNode->hFile, /* File handle here */
@@ -39607,11 +41313,11 @@
3960741313
if( osIsNT() ){
3960841314
zConverted = winUnicodeToUtf8(zFilename);
3960941315
}
3961041316
#ifdef SQLITE_WIN32_HAS_ANSI
3961141317
else{
39612
- zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
41318
+ zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
3961341319
}
3961441320
#endif
3961541321
/* caller will handle out of memory */
3961641322
return zConverted;
3961741323
}
@@ -39628,11 +41334,11 @@
3962841334
if( osIsNT() ){
3962941335
zConverted = winUtf8ToUnicode(zFilename);
3963041336
}
3963141337
#ifdef SQLITE_WIN32_HAS_ANSI
3963241338
else{
39633
- zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
41339
+ zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
3963441340
}
3963541341
#endif
3963641342
/* caller will handle out of memory */
3963741343
return zConverted;
3963841344
}
@@ -39829,11 +41535,11 @@
3982941535
sqlite3_free(zBuf);
3983041536
OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
3983141537
return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
3983241538
"winGetTempname3", 0);
3983341539
}
39834
- zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
41540
+ zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
3983541541
if( zUtf8 ){
3983641542
sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
3983741543
sqlite3_free(zUtf8);
3983841544
}else{
3983941545
sqlite3_free(zBuf);
@@ -40607,11 +42313,11 @@
4060742313
sqlite3_free(zTemp);
4060842314
return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
4060942315
"winFullPathname4", zRelative);
4061042316
}
4061142317
sqlite3_free(zConverted);
40612
- zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
42318
+ zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
4061342319
sqlite3_free(zTemp);
4061442320
}
4061542321
#endif
4061642322
if( zOut ){
4061742323
sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
@@ -41413,11 +43119,33 @@
4141343119
** This file implements that page cache.
4141443120
*/
4141543121
/* #include "sqliteInt.h" */
4141643122
4141743123
/*
41418
-** A complete page cache is an instance of this structure.
43124
+** A complete page cache is an instance of this structure. Every
43125
+** entry in the cache holds a single page of the database file. The
43126
+** btree layer only operates on the cached copy of the database pages.
43127
+**
43128
+** A page cache entry is "clean" if it exactly matches what is currently
43129
+** on disk. A page is "dirty" if it has been modified and needs to be
43130
+** persisted to disk.
43131
+**
43132
+** pDirty, pDirtyTail, pSynced:
43133
+** All dirty pages are linked into the doubly linked list using
43134
+** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43135
+** such that p was added to the list more recently than p->pDirtyNext.
43136
+** PCache.pDirty points to the first (newest) element in the list and
43137
+** pDirtyTail to the last (oldest).
43138
+**
43139
+** The PCache.pSynced variable is used to optimize searching for a dirty
43140
+** page to eject from the cache mid-transaction. It is better to eject
43141
+** a page that does not require a journal sync than one that does.
43142
+** Therefore, pSynced is maintained to that it *almost* always points
43143
+** to either the oldest page in the pDirty/pDirtyTail list that has a
43144
+** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43145
+** (so that the right page to eject can be found by following pDirtyPrev
43146
+** pointers).
4141943147
*/
4142043148
struct PCache {
4142143149
PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
4142243150
PgHdr *pSynced; /* Last synced page in dirty page list */
4142343151
int nRefSum; /* Sum of ref counts over all pages */
@@ -41429,10 +43157,99 @@
4142943157
u8 eCreate; /* eCreate value for for xFetch() */
4143043158
int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
4143143159
void *pStress; /* Argument to xStress */
4143243160
sqlite3_pcache *pCache; /* Pluggable cache module */
4143343161
};
43162
+
43163
+/********************************** Test and Debug Logic **********************/
43164
+/*
43165
+** Debug tracing macros. Enable by by changing the "0" to "1" and
43166
+** recompiling.
43167
+**
43168
+** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43169
+** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43170
+** is displayed for many operations, resulting in a lot of output.
43171
+*/
43172
+#if defined(SQLITE_DEBUG) && 0
43173
+ int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
43174
+ int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
43175
+# define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43176
+ void pcacheDump(PCache *pCache){
43177
+ int N;
43178
+ int i, j;
43179
+ sqlite3_pcache_page *pLower;
43180
+ PgHdr *pPg;
43181
+ unsigned char *a;
43182
+
43183
+ if( sqlite3PcacheTrace<2 ) return;
43184
+ if( pCache->pCache==0 ) return;
43185
+ N = sqlite3PcachePagecount(pCache);
43186
+ if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43187
+ for(i=1; i<=N; i++){
43188
+ pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43189
+ if( pLower==0 ) continue;
43190
+ pPg = (PgHdr*)pLower->pExtra;
43191
+ printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43192
+ a = (unsigned char *)pLower->pBuf;
43193
+ for(j=0; j<12; j++) printf("%02x", a[j]);
43194
+ printf("\n");
43195
+ if( pPg->pPage==0 ){
43196
+ sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43197
+ }
43198
+ }
43199
+ }
43200
+ #else
43201
+# define pcacheTrace(X)
43202
+# define pcacheDump(X)
43203
+#endif
43204
+
43205
+/*
43206
+** Check invariants on a PgHdr entry. Return true if everything is OK.
43207
+** Return false if any invariant is violated.
43208
+**
43209
+** This routine is for use inside of assert() statements only. For
43210
+** example:
43211
+**
43212
+** assert( sqlite3PcachePageSanity(pPg) );
43213
+*/
43214
+#if SQLITE_DEBUG
43215
+SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43216
+ PCache *pCache;
43217
+ assert( pPg!=0 );
43218
+ assert( pPg->pgno>0 ); /* Page number is 1 or more */
43219
+ pCache = pPg->pCache;
43220
+ assert( pCache!=0 ); /* Every page has an associated PCache */
43221
+ if( pPg->flags & PGHDR_CLEAN ){
43222
+ assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43223
+ assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
43224
+ assert( pCache->pDirtyTail!=pPg );
43225
+ }
43226
+ /* WRITEABLE pages must also be DIRTY */
43227
+ if( pPg->flags & PGHDR_WRITEABLE ){
43228
+ assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
43229
+ }
43230
+ /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
43231
+ ** for example, when using the sqlite3PagerDontWrite() optimization:
43232
+ ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43233
+ ** (2) Page X moved to freelist, WRITEABLE is cleared
43234
+ ** (3) Page X reused, WRITEABLE is set again
43235
+ ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43236
+ ** in step 3, and page might be written into the database without first
43237
+ ** syncing the rollback journal, which might cause corruption on a power
43238
+ ** loss.
43239
+ **
43240
+ ** Another example is when the database page size is smaller than the
43241
+ ** disk sector size. When any page of a sector is journalled, all pages
43242
+ ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43243
+ ** in case they are later modified, since all pages in the same sector
43244
+ ** must be journalled and synced before any of those pages can be safely
43245
+ ** written.
43246
+ */
43247
+ return 1;
43248
+}
43249
+#endif /* SQLITE_DEBUG */
43250
+
4143443251
4143543252
/********************************** Linked List Management ********************/
4143643253
4143743254
/* Allowed values for second argument to pcacheManageDirtyList() */
4143843255
#define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
@@ -41446,21 +43263,20 @@
4144643263
** the dirty list. Doing both moves pPage to the front of the dirty list.
4144743264
*/
4144843265
static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
4144943266
PCache *p = pPage->pCache;
4145043267
43268
+ pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43269
+ addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43270
+ pPage->pgno));
4145143271
if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
4145243272
assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
4145343273
assert( pPage->pDirtyPrev || pPage==p->pDirty );
4145443274
4145543275
/* Update the PCache1.pSynced variable if necessary. */
4145643276
if( p->pSynced==pPage ){
41457
- PgHdr *pSynced = pPage->pDirtyPrev;
41458
- while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
41459
- pSynced = pSynced->pDirtyPrev;
41460
- }
41461
- p->pSynced = pSynced;
43277
+ p->pSynced = pPage->pDirtyPrev;
4146243278
}
4146343279
4146443280
if( pPage->pDirtyNext ){
4146543281
pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
4146643282
}else{
@@ -41468,14 +43284,19 @@
4146843284
p->pDirtyTail = pPage->pDirtyPrev;
4146943285
}
4147043286
if( pPage->pDirtyPrev ){
4147143287
pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
4147243288
}else{
43289
+ /* If there are now no dirty pages in the cache, set eCreate to 2.
43290
+ ** This is an optimization that allows sqlite3PcacheFetch() to skip
43291
+ ** searching for a dirty page to eject from the cache when it might
43292
+ ** otherwise have to. */
4147343293
assert( pPage==p->pDirty );
4147443294
p->pDirty = pPage->pDirtyNext;
41475
- if( p->pDirty==0 && p->bPurgeable ){
41476
- assert( p->eCreate==1 );
43295
+ assert( p->bPurgeable || p->eCreate==2 );
43296
+ if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
43297
+ assert( p->bPurgeable==0 || p->eCreate==1 );
4147743298
p->eCreate = 2;
4147843299
}
4147943300
}
4148043301
pPage->pDirtyNext = 0;
4148143302
pPage->pDirtyPrev = 0;
@@ -41493,23 +43314,34 @@
4149343314
assert( p->eCreate==2 );
4149443315
p->eCreate = 1;
4149543316
}
4149643317
}
4149743318
p->pDirty = pPage;
41498
- if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
43319
+
43320
+ /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43321
+ ** pSynced to point to it. Checking the NEED_SYNC flag is an
43322
+ ** optimization, as if pSynced points to a page with the NEED_SYNC
43323
+ ** flag set sqlite3PcacheFetchStress() searches through all newer
43324
+ ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
43325
+ if( !p->pSynced
43326
+ && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
43327
+ ){
4149943328
p->pSynced = pPage;
4150043329
}
4150143330
}
43331
+ pcacheDump(p);
4150243332
}
4150343333
4150443334
/*
4150543335
** Wrapper around the pluggable caches xUnpin method. If the cache is
4150643336
** being used for an in-memory database, this function is a no-op.
4150743337
*/
4150843338
static void pcacheUnpin(PgHdr *p){
4150943339
if( p->pCache->bPurgeable ){
43340
+ pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
4151043341
sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43342
+ pcacheDump(p->pCache);
4151143343
}
4151243344
}
4151343345
4151443346
/*
4151543347
** Compute the number of pages of cache requested. p->szCache is the
@@ -41575,10 +43407,11 @@
4157543407
p->eCreate = 2;
4157643408
p->xStress = xStress;
4157743409
p->pStress = pStress;
4157843410
p->szCache = 100;
4157943411
p->szSpill = 1;
43412
+ pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
4158043413
return sqlite3PcacheSetPageSize(p, szPage);
4158143414
}
4158243415
4158343416
/*
4158443417
** Change the page size for PCache object. The caller must ensure that there
@@ -41597,10 +43430,11 @@
4159743430
if( pCache->pCache ){
4159843431
sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
4159943432
}
4160043433
pCache->pCache = pNew;
4160143434
pCache->szPage = szPage;
43435
+ pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
4160243436
}
4160343437
return SQLITE_OK;
4160443438
}
4160543439
4160643440
/*
@@ -41631,15 +43465,17 @@
4163143465
PCache *pCache, /* Obtain the page from this cache */
4163243466
Pgno pgno, /* Page number to obtain */
4163343467
int createFlag /* If true, create page if it does not exist already */
4163443468
){
4163543469
int eCreate;
43470
+ sqlite3_pcache_page *pRes;
4163643471
4163743472
assert( pCache!=0 );
4163843473
assert( pCache->pCache!=0 );
4163943474
assert( createFlag==3 || createFlag==0 );
4164043475
assert( pgno>0 );
43476
+ assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
4164143477
4164243478
/* eCreate defines what to do if the page does not exist.
4164343479
** 0 Do not allocate a new page. (createFlag==0)
4164443480
** 1 Allocate a new page if doing so is inexpensive.
4164543481
** (createFlag==1 AND bPurgeable AND pDirty)
@@ -41648,16 +43484,19 @@
4164843484
*/
4164943485
eCreate = createFlag & pCache->eCreate;
4165043486
assert( eCreate==0 || eCreate==1 || eCreate==2 );
4165143487
assert( createFlag==0 || pCache->eCreate==eCreate );
4165243488
assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
41653
- return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43489
+ pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43490
+ pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43491
+ createFlag?" create":"",pRes));
43492
+ return pRes;
4165443493
}
4165543494
4165643495
/*
4165743496
** If the sqlite3PcacheFetch() routine is unable to allocate a new
41658
-** page because new clean pages are available for reuse and the cache
43497
+** page because no clean pages are available for reuse and the cache
4165943498
** size limit has been reached, then this routine can be invoked to
4166043499
** try harder to allocate a page. This routine might invoke the stress
4166143500
** callback to spill dirty pages to the journal. It will then try to
4166243501
** allocate the new page and will only fail to allocate a new page on
4166343502
** an OOM error.
@@ -41675,11 +43514,15 @@
4167543514
if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
4167643515
/* Find a dirty page to write-out and recycle. First try to find a
4167743516
** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
4167843517
** cleared), but if that is not possible settle for any other
4167943518
** unreferenced dirty page.
41680
- */
43519
+ **
43520
+ ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43521
+ ** flag is currently referenced, then the following may leave pSynced
43522
+ ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43523
+ ** cleared). This is Ok, as pSynced is just an optimization. */
4168143524
for(pPg=pCache->pSynced;
4168243525
pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
4168343526
pPg=pPg->pDirtyPrev
4168443527
);
4168543528
pCache->pSynced = pPg;
@@ -41693,11 +43536,13 @@
4169343536
"spill page %d making room for %d - cache used: %d/%d",
4169443537
pPg->pgno, pgno,
4169543538
sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
4169643539
numberOfCachePages(pCache));
4169743540
#endif
43541
+ pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
4169843542
rc = pCache->xStress(pCache->pStress, pPg);
43543
+ pcacheDump(pCache);
4169943544
if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
4170043545
return rc;
4170143546
}
4170243547
}
4170343548
}
@@ -41753,10 +43598,11 @@
4175343598
if( !pPgHdr->pPage ){
4175443599
return pcacheFetchFinishWithInit(pCache, pgno, pPage);
4175543600
}
4175643601
pCache->nRefSum++;
4175743602
pPgHdr->nRef++;
43603
+ assert( sqlite3PcachePageSanity(pPgHdr) );
4175843604
return pPgHdr;
4175943605
}
4176043606
4176143607
/*
4176243608
** Decrement the reference count on a page. If the page is clean and the
@@ -41766,12 +43612,15 @@
4176643612
assert( p->nRef>0 );
4176743613
p->pCache->nRefSum--;
4176843614
if( (--p->nRef)==0 ){
4176943615
if( p->flags&PGHDR_CLEAN ){
4177043616
pcacheUnpin(p);
41771
- }else if( p->pDirtyPrev!=0 ){
41772
- /* Move the page to the head of the dirty list. */
43617
+ }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
43618
+ /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
43619
+ ** then page p is already at the head of the dirty list and the
43620
+ ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
43621
+ ** tag above. */
4177343622
pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
4177443623
}
4177543624
}
4177643625
}
4177743626
@@ -41778,10 +43627,11 @@
4177843627
/*
4177943628
** Increase the reference count of a supplied page by 1.
4178043629
*/
4178143630
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
4178243631
assert(p->nRef>0);
43632
+ assert( sqlite3PcachePageSanity(p) );
4178343633
p->nRef++;
4178443634
p->pCache->nRefSum++;
4178543635
}
4178643636
4178743637
/*
@@ -41789,10 +43639,11 @@
4178943639
** page. This function deletes that reference, so after it returns the
4179043640
** page pointed to by p is invalid.
4179143641
*/
4179243642
SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
4179343643
assert( p->nRef==1 );
43644
+ assert( sqlite3PcachePageSanity(p) );
4179443645
if( p->flags&PGHDR_DIRTY ){
4179543646
pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
4179643647
}
4179743648
p->pCache->nRefSum--;
4179843649
sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
@@ -41802,30 +43653,36 @@
4180243653
** Make sure the page is marked as dirty. If it isn't dirty already,
4180343654
** make it so.
4180443655
*/
4180543656
SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
4180643657
assert( p->nRef>0 );
41807
- if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
43658
+ assert( sqlite3PcachePageSanity(p) );
43659
+ if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
4180843660
p->flags &= ~PGHDR_DONT_WRITE;
4180943661
if( p->flags & PGHDR_CLEAN ){
4181043662
p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
43663
+ pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
4181143664
assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
4181243665
pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
4181343666
}
43667
+ assert( sqlite3PcachePageSanity(p) );
4181443668
}
4181543669
}
4181643670
4181743671
/*
4181843672
** Make sure the page is marked as clean. If it isn't clean already,
4181943673
** make it so.
4182043674
*/
4182143675
SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
41822
- if( (p->flags & PGHDR_DIRTY) ){
43676
+ assert( sqlite3PcachePageSanity(p) );
43677
+ if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
4182343678
assert( (p->flags & PGHDR_CLEAN)==0 );
4182443679
pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
4182543680
p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
4182643681
p->flags |= PGHDR_CLEAN;
43682
+ pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
43683
+ assert( sqlite3PcachePageSanity(p) );
4182743684
if( p->nRef==0 ){
4182843685
pcacheUnpin(p);
4182943686
}
4183043687
}
4183143688
}
@@ -41833,14 +43690,27 @@
4183343690
/*
4183443691
** Make every page in the cache clean.
4183543692
*/
4183643693
SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
4183743694
PgHdr *p;
43695
+ pcacheTrace(("%p.CLEAN-ALL\n",pCache));
4183843696
while( (p = pCache->pDirty)!=0 ){
4183943697
sqlite3PcacheMakeClean(p);
4184043698
}
4184143699
}
43700
+
43701
+/*
43702
+** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
43703
+*/
43704
+SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
43705
+ PgHdr *p;
43706
+ pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
43707
+ for(p=pCache->pDirty; p; p=p->pDirtyNext){
43708
+ p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
43709
+ }
43710
+ pCache->pSynced = pCache->pDirtyTail;
43711
+}
4184243712
4184343713
/*
4184443714
** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
4184543715
*/
4184643716
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
@@ -41856,10 +43726,12 @@
4185643726
*/
4185743727
SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
4185843728
PCache *pCache = p->pCache;
4185943729
assert( p->nRef>0 );
4186043730
assert( newPgno>0 );
43731
+ assert( sqlite3PcachePageSanity(p) );
43732
+ pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
4186143733
sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
4186243734
p->pgno = newPgno;
4186343735
if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
4186443736
pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
4186543737
}
@@ -41876,18 +43748,19 @@
4187643748
*/
4187743749
SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
4187843750
if( pCache->pCache ){
4187943751
PgHdr *p;
4188043752
PgHdr *pNext;
43753
+ pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
4188143754
for(p=pCache->pDirty; p; p=pNext){
4188243755
pNext = p->pDirtyNext;
4188343756
/* This routine never gets call with a positive pgno except right
4188443757
** after sqlite3PcacheCleanAll(). So if there are dirty pages,
4188543758
** it must be that pgno==0.
4188643759
*/
4188743760
assert( p->pgno>0 );
41888
- if( ALWAYS(p->pgno>pgno) ){
43761
+ if( p->pgno>pgno ){
4188943762
assert( p->flags&PGHDR_DIRTY );
4189043763
sqlite3PcacheMakeClean(p);
4189143764
}
4189243765
}
4189343766
if( pgno==0 && pCache->nRefSum ){
@@ -41906,10 +43779,11 @@
4190643779
/*
4190743780
** Close a cache.
4190843781
*/
4190943782
SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
4191043783
assert( pCache->pCache!=0 );
43784
+ pcacheTrace(("%p.CLOSE\n",pCache));
4191143785
sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
4191243786
}
4191343787
4191443788
/*
4191543789
** Discard the contents of the cache.
@@ -42074,10 +43948,21 @@
4207443948
** Return the size of the header added by this middleware layer
4207543949
** in the page-cache hierarchy.
4207643950
*/
4207743951
SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
4207843952
43953
+/*
43954
+** Return the number of dirty pages currently in the cache, as a percentage
43955
+** of the configured cache size.
43956
+*/
43957
+SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
43958
+ PgHdr *pDirty;
43959
+ int nDirty = 0;
43960
+ int nCache = numberOfCachePages(pCache);
43961
+ for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
43962
+ return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
43963
+}
4207943964
4208043965
#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
4208143966
/*
4208243967
** For all dirty pages currently in the cache, invoke the specified
4208343968
** callback. This is only used if the SQLITE_CHECK_PAGES macro is
@@ -42783,12 +44668,12 @@
4278344668
pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
4278444669
#endif
4278544670
4278644671
#if SQLITE_THREADSAFE
4278744672
if( sqlite3GlobalConfig.bCoreMutex ){
42788
- pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
42789
- pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
44673
+ pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
44674
+ pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
4279044675
}
4279144676
#endif
4279244677
if( pcache1.separateCache
4279344678
&& sqlite3GlobalConfig.nPage!=0
4279444679
&& sqlite3GlobalConfig.pPage==0
@@ -43390,12 +45275,13 @@
4339045275
** batch number is O(NlogN) where N is the number of elements in the RowSet.
4339145276
** The cost of a TEST using the same batch number is O(logN). The cost
4339245277
** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
4339345278
** primitives are constant time. The cost of DESTROY is O(N).
4339445279
**
43395
-** There is an added cost of O(N) when switching between TEST and
43396
-** SMALLEST primitives.
45280
+** TEST and SMALLEST may not be used by the same RowSet. This used to
45281
+** be possible, but the feature was not used, so it was removed in order
45282
+** to simplify the code.
4339745283
*/
4339845284
/* #include "sqliteInt.h" */
4339945285
4340045286
4340145287
/*
@@ -43512,11 +45398,13 @@
4351245398
** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
4351345399
** routine returns NULL.
4351445400
*/
4351545401
static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
4351645402
assert( p!=0 );
43517
- if( p->nFresh==0 ){
45403
+ if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
45404
+ /* We could allocate a fresh RowSetEntry each time one is needed, but it
45405
+ ** is more efficient to pull a preallocated entry from the pool */
4351845406
struct RowSetChunk *pNew;
4351945407
pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
4352045408
if( pNew==0 ){
4352145409
return 0;
4352245410
}
@@ -43546,11 +45434,13 @@
4354645434
if( pEntry==0 ) return;
4354745435
pEntry->v = rowid;
4354845436
pEntry->pRight = 0;
4354945437
pLast = p->pLast;
4355045438
if( pLast ){
43551
- if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
45439
+ if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
45440
+ /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45441
+ ** where possible */
4355245442
p->rsFlags &= ~ROWSET_SORTED;
4355345443
}
4355445444
pLast->pRight = pEntry;
4355545445
}else{
4355645446
p->pEntry = pEntry;
@@ -43668,27 +45558,33 @@
4366845558
struct RowSetEntry **ppList,
4366945559
int iDepth
4367045560
){
4367145561
struct RowSetEntry *p; /* Root of the new tree */
4367245562
struct RowSetEntry *pLeft; /* Left subtree */
43673
- if( *ppList==0 ){
43674
- return 0;
45563
+ if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45564
+ /* Prevent unnecessary deep recursion when we run out of entries */
45565
+ return 0;
4367545566
}
43676
- if( iDepth==1 ){
45567
+ if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
45568
+ /* This branch causes a *balanced* tree to be generated. A valid tree
45569
+ ** is still generated without this branch, but the tree is wildly
45570
+ ** unbalanced and inefficient. */
45571
+ pLeft = rowSetNDeepTree(ppList, iDepth-1);
45572
+ p = *ppList;
45573
+ if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
45574
+ /* It is safe to always return here, but the resulting tree
45575
+ ** would be unbalanced */
45576
+ return pLeft;
45577
+ }
45578
+ p->pLeft = pLeft;
45579
+ *ppList = p->pRight;
45580
+ p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45581
+ }else{
4367745582
p = *ppList;
4367845583
*ppList = p->pRight;
4367945584
p->pLeft = p->pRight = 0;
43680
- return p;
43681
- }
43682
- pLeft = rowSetNDeepTree(ppList, iDepth-1);
43683
- p = *ppList;
43684
- if( p==0 ){
43685
- return pLeft;
43686
- }
43687
- p->pLeft = pLeft;
43688
- *ppList = p->pRight;
43689
- p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45585
+ }
4369045586
return p;
4369145587
}
4369245588
4369345589
/*
4369445590
** Convert a sorted list of elements into a binary tree. Make the tree
@@ -43711,63 +45607,41 @@
4371145607
p->pRight = rowSetNDeepTree(&pList, iDepth);
4371245608
}
4371345609
return p;
4371445610
}
4371545611
43716
-/*
43717
-** Take all the entries on p->pEntry and on the trees in p->pForest and
43718
-** sort them all together into one big ordered list on p->pEntry.
43719
-**
43720
-** This routine should only be called once in the life of a RowSet.
43721
-*/
43722
-static void rowSetToList(RowSet *p){
43723
-
43724
- /* This routine is called only once */
43725
- assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
43726
-
43727
- if( (p->rsFlags & ROWSET_SORTED)==0 ){
43728
- p->pEntry = rowSetEntrySort(p->pEntry);
43729
- }
43730
-
43731
- /* While this module could theoretically support it, sqlite3RowSetNext()
43732
- ** is never called after sqlite3RowSetText() for the same RowSet. So
43733
- ** there is never a forest to deal with. Should this change, simply
43734
- ** remove the assert() and the #if 0. */
43735
- assert( p->pForest==0 );
43736
-#if 0
43737
- while( p->pForest ){
43738
- struct RowSetEntry *pTree = p->pForest->pLeft;
43739
- if( pTree ){
43740
- struct RowSetEntry *pHead, *pTail;
43741
- rowSetTreeToList(pTree, &pHead, &pTail);
43742
- p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
43743
- }
43744
- p->pForest = p->pForest->pRight;
43745
- }
43746
-#endif
43747
- p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
43748
-}
43749
-
4375045612
/*
4375145613
** Extract the smallest element from the RowSet.
4375245614
** Write the element into *pRowid. Return 1 on success. Return
4375345615
** 0 if the RowSet is already empty.
4375445616
**
4375545617
** After this routine has been called, the sqlite3RowSetInsert()
43756
-** routine may not be called again.
45618
+** routine may not be called again.
45619
+**
45620
+** This routine may not be called after sqlite3RowSetTest() has
45621
+** been used. Older versions of RowSet allowed that, but as the
45622
+** capability was not used by the code generator, it was removed
45623
+** for code economy.
4375745624
*/
4375845625
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
4375945626
assert( p!=0 );
45627
+ assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
4376045628
4376145629
/* Merge the forest into a single sorted list on first call */
43762
- if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
45630
+ if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45631
+ if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45632
+ p->pEntry = rowSetEntrySort(p->pEntry);
45633
+ }
45634
+ p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
45635
+ }
4376345636
4376445637
/* Return the next entry on the list */
4376545638
if( p->pEntry ){
4376645639
*pRowid = p->pEntry->v;
4376745640
p->pEntry = p->pEntry->pRight;
43768
- if( p->pEntry==0 ){
45641
+ if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
45642
+ /* Free memory immediately, rather than waiting on sqlite3_finalize() */
4376945643
sqlite3RowSetClear(p);
4377045644
}
4377145645
return 1;
4377245646
}else{
4377345647
return 0;
@@ -43786,17 +45660,19 @@
4378645660
struct RowSetEntry *p, *pTree;
4378745661
4378845662
/* This routine is never called after sqlite3RowSetNext() */
4378945663
assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
4379045664
43791
- /* Sort entries into the forest on the first test of a new batch
45665
+ /* Sort entries into the forest on the first test of a new batch.
45666
+ ** To save unnecessary work, only do this when the batch number changes.
4379245667
*/
43793
- if( iBatch!=pRowSet->iBatch ){
45668
+ if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
4379445669
p = pRowSet->pEntry;
4379545670
if( p ){
4379645671
struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
43797
- if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
45672
+ if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45673
+ /* Only sort the current set of entiries if they need it */
4379845674
p = rowSetEntrySort(p);
4379945675
}
4380045676
for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
4380145677
ppPrevTree = &pTree->pRight;
4380245678
if( pTree->pLeft==0 ){
@@ -44866,10 +46742,11 @@
4486646742
** return SQLITE_IOERR_NOMEM while the journal file is being written). It
4486746743
** is therefore not possible for an in-memory pager to enter the ERROR
4486846744
** state.
4486946745
*/
4487046746
if( MEMDB ){
46747
+ assert( !isOpen(p->fd) );
4487146748
assert( p->noSync );
4487246749
assert( p->journalMode==PAGER_JOURNALMODE_OFF
4487346750
|| p->journalMode==PAGER_JOURNALMODE_MEMORY
4487446751
);
4487546752
assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
@@ -44952,11 +46829,11 @@
4495246829
/* There must be at least one outstanding reference to the pager if
4495346830
** in ERROR state. Otherwise the pager should have already dropped
4495446831
** back to OPEN state.
4495546832
*/
4495646833
assert( pPager->errCode!=SQLITE_OK );
44957
- assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
46834
+ assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
4495846835
break;
4495946836
}
4496046837
4496146838
return 1;
4496246839
}
@@ -45164,10 +47041,12 @@
4516447041
}
4516547042
}
4516647043
4516747044
return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
4516847045
}
47046
+#else
47047
+# define jrnlBufferSize(x) 0
4516947048
#endif
4517047049
4517147050
/*
4517247051
** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
4517347052
** on the cache using a hash function. This is used for testing
@@ -45812,17 +47691,21 @@
4581247691
/* If Pager.errCode is set, the contents of the pager cache cannot be
4581347692
** trusted. Now that there are no outstanding references to the pager,
4581447693
** it can safely move back to PAGER_OPEN state. This happens in both
4581547694
** normal and exclusive-locking mode.
4581647695
*/
47696
+ assert( pPager->errCode==SQLITE_OK || !MEMDB );
4581747697
if( pPager->errCode ){
45818
- assert( !MEMDB );
45819
- pager_reset(pPager);
45820
- pPager->changeCountDone = pPager->tempFile;
45821
- pPager->eState = PAGER_OPEN;
45822
- pPager->errCode = SQLITE_OK;
47698
+ if( pPager->tempFile==0 ){
47699
+ pager_reset(pPager);
47700
+ pPager->changeCountDone = 0;
47701
+ pPager->eState = PAGER_OPEN;
47702
+ }else{
47703
+ pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
47704
+ }
4582347705
if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
47706
+ pPager->errCode = SQLITE_OK;
4582447707
}
4582547708
4582647709
pPager->journalOff = 0;
4582747710
pPager->journalHdr = 0;
4582847711
pPager->setMaster = 0;
@@ -45861,10 +47744,33 @@
4586147744
}
4586247745
return rc;
4586347746
}
4586447747
4586547748
static int pager_truncate(Pager *pPager, Pgno nPage);
47749
+
47750
+/*
47751
+** The write transaction open on pPager is being committed (bCommit==1)
47752
+** or rolled back (bCommit==0).
47753
+**
47754
+** Return TRUE if and only if all dirty pages should be flushed to disk.
47755
+**
47756
+** Rules:
47757
+**
47758
+** * For non-TEMP databases, always sync to disk. This is necessary
47759
+** for transactions to be durable.
47760
+**
47761
+** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
47762
+** file has been created already (via a spill on pagerStress()) and
47763
+** when the number of dirty pages in memory exceeds 25% of the total
47764
+** cache size.
47765
+*/
47766
+static int pagerFlushOnCommit(Pager *pPager, int bCommit){
47767
+ if( pPager->tempFile==0 ) return 1;
47768
+ if( !bCommit ) return 0;
47769
+ if( !isOpen(pPager->fd) ) return 0;
47770
+ return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
47771
+}
4586647772
4586747773
/*
4586847774
** This routine ends a transaction. A transaction is usually ended by
4586947775
** either a COMMIT or a ROLLBACK operation. This routine may be called
4587047776
** after rollback of a hot-journal, or if an error occurs while opening
@@ -45965,11 +47871,11 @@
4596547871
}
4596647872
pPager->journalOff = 0;
4596747873
}else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
4596847874
|| (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
4596947875
){
45970
- rc = zeroJournalHdr(pPager, hasMaster);
47876
+ rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
4597147877
pPager->journalOff = 0;
4597247878
}else{
4597347879
/* This branch may be executed with Pager.journalMode==MEMORY if
4597447880
** a hot-journal was just rolled back. In this case the journal
4597547881
** file should be closed and deleted. If this connection writes to
@@ -46000,12 +47906,18 @@
4600047906
#endif
4600147907
4600247908
sqlite3BitvecDestroy(pPager->pInJournal);
4600347909
pPager->pInJournal = 0;
4600447910
pPager->nRec = 0;
46005
- sqlite3PcacheCleanAll(pPager->pPCache);
46006
- sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
47911
+ if( rc==SQLITE_OK ){
47912
+ if( pagerFlushOnCommit(pPager, bCommit) ){
47913
+ sqlite3PcacheCleanAll(pPager->pPCache);
47914
+ }else{
47915
+ sqlite3PcacheClearWritable(pPager->pPCache);
47916
+ }
47917
+ sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
47918
+ }
4600747919
4600847920
if( pagerUseWal(pPager) ){
4600947921
/* Drop the WAL write-lock, if any. Also, if the connection was in
4601047922
** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
4601147923
** lock held on the database file.
@@ -46285,11 +48197,11 @@
4628548197
pPg = 0;
4628648198
}else{
4628748199
pPg = sqlite3PagerLookup(pPager, pgno);
4628848200
}
4628948201
assert( pPg || !MEMDB );
46290
- assert( pPager->eState!=PAGER_OPEN || pPg==0 );
48202
+ assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
4629148203
PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
4629248204
PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
4629348205
(isMainJrnl?"main-journal":"sub-journal")
4629448206
));
4629548207
if( isMainJrnl ){
@@ -46335,11 +48247,10 @@
4633548247
pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
4633648248
rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
4633748249
assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
4633848250
pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
4633948251
if( rc!=SQLITE_OK ) return rc;
46340
- pPg->flags &= ~PGHDR_NEED_READ;
4634148252
sqlite3PcacheMakeDirty(pPg);
4634248253
}
4634348254
if( pPg ){
4634448255
/* No page should ever be explicitly rolled back that is in use, except
4634548256
** for page 1 which is held in use in order to keep the lock on the
@@ -46349,33 +48260,14 @@
4634948260
*/
4635048261
void *pData;
4635148262
pData = pPg->pData;
4635248263
memcpy(pData, (u8*)aData, pPager->pageSize);
4635348264
pPager->xReiniter(pPg);
46354
- if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
46355
- /* If the contents of this page were just restored from the main
46356
- ** journal file, then its content must be as they were when the
46357
- ** transaction was first opened. In this case we can mark the page
46358
- ** as clean, since there will be no need to write it out to the
46359
- ** database.
46360
- **
46361
- ** There is one exception to this rule. If the page is being rolled
46362
- ** back as part of a savepoint (or statement) rollback from an
46363
- ** unsynced portion of the main journal file, then it is not safe
46364
- ** to mark the page as clean. This is because marking the page as
46365
- ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
46366
- ** already in the journal file (recorded in Pager.pInJournal) and
46367
- ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
46368
- ** again within this transaction, it will be marked as dirty but
46369
- ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
46370
- ** be written out into the database file before its journal file
46371
- ** segment is synced. If a crash occurs during or following this,
46372
- ** database corruption may ensue.
46373
- */
46374
- assert( !pagerUseWal(pPager) );
46375
- sqlite3PcacheMakeClean(pPg);
46376
- }
48265
+ /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
48266
+ ** that call was dangerous and had no detectable benefit since the cache
48267
+ ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48268
+ ** has been removed. */
4637748269
pager_set_pagehash(pPg);
4637848270
4637948271
/* If this was page 1, then restore the value of Pager.dbFileVers.
4638048272
** Do this before any decoding. */
4638148273
if( pgno==1 ){
@@ -47162,25 +49054,24 @@
4716249054
** available from the WAL sub-system if the log file is empty or
4716349055
** contains no valid committed transactions.
4716449056
*/
4716549057
assert( pPager->eState==PAGER_OPEN );
4716649058
assert( pPager->eLock>=SHARED_LOCK );
49059
+ assert( isOpen(pPager->fd) );
49060
+ assert( pPager->tempFile==0 );
4716749061
nPage = sqlite3WalDbsize(pPager->pWal);
4716849062
4716949063
/* If the number of pages in the database is not available from the
4717049064
** WAL sub-system, determine the page counte based on the size of
4717149065
** the database file. If the size of the database file is not an
4717249066
** integer multiple of the page-size, round up the result.
4717349067
*/
47174
- if( nPage==0 ){
49068
+ if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
4717549069
i64 n = 0; /* Size of db file in bytes */
47176
- assert( isOpen(pPager->fd) || pPager->tempFile );
47177
- if( isOpen(pPager->fd) ){
47178
- int rc = sqlite3OsFileSize(pPager->fd, &n);
47179
- if( rc!=SQLITE_OK ){
47180
- return rc;
47181
- }
49070
+ int rc = sqlite3OsFileSize(pPager->fd, &n);
49071
+ if( rc!=SQLITE_OK ){
49072
+ return rc;
4718249073
}
4718349074
nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
4718449075
}
4718549076
4718649077
/* If the current number of pages in the file is greater than the
@@ -48252,12 +50143,13 @@
4825250143
static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
4825350144
int rc = SQLITE_OK; /* Return code */
4825450145
4825550146
/* This function is only called for rollback pagers in WRITER_DBMOD state. */
4825650147
assert( !pagerUseWal(pPager) );
48257
- assert( pPager->eState==PAGER_WRITER_DBMOD );
50148
+ assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
4825850149
assert( pPager->eLock==EXCLUSIVE_LOCK );
50150
+ assert( isOpen(pPager->fd) || pList->pDirty==0 );
4825950151
4826050152
/* If the file is a temp-file has not yet been opened, open it now. It
4826150153
** is not possible for rc to be other than SQLITE_OK if this branch
4826250154
** is taken, as pager_wait_on_lock() is a no-op for temp-files.
4826350155
*/
@@ -48921,10 +50813,11 @@
4892150813
*/
4892250814
rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
4892350815
if( rc==SQLITE_OK && !locked ){
4892450816
Pgno nPage; /* Number of pages in database file */
4892550817
50818
+ assert( pPager->tempFile==0 );
4892650819
rc = pagerPagecount(pPager, &nPage);
4892750820
if( rc==SQLITE_OK ){
4892850821
/* If the database is zero pages in size, that means that either (1) the
4892950822
** journal is a remnant from a prior database with the same name where
4893050823
** the database file but not the journal was deleted, or (2) the initial
@@ -49013,21 +50906,21 @@
4901350906
int rc = SQLITE_OK; /* Return code */
4901450907
4901550908
/* This routine is only called from b-tree and only when there are no
4901650909
** outstanding pages. This implies that the pager state should either
4901750910
** be OPEN or READER. READER is only possible if the pager is or was in
49018
- ** exclusive access mode.
49019
- */
50911
+ ** exclusive access mode. */
4902050912
assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
4902150913
assert( assert_pager_state(pPager) );
4902250914
assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49023
- if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
50915
+ assert( pPager->errCode==SQLITE_OK );
4902450916
4902550917
if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
4902650918
int bHotJournal = 1; /* True if there exists a hot journal-file */
4902750919
4902850920
assert( !MEMDB );
50921
+ assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
4902950922
4903050923
rc = pager_wait_on_lock(pPager, SHARED_LOCK);
4903150924
if( rc!=SQLITE_OK ){
4903250925
assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
4903350926
goto failed;
@@ -49109,11 +51002,11 @@
4910951002
*/
4911051003
if( isOpen(pPager->jfd) ){
4911151004
assert( rc==SQLITE_OK );
4911251005
rc = pagerSyncHotJournal(pPager);
4911351006
if( rc==SQLITE_OK ){
49114
- rc = pager_playback(pPager, 1);
51007
+ rc = pager_playback(pPager, !pPager->tempFile);
4911551008
pPager->eState = PAGER_OPEN;
4911651009
}
4911751010
}else if( !pPager->exclusiveMode ){
4911851011
pagerUnlockDb(pPager, SHARED_LOCK);
4911951012
}
@@ -49205,11 +51098,11 @@
4920551098
if( pagerUseWal(pPager) ){
4920651099
assert( rc==SQLITE_OK );
4920751100
rc = pagerBeginReadTransaction(pPager);
4920851101
}
4920951102
49210
- if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51103
+ if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
4921151104
rc = pagerPagecount(pPager, &pPager->dbSize);
4921251105
}
4921351106
4921451107
failed:
4921551108
if( rc!=SQLITE_OK ){
@@ -49338,11 +51231,11 @@
4933851231
rc = sqlite3OsFetch(pPager->fd,
4933951232
(i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
4934051233
);
4934151234
4934251235
if( rc==SQLITE_OK && pData ){
49343
- if( pPager->eState>PAGER_READER ){
51236
+ if( pPager->eState>PAGER_READER || pPager->tempFile ){
4934451237
pPg = sqlite3PagerLookup(pPager, pgno);
4934551238
}
4934651239
if( pPg==0 ){
4934751240
rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
4934851241
}else{
@@ -49405,11 +51298,12 @@
4940551298
if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
4940651299
rc = SQLITE_CORRUPT_BKPT;
4940751300
goto pager_acquire_err;
4940851301
}
4940951302
49410
- if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
51303
+ assert( !isOpen(pPager->fd) || !MEMDB );
51304
+ if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
4941151305
if( pgno>pPager->mxPgno ){
4941251306
rc = SQLITE_FULL;
4941351307
goto pager_acquire_err;
4941451308
}
4941551309
if( noContent ){
@@ -49547,28 +51441,28 @@
4954751441
/* Open the journal file if it is not already open. */
4954851442
if( !isOpen(pPager->jfd) ){
4954951443
if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
4955051444
sqlite3MemJournalOpen(pPager->jfd);
4955151445
}else{
49552
- const int flags = /* VFS flags to open journal file */
49553
- SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
49554
- (pPager->tempFile ?
49555
- (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
49556
- (SQLITE_OPEN_MAIN_JOURNAL)
49557
- );
51446
+ int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51447
+ int nSpill;
4955851448
51449
+ if( pPager->tempFile ){
51450
+ flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51451
+ nSpill = sqlite3Config.nStmtSpill;
51452
+ }else{
51453
+ flags |= SQLITE_OPEN_MAIN_JOURNAL;
51454
+ nSpill = jrnlBufferSize(pPager);
51455
+ }
51456
+
4955951457
/* Verify that the database still has the same name as it did when
4956051458
** it was originally opened. */
4956151459
rc = databaseIsUnmoved(pPager);
4956251460
if( rc==SQLITE_OK ){
49563
-#ifdef SQLITE_ENABLE_ATOMIC_WRITE
49564
- rc = sqlite3JournalOpen(
49565
- pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
51461
+ rc = sqlite3JournalOpen (
51462
+ pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
4956651463
);
49567
-#else
49568
- rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
49569
-#endif
4957051464
}
4957151465
}
4957251466
assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
4957351467
}
4957451468
@@ -49935,10 +51829,11 @@
4993551829
return pPager->errCode;
4993651830
}else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
4993751831
if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
4993851832
return SQLITE_OK;
4993951833
}else if( pPager->sectorSize > (u32)pPager->pageSize ){
51834
+ assert( pPager->tempFile==0 );
4994051835
return pagerWriteLargeSector(pPg);
4994151836
}else{
4994251837
return pager_write(pPg);
4994351838
}
4994451839
}
@@ -49965,18 +51860,25 @@
4996551860
** on the given page is unused. The pager marks the page as clean so
4996651861
** that it does not get written to disk.
4996751862
**
4996851863
** Tests show that this optimization can quadruple the speed of large
4996951864
** DELETE operations.
51865
+**
51866
+** This optimization cannot be used with a temp-file, as the page may
51867
+** have been dirty at the start of the transaction. In that case, if
51868
+** memory pressure forces page pPg out of the cache, the data does need
51869
+** to be written out to disk so that it may be read back in if the
51870
+** current transaction is rolled back.
4997051871
*/
4997151872
SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
4997251873
Pager *pPager = pPg->pPager;
49973
- if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
51874
+ if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
4997451875
PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
4997551876
IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
4997651877
pPg->flags |= PGHDR_DONT_WRITE;
4997751878
pPg->flags &= ~PGHDR_WRITEABLE;
51879
+ testcase( pPg->flags & PGHDR_NEED_SYNC );
4997851880
pager_set_pagehash(pPg);
4997951881
}
4998051882
}
4998151883
4998251884
/*
@@ -50166,22 +52068,26 @@
5016652068
);
5016752069
assert( assert_pager_state(pPager) );
5016852070
5016952071
/* If a prior error occurred, report that error again. */
5017052072
if( NEVER(pPager->errCode) ) return pPager->errCode;
52073
+
52074
+ /* Provide the ability to easily simulate an I/O error during testing */
52075
+ if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
5017152076
5017252077
PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
5017352078
pPager->zFilename, zMaster, pPager->dbSize));
5017452079
5017552080
/* If no database changes have been made, return early. */
5017652081
if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
5017752082
50178
- if( MEMDB ){
52083
+ assert( MEMDB==0 || pPager->tempFile );
52084
+ assert( isOpen(pPager->fd) || pPager->tempFile );
52085
+ if( 0==pagerFlushOnCommit(pPager, 1) ){
5017952086
/* If this is an in-memory db, or no pages have been written to, or this
5018052087
** function has already been called, it is mostly a no-op. However, any
50181
- ** backup in progress needs to be restarted.
50182
- */
52088
+ ** backup in progress needs to be restarted. */
5018352089
sqlite3BackupRestart(pPager->pBackup);
5018452090
}else{
5018552091
if( pagerUseWal(pPager) ){
5018652092
PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
5018752093
PgHdr *pPageOne = 0;
@@ -50516,14 +52422,14 @@
5051652422
pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
5051752423
}
5051852424
}
5051952425
5052052426
/*
50521
-** Return true if this is an in-memory pager.
52427
+** Return true if this is an in-memory or temp-file backed pager.
5052252428
*/
5052352429
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
50524
- return MEMDB;
52430
+ return pPager->tempFile;
5052552431
}
5052652432
5052752433
/*
5052852434
** Check that there are at least nSavepoint savepoints open. If there are
5052952435
** currently less than nSavepoints open, then open one or more savepoints
@@ -50799,11 +52705,12 @@
5079952705
assert( assert_pager_state(pPager) );
5080052706
5080152707
/* In order to be able to rollback, an in-memory database must journal
5080252708
** the page we are moving from.
5080352709
*/
50804
- if( MEMDB ){
52710
+ assert( pPager->tempFile || !MEMDB );
52711
+ if( pPager->tempFile ){
5080552712
rc = sqlite3PagerWrite(pPg);
5080652713
if( rc ) return rc;
5080752714
}
5080852715
5080952716
/* If the page being moved is dirty and has not been saved by the latest
@@ -50856,11 +52763,11 @@
5085652763
pPg->flags &= ~PGHDR_NEED_SYNC;
5085752764
pPgOld = sqlite3PagerLookup(pPager, pgno);
5085852765
assert( !pPgOld || pPgOld->nRef==1 );
5085952766
if( pPgOld ){
5086052767
pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
50861
- if( MEMDB ){
52768
+ if( pPager->tempFile ){
5086252769
/* Do not discard pages from an in-memory database since we might
5086352770
** need to rollback later. Just move the page out of the way. */
5086452771
sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
5086552772
}else{
5086652773
sqlite3PcacheDrop(pPgOld);
@@ -50873,12 +52780,11 @@
5087352780
5087452781
/* For an in-memory database, make sure the original page continues
5087552782
** to exist, in case the transaction needs to roll back. Use pPgOld
5087652783
** as the original page since it has already been allocated.
5087752784
*/
50878
- if( MEMDB ){
50879
- assert( pPgOld );
52785
+ if( pPager->tempFile && pPgOld ){
5088052786
sqlite3PcacheMove(pPgOld, origPgno);
5088152787
sqlite3PagerUnrefNotNull(pPgOld);
5088252788
}
5088352789
5088452790
if( needSyncPgno ){
@@ -51126,11 +53032,12 @@
5112653032
#ifndef SQLITE_OMIT_VACUUM
5112753033
/*
5112853034
** Unless this is an in-memory or temporary database, clear the pager cache.
5112953035
*/
5113053036
SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
51131
- if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
53037
+ assert( MEMDB==0 || pPager->tempFile );
53038
+ if( pPager->tempFile==0 ) pager_reset(pPager);
5113253039
}
5113353040
#endif
5113453041
5113553042
#ifndef SQLITE_OMIT_WAL
5113653043
/*
@@ -51305,10 +53212,11 @@
5130553212
if( rc==SQLITE_OK ){
5130653213
rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
5130753214
pPager->pageSize, (u8*)pPager->pTmpSpace);
5130853215
pPager->pWal = 0;
5130953216
pagerFixMaplimit(pPager);
53217
+ if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
5131053218
}
5131153219
}
5131253220
return rc;
5131353221
}
5131453222
@@ -54760,10 +56668,27 @@
5476056668
/* Try to open on pSnapshot when the next read-transaction starts
5476156669
*/
5476256670
SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
5476356671
pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
5476456672
}
56673
+
56674
+/*
56675
+** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
56676
+** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
56677
+*/
56678
+SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
56679
+ WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
56680
+ WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
56681
+
56682
+ /* aSalt[0] is a copy of the value stored in the wal file header. It
56683
+ ** is incremented each time the wal file is restarted. */
56684
+ if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
56685
+ if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
56686
+ if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
56687
+ if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
56688
+ return 0;
56689
+}
5476556690
#endif /* SQLITE_ENABLE_SNAPSHOT */
5476656691
5476756692
#ifdef SQLITE_ENABLE_ZIPVFS
5476856693
/*
5476956694
** If the argument is not NULL, it points to a Wal object that holds a
@@ -57475,15 +59400,15 @@
5747559400
flagByte &= ~PTF_LEAF;
5747659401
pPage->childPtrSize = 4-4*pPage->leaf;
5747759402
pPage->xCellSize = cellSizePtr;
5747859403
pBt = pPage->pBt;
5747959404
if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
57480
- /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
57481
- ** table b-tree page. */
59405
+ /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59406
+ ** interior table b-tree page. */
5748259407
assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
57483
- /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
57484
- ** table b-tree page. */
59408
+ /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59409
+ ** leaf table b-tree page. */
5748559410
assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
5748659411
pPage->intKey = 1;
5748759412
if( pPage->leaf ){
5748859413
pPage->intKeyLeaf = 1;
5748959414
pPage->xParseCell = btreeParseCellPtr;
@@ -57493,15 +59418,15 @@
5749359418
pPage->xParseCell = btreeParseCellPtrNoPayload;
5749459419
}
5749559420
pPage->maxLocal = pBt->maxLeaf;
5749659421
pPage->minLocal = pBt->minLeaf;
5749759422
}else if( flagByte==PTF_ZERODATA ){
57498
- /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
57499
- ** index b-tree page. */
59423
+ /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59424
+ ** interior index b-tree page. */
5750059425
assert( (PTF_ZERODATA)==2 );
57501
- /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
57502
- ** index b-tree page. */
59426
+ /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59427
+ ** leaf index b-tree page. */
5750359428
assert( (PTF_ZERODATA|PTF_LEAF)==10 );
5750459429
pPage->intKey = 0;
5750559430
pPage->intKeyLeaf = 0;
5750659431
pPage->xParseCell = btreeParseCellPtrIndex;
5750759432
pPage->maxLocal = pBt->maxLocal;
@@ -62344,12 +64269,12 @@
6234464269
for(i=iFirst; i<iEnd; i++){
6234564270
int sz, rc;
6234664271
u8 *pSlot;
6234764272
sz = cachedCellSize(pCArray, i);
6234864273
if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64274
+ if( (pData - pBegin)<sz ) return 1;
6234964275
pData -= sz;
62350
- if( pData<pBegin ) return 1;
6235164276
pSlot = pData;
6235264277
}
6235364278
/* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6235464279
** database. But they might for a corrupt database. Hence use memmove()
6235564280
** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
@@ -62507,11 +64432,11 @@
6250764432
6250864433
#ifdef SQLITE_DEBUG
6250964434
for(i=0; i<nNew && !CORRUPT_DB; i++){
6251064435
u8 *pCell = pCArray->apCell[i+iNew];
6251164436
int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
62512
- if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
64437
+ if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
6251364438
pCell = &pTmp[pCell - aData];
6251464439
}
6251564440
assert( 0==memcmp(pCell, &aData[iOff],
6251664441
pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
6251764442
}
@@ -63938,10 +65863,32 @@
6393865863
6393965864
iCellDepth = pCur->iPage;
6394065865
iCellIdx = pCur->aiIdx[iCellDepth];
6394165866
pPage = pCur->apPage[iCellDepth];
6394265867
pCell = findCell(pPage, iCellIdx);
65868
+
65869
+ /* If the bPreserve flag is set to true, then the cursor position must
65870
+ ** be preserved following this delete operation. If the current delete
65871
+ ** will cause a b-tree rebalance, then this is done by saving the cursor
65872
+ ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
65873
+ ** returning.
65874
+ **
65875
+ ** Or, if the current delete will not cause a rebalance, then the cursor
65876
+ ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
65877
+ ** before or after the deleted entry. In this case set bSkipnext to true. */
65878
+ if( bPreserve ){
65879
+ if( !pPage->leaf
65880
+ || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
65881
+ ){
65882
+ /* A b-tree rebalance will be required after deleting this entry.
65883
+ ** Save the cursor key. */
65884
+ rc = saveCursorKey(pCur);
65885
+ if( rc ) return rc;
65886
+ }else{
65887
+ bSkipnext = 1;
65888
+ }
65889
+ }
6394365890
6394465891
/* If the page containing the entry to delete is not a leaf page, move
6394565892
** the cursor to the largest entry in the tree that is smaller than
6394665893
** the entry being deleted. This cell will replace the cell being deleted
6394765894
** from the internal node. The 'previous' entry is used for this instead
@@ -63965,32 +65912,10 @@
6396565912
** invalidate any incrblob cursors open on the row being deleted. */
6396665913
if( pCur->pKeyInfo==0 ){
6396765914
invalidateIncrblobCursors(p, pCur->info.nKey, 0);
6396865915
}
6396965916
63970
- /* If the bPreserve flag is set to true, then the cursor position must
63971
- ** be preserved following this delete operation. If the current delete
63972
- ** will cause a b-tree rebalance, then this is done by saving the cursor
63973
- ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
63974
- ** returning.
63975
- **
63976
- ** Or, if the current delete will not cause a rebalance, then the cursor
63977
- ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
63978
- ** before or after the deleted entry. In this case set bSkipnext to true. */
63979
- if( bPreserve ){
63980
- if( !pPage->leaf
63981
- || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
63982
- ){
63983
- /* A b-tree rebalance will be required after deleting this entry.
63984
- ** Save the cursor key. */
63985
- rc = saveCursorKey(pCur);
63986
- if( rc ) return rc;
63987
- }else{
63988
- bSkipnext = 1;
63989
- }
63990
- }
63991
-
6399265917
/* Make the page containing the entry to be deleted writable. Then free any
6399365918
** overflow pages associated with the entry and finally remove the cell
6399465919
** itself from within the page. */
6399565920
rc = sqlite3PagerWrite(pPage->pDbPage);
6399665921
if( rc ) return rc;
@@ -67111,14 +69036,10 @@
6711169036
** freed before the copy is made.
6711269037
*/
6711369038
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
6711469039
int rc = SQLITE_OK;
6711569040
67116
- /* The pFrom==0 case in the following assert() is when an sqlite3_value
67117
- ** from sqlite3_value_dup() is used as the argument
67118
- ** to sqlite3_result_value(). */
67119
- assert( pTo->db==pFrom->db || pFrom->db==0 );
6712069041
assert( (pFrom->flags & MEM_RowSet)==0 );
6712169042
if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
6712269043
memcpy(pTo, pFrom, MEMCELLSIZE);
6712369044
pTo->flags &= ~MEM_Dyn;
6712469045
if( pTo->flags&(MEM_Str|MEM_Blob) ){
@@ -68102,10 +70023,11 @@
6810270023
** Swap all content between two VDBE structures.
6810370024
*/
6810470025
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
6810570026
Vdbe tmp, *pTmp;
6810670027
char *zTmp;
70028
+ assert( pA->db==pB->db );
6810770029
tmp = *pA;
6810870030
*pA = *pB;
6810970031
*pB = tmp;
6811070032
pTmp = pA->pNext;
6811170033
pA->pNext = pB->pNext;
@@ -68568,77 +70490,88 @@
6856870490
** indicate what the prepared statement actually does.
6856970491
**
6857070492
** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
6857170493
**
6857270494
** (5) Reclaim the memory allocated for storing labels.
70495
+**
70496
+** This routine will only function correctly if the mkopcodeh.tcl generator
70497
+** script numbers the opcodes correctly. Changes to this routine must be
70498
+** coordinated with changes to mkopcodeh.tcl.
6857370499
*/
6857470500
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
68575
- int i;
6857670501
int nMaxArgs = *pMaxFuncArgs;
6857770502
Op *pOp;
6857870503
Parse *pParse = p->pParse;
6857970504
int *aLabel = pParse->aLabel;
6858070505
p->readOnly = 1;
6858170506
p->bIsReader = 0;
68582
- for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
68583
- u8 opcode = pOp->opcode;
68584
-
68585
- /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
68586
- ** cases from this switch! */
68587
- switch( opcode ){
68588
- case OP_Transaction: {
68589
- if( pOp->p2!=0 ) p->readOnly = 0;
68590
- /* fall thru */
68591
- }
68592
- case OP_AutoCommit:
68593
- case OP_Savepoint: {
68594
- p->bIsReader = 1;
68595
- break;
68596
- }
70507
+ pOp = &p->aOp[p->nOp-1];
70508
+ while(1){
70509
+
70510
+ /* Only JUMP opcodes and the short list of special opcodes in the switch
70511
+ ** below need to be considered. The mkopcodeh.tcl generator script groups
70512
+ ** all these opcodes together near the front of the opcode list. Skip
70513
+ ** any opcode that does not need processing by virtual of the fact that
70514
+ ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70515
+ */
70516
+ if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70517
+ /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70518
+ ** cases from this switch! */
70519
+ switch( pOp->opcode ){
70520
+ case OP_Transaction: {
70521
+ if( pOp->p2!=0 ) p->readOnly = 0;
70522
+ /* fall thru */
70523
+ }
70524
+ case OP_AutoCommit:
70525
+ case OP_Savepoint: {
70526
+ p->bIsReader = 1;
70527
+ break;
70528
+ }
6859770529
#ifndef SQLITE_OMIT_WAL
68598
- case OP_Checkpoint:
70530
+ case OP_Checkpoint:
6859970531
#endif
68600
- case OP_Vacuum:
68601
- case OP_JournalMode: {
68602
- p->readOnly = 0;
68603
- p->bIsReader = 1;
68604
- break;
68605
- }
70532
+ case OP_Vacuum:
70533
+ case OP_JournalMode: {
70534
+ p->readOnly = 0;
70535
+ p->bIsReader = 1;
70536
+ break;
70537
+ }
6860670538
#ifndef SQLITE_OMIT_VIRTUALTABLE
68607
- case OP_VUpdate: {
68608
- if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
68609
- break;
68610
- }
68611
- case OP_VFilter: {
68612
- int n;
68613
- assert( p->nOp - i >= 3 );
68614
- assert( pOp[-1].opcode==OP_Integer );
68615
- n = pOp[-1].p1;
68616
- if( n>nMaxArgs ) nMaxArgs = n;
68617
- break;
68618
- }
68619
-#endif
68620
- case OP_Next:
68621
- case OP_NextIfOpen:
68622
- case OP_SorterNext: {
68623
- pOp->p4.xAdvance = sqlite3BtreeNext;
68624
- pOp->p4type = P4_ADVANCE;
68625
- break;
68626
- }
68627
- case OP_Prev:
68628
- case OP_PrevIfOpen: {
68629
- pOp->p4.xAdvance = sqlite3BtreePrevious;
68630
- pOp->p4type = P4_ADVANCE;
68631
- break;
68632
- }
68633
- }
68634
-
68635
- pOp->opflags = sqlite3OpcodeProperty[opcode];
68636
- if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
68637
- assert( ADDR(pOp->p2)<pParse->nLabel );
68638
- pOp->p2 = aLabel[ADDR(pOp->p2)];
68639
- }
70539
+ case OP_VUpdate: {
70540
+ if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70541
+ break;
70542
+ }
70543
+ case OP_VFilter: {
70544
+ int n;
70545
+ assert( (pOp - p->aOp) >= 3 );
70546
+ assert( pOp[-1].opcode==OP_Integer );
70547
+ n = pOp[-1].p1;
70548
+ if( n>nMaxArgs ) nMaxArgs = n;
70549
+ break;
70550
+ }
70551
+#endif
70552
+ case OP_Next:
70553
+ case OP_NextIfOpen:
70554
+ case OP_SorterNext: {
70555
+ pOp->p4.xAdvance = sqlite3BtreeNext;
70556
+ pOp->p4type = P4_ADVANCE;
70557
+ break;
70558
+ }
70559
+ case OP_Prev:
70560
+ case OP_PrevIfOpen: {
70561
+ pOp->p4.xAdvance = sqlite3BtreePrevious;
70562
+ pOp->p4type = P4_ADVANCE;
70563
+ break;
70564
+ }
70565
+ }
70566
+ if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70567
+ assert( ADDR(pOp->p2)<pParse->nLabel );
70568
+ pOp->p2 = aLabel[ADDR(pOp->p2)];
70569
+ }
70570
+ }
70571
+ if( pOp==p->aOp ) break;
70572
+ pOp--;
6864070573
}
6864170574
sqlite3DbFree(p->db, pParse->aLabel);
6864270575
pParse->aLabel = 0;
6864370576
pParse->nLabel = 0;
6864470577
*pMaxFuncArgs = nMaxArgs;
@@ -68814,56 +70747,54 @@
6881470747
6881570748
/*
6881670749
** Delete a P4 value if necessary.
6881770750
*/
6881870751
static void freeP4(sqlite3 *db, int p4type, void *p4){
68819
- if( p4 ){
68820
- assert( db );
68821
- switch( p4type ){
68822
- case P4_FUNCCTX: {
68823
- freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
68824
- /* Fall through into the next case */
68825
- }
68826
- case P4_REAL:
68827
- case P4_INT64:
68828
- case P4_DYNAMIC:
68829
- case P4_INTARRAY: {
68830
- sqlite3DbFree(db, p4);
68831
- break;
68832
- }
68833
- case P4_KEYINFO: {
68834
- if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
68835
- break;
68836
- }
70752
+ assert( db );
70753
+ switch( p4type ){
70754
+ case P4_FUNCCTX: {
70755
+ freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
70756
+ /* Fall through into the next case */
70757
+ }
70758
+ case P4_REAL:
70759
+ case P4_INT64:
70760
+ case P4_DYNAMIC:
70761
+ case P4_INTARRAY: {
70762
+ sqlite3DbFree(db, p4);
70763
+ break;
70764
+ }
70765
+ case P4_KEYINFO: {
70766
+ if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
70767
+ break;
70768
+ }
6883770769
#ifdef SQLITE_ENABLE_CURSOR_HINTS
68838
- case P4_EXPR: {
68839
- sqlite3ExprDelete(db, (Expr*)p4);
68840
- break;
68841
- }
68842
-#endif
68843
- case P4_MPRINTF: {
68844
- if( db->pnBytesFreed==0 ) sqlite3_free(p4);
68845
- break;
68846
- }
68847
- case P4_FUNCDEF: {
68848
- freeEphemeralFunction(db, (FuncDef*)p4);
68849
- break;
68850
- }
68851
- case P4_MEM: {
68852
- if( db->pnBytesFreed==0 ){
68853
- sqlite3ValueFree((sqlite3_value*)p4);
68854
- }else{
68855
- Mem *p = (Mem*)p4;
68856
- if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
68857
- sqlite3DbFree(db, p);
68858
- }
68859
- break;
68860
- }
68861
- case P4_VTAB : {
68862
- if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
68863
- break;
68864
- }
70770
+ case P4_EXPR: {
70771
+ sqlite3ExprDelete(db, (Expr*)p4);
70772
+ break;
70773
+ }
70774
+#endif
70775
+ case P4_MPRINTF: {
70776
+ if( db->pnBytesFreed==0 ) sqlite3_free(p4);
70777
+ break;
70778
+ }
70779
+ case P4_FUNCDEF: {
70780
+ freeEphemeralFunction(db, (FuncDef*)p4);
70781
+ break;
70782
+ }
70783
+ case P4_MEM: {
70784
+ if( db->pnBytesFreed==0 ){
70785
+ sqlite3ValueFree((sqlite3_value*)p4);
70786
+ }else{
70787
+ Mem *p = (Mem*)p4;
70788
+ if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
70789
+ sqlite3DbFree(db, p);
70790
+ }
70791
+ break;
70792
+ }
70793
+ case P4_VTAB : {
70794
+ if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
70795
+ break;
6886570796
}
6886670797
}
6886770798
}
6886870799
6886970800
/*
@@ -69340,10 +71271,14 @@
6934071271
break;
6934171272
}
6934271273
case P4_ADVANCE: {
6934371274
zTemp[0] = 0;
6934471275
break;
71276
+ }
71277
+ case P4_TABLE: {
71278
+ sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71279
+ break;
6934571280
}
6934671281
default: {
6934771282
zP4 = pOp->p4.z;
6934871283
if( zP4==0 ){
6934971284
zP4 = zTemp;
@@ -71531,10 +73466,11 @@
7153173466
idx += getVarint32(&aKey[idx], serial_type);
7153273467
pMem->enc = pKeyInfo->enc;
7153373468
pMem->db = pKeyInfo->db;
7153473469
/* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
7153573470
pMem->szMalloc = 0;
73471
+ pMem->z = 0;
7153673472
d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
7153773473
pMem++;
7153873474
if( (++u)>=p->nField ) break;
7153973475
}
7154073476
assert( u<=pKeyInfo->nField + 1 );
@@ -72511,10 +74447,94 @@
7251174447
pVtab->zErrMsg = 0;
7251274448
}
7251374449
}
7251474450
#endif /* SQLITE_OMIT_VIRTUALTABLE */
7251574451
74452
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74453
+
74454
+/*
74455
+** If the second argument is not NULL, release any allocations associated
74456
+** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74457
+** structure itself, using sqlite3DbFree().
74458
+**
74459
+** This function is used to free UnpackedRecord structures allocated by
74460
+** the vdbeUnpackRecord() function found in vdbeapi.c.
74461
+*/
74462
+static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74463
+ if( p ){
74464
+ int i;
74465
+ for(i=0; i<p->nField; i++){
74466
+ Mem *pMem = &p->aMem[i];
74467
+ if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74468
+ }
74469
+ sqlite3DbFree(db, p);
74470
+ }
74471
+}
74472
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74473
+
74474
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74475
+/*
74476
+** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74477
+** then cursor passed as the second argument should point to the row about
74478
+** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74479
+** the required value will be read from the row the cursor points to.
74480
+*/
74481
+SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74482
+ Vdbe *v, /* Vdbe pre-update hook is invoked by */
74483
+ VdbeCursor *pCsr, /* Cursor to grab old.* values from */
74484
+ int op, /* SQLITE_INSERT, UPDATE or DELETE */
74485
+ const char *zDb, /* Database name */
74486
+ Table *pTab, /* Modified table */
74487
+ i64 iKey1, /* Initial key value */
74488
+ int iReg /* Register for new.* record */
74489
+){
74490
+ sqlite3 *db = v->db;
74491
+ i64 iKey2;
74492
+ PreUpdate preupdate;
74493
+ const char *zTbl = pTab->zName;
74494
+ static const u8 fakeSortOrder = 0;
74495
+
74496
+ assert( db->pPreUpdate==0 );
74497
+ memset(&preupdate, 0, sizeof(PreUpdate));
74498
+ if( op==SQLITE_UPDATE ){
74499
+ iKey2 = v->aMem[iReg].u.i;
74500
+ }else{
74501
+ iKey2 = iKey1;
74502
+ }
74503
+
74504
+ assert( pCsr->nField==pTab->nCol
74505
+ || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74506
+ );
74507
+
74508
+ preupdate.v = v;
74509
+ preupdate.pCsr = pCsr;
74510
+ preupdate.op = op;
74511
+ preupdate.iNewReg = iReg;
74512
+ preupdate.keyinfo.db = db;
74513
+ preupdate.keyinfo.enc = ENC(db);
74514
+ preupdate.keyinfo.nField = pTab->nCol;
74515
+ preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74516
+ preupdate.iKey1 = iKey1;
74517
+ preupdate.iKey2 = iKey2;
74518
+ preupdate.iPKey = pTab->iPKey;
74519
+
74520
+ db->pPreUpdate = &preupdate;
74521
+ db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74522
+ db->pPreUpdate = 0;
74523
+ sqlite3DbFree(db, preupdate.aRecord);
74524
+ vdbeFreeUnpacked(db, preupdate.pUnpacked);
74525
+ vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74526
+ if( preupdate.aNew ){
74527
+ int i;
74528
+ for(i=0; i<pCsr->nField; i++){
74529
+ sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74530
+ }
74531
+ sqlite3DbFree(db, preupdate.aNew);
74532
+ }
74533
+}
74534
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74535
+
7251674536
/************** End of vdbeaux.c *********************************************/
7251774537
/************** Begin file vdbeapi.c *****************************************/
7251874538
/*
7251974539
** 2004 May 26
7252074540
**
@@ -74119,10 +76139,191 @@
7411976139
v = pVdbe->aCounter[op];
7412076140
if( resetFlag ) pVdbe->aCounter[op] = 0;
7412176141
return (int)v;
7412276142
}
7412376143
76144
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76145
+/*
76146
+** Allocate and populate an UnpackedRecord structure based on the serialized
76147
+** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76148
+** if successful, or a NULL pointer if an OOM error is encountered.
76149
+*/
76150
+static UnpackedRecord *vdbeUnpackRecord(
76151
+ KeyInfo *pKeyInfo,
76152
+ int nKey,
76153
+ const void *pKey
76154
+){
76155
+ char *dummy; /* Dummy argument for AllocUnpackedRecord() */
76156
+ UnpackedRecord *pRet; /* Return value */
76157
+
76158
+ pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76159
+ if( pRet ){
76160
+ memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76161
+ sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76162
+ }
76163
+ return pRet;
76164
+}
76165
+
76166
+/*
76167
+** This function is called from within a pre-update callback to retrieve
76168
+** a field of the row currently being updated or deleted.
76169
+*/
76170
+SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76171
+ PreUpdate *p = db->pPreUpdate;
76172
+ int rc = SQLITE_OK;
76173
+
76174
+ /* Test that this call is being made from within an SQLITE_DELETE or
76175
+ ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76176
+ if( !p || p->op==SQLITE_INSERT ){
76177
+ rc = SQLITE_MISUSE_BKPT;
76178
+ goto preupdate_old_out;
76179
+ }
76180
+ if( iIdx>=p->pCsr->nField || iIdx<0 ){
76181
+ rc = SQLITE_RANGE;
76182
+ goto preupdate_old_out;
76183
+ }
76184
+
76185
+ /* If the old.* record has not yet been loaded into memory, do so now. */
76186
+ if( p->pUnpacked==0 ){
76187
+ u32 nRec;
76188
+ u8 *aRec;
76189
+
76190
+ rc = sqlite3BtreeDataSize(p->pCsr->uc.pCursor, &nRec);
76191
+ if( rc!=SQLITE_OK ) goto preupdate_old_out;
76192
+ aRec = sqlite3DbMallocRaw(db, nRec);
76193
+ if( !aRec ) goto preupdate_old_out;
76194
+ rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76195
+ if( rc==SQLITE_OK ){
76196
+ p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76197
+ if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76198
+ }
76199
+ if( rc!=SQLITE_OK ){
76200
+ sqlite3DbFree(db, aRec);
76201
+ goto preupdate_old_out;
76202
+ }
76203
+ p->aRecord = aRec;
76204
+ }
76205
+
76206
+ if( iIdx>=p->pUnpacked->nField ){
76207
+ *ppValue = (sqlite3_value *)columnNullValue();
76208
+ }else{
76209
+ *ppValue = &p->pUnpacked->aMem[iIdx];
76210
+ if( iIdx==p->iPKey ){
76211
+ sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76212
+ }
76213
+ }
76214
+
76215
+ preupdate_old_out:
76216
+ sqlite3Error(db, rc);
76217
+ return sqlite3ApiExit(db, rc);
76218
+}
76219
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76220
+
76221
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76222
+/*
76223
+** This function is called from within a pre-update callback to retrieve
76224
+** the number of columns in the row being updated, deleted or inserted.
76225
+*/
76226
+SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *db){
76227
+ PreUpdate *p = db->pPreUpdate;
76228
+ return (p ? p->keyinfo.nField : 0);
76229
+}
76230
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76231
+
76232
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76233
+/*
76234
+** This function is designed to be called from within a pre-update callback
76235
+** only. It returns zero if the change that caused the callback was made
76236
+** immediately by a user SQL statement. Or, if the change was made by a
76237
+** trigger program, it returns the number of trigger programs currently
76238
+** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76239
+** top-level trigger etc.).
76240
+**
76241
+** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76242
+** or SET DEFAULT action is considered a trigger.
76243
+*/
76244
+SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *db){
76245
+ PreUpdate *p = db->pPreUpdate;
76246
+ return (p ? p->v->nFrame : 0);
76247
+}
76248
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76249
+
76250
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76251
+/*
76252
+** This function is called from within a pre-update callback to retrieve
76253
+** a field of the row currently being updated or inserted.
76254
+*/
76255
+SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76256
+ PreUpdate *p = db->pPreUpdate;
76257
+ int rc = SQLITE_OK;
76258
+ Mem *pMem;
76259
+
76260
+ if( !p || p->op==SQLITE_DELETE ){
76261
+ rc = SQLITE_MISUSE_BKPT;
76262
+ goto preupdate_new_out;
76263
+ }
76264
+ if( iIdx>=p->pCsr->nField || iIdx<0 ){
76265
+ rc = SQLITE_RANGE;
76266
+ goto preupdate_new_out;
76267
+ }
76268
+
76269
+ if( p->op==SQLITE_INSERT ){
76270
+ /* For an INSERT, memory cell p->iNewReg contains the serialized record
76271
+ ** that is being inserted. Deserialize it. */
76272
+ UnpackedRecord *pUnpack = p->pNewUnpacked;
76273
+ if( !pUnpack ){
76274
+ Mem *pData = &p->v->aMem[p->iNewReg];
76275
+ rc = sqlite3VdbeMemExpandBlob(pData);
76276
+ if( rc!=SQLITE_OK ) goto preupdate_new_out;
76277
+ pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76278
+ if( !pUnpack ){
76279
+ rc = SQLITE_NOMEM;
76280
+ goto preupdate_new_out;
76281
+ }
76282
+ p->pNewUnpacked = pUnpack;
76283
+ }
76284
+ if( iIdx>=pUnpack->nField ){
76285
+ pMem = (sqlite3_value *)columnNullValue();
76286
+ }else{
76287
+ pMem = &pUnpack->aMem[iIdx];
76288
+ if( iIdx==p->iPKey ){
76289
+ sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76290
+ }
76291
+ }
76292
+ }else{
76293
+ /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76294
+ ** value. Make a copy of the cell contents and return a pointer to it.
76295
+ ** It is not safe to return a pointer to the memory cell itself as the
76296
+ ** caller may modify the value text encoding.
76297
+ */
76298
+ assert( p->op==SQLITE_UPDATE );
76299
+ if( !p->aNew ){
76300
+ p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76301
+ if( !p->aNew ){
76302
+ rc = SQLITE_NOMEM;
76303
+ goto preupdate_new_out;
76304
+ }
76305
+ }
76306
+ assert( iIdx>=0 && iIdx<p->pCsr->nField );
76307
+ pMem = &p->aNew[iIdx];
76308
+ if( pMem->flags==0 ){
76309
+ if( iIdx==p->iPKey ){
76310
+ sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76311
+ }else{
76312
+ rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76313
+ if( rc!=SQLITE_OK ) goto preupdate_new_out;
76314
+ }
76315
+ }
76316
+ }
76317
+ *ppValue = pMem;
76318
+
76319
+ preupdate_new_out:
76320
+ sqlite3Error(db, rc);
76321
+ return sqlite3ApiExit(db, rc);
76322
+}
76323
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76324
+
7412476325
#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
7412576326
/*
7412676327
** Return status data for a single loop within query pStmt.
7412776328
*/
7412876329
SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
@@ -74469,10 +76670,20 @@
7446976670
sqlite3_max_blobsize = p->n;
7447076671
}
7447176672
}
7447276673
#endif
7447376674
76675
+/*
76676
+** This macro evaluates to true if either the update hook or the preupdate
76677
+** hook are enabled for database connect DB.
76678
+*/
76679
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76680
+# define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
76681
+#else
76682
+# define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
76683
+#endif
76684
+
7447476685
/*
7447576686
** The next global variable is incremented each time the OP_Found opcode
7447676687
** is executed. This is used to test whether or not the foreign key
7447776688
** operation implemented using OP_FkIsZero is working. This variable
7447876689
** has no function other than to help verify the correct operation of the
@@ -74588,11 +76799,11 @@
7458876799
nByte =
7458976800
ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
7459076801
(eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
7459176802
7459276803
assert( iCur>=0 && iCur<p->nCursor );
74593
- if( p->apCsr[iCur] ){
76804
+ if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
7459476805
sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
7459576806
p->apCsr[iCur] = 0;
7459676807
}
7459776808
if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
7459876809
p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
@@ -74665,24 +76876,27 @@
7466576876
u8 enc /* Use this text encoding */
7466676877
){
7466776878
if( affinity>=SQLITE_AFF_NUMERIC ){
7466876879
assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
7466976880
|| affinity==SQLITE_AFF_NUMERIC );
74670
- if( (pRec->flags & MEM_Int)==0 ){
76881
+ if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
7467176882
if( (pRec->flags & MEM_Real)==0 ){
7467276883
if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
7467376884
}else{
7467476885
sqlite3VdbeIntegerAffinity(pRec);
7467576886
}
7467676887
}
7467776888
}else if( affinity==SQLITE_AFF_TEXT ){
7467876889
/* Only attempt the conversion to TEXT if there is an integer or real
7467976890
** representation (blob and NULL do not get converted) but no string
74680
- ** representation.
74681
- */
74682
- if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
74683
- sqlite3VdbeMemStringify(pRec, enc, 1);
76891
+ ** representation. It would be harmless to repeat the conversion if
76892
+ ** there is already a string rep, but it is pointless to waste those
76893
+ ** CPU cycles. */
76894
+ if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
76895
+ if( (pRec->flags&(MEM_Real|MEM_Int)) ){
76896
+ sqlite3VdbeMemStringify(pRec, enc, 1);
76897
+ }
7468476898
}
7468576899
pRec->flags &= ~(MEM_Real|MEM_Int);
7468676900
}
7468776901
}
7468876902
@@ -75004,11 +77218,11 @@
7500477218
Mem *pOut;
7500577219
assert( pOp->p2>0 );
7500677220
assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
7500777221
pOut = &p->aMem[pOp->p2];
7500877222
memAboutToChange(p, pOut);
75009
- if( VdbeMemDynamic(pOut) ){
77223
+ if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
7501077224
return out2PrereleaseWithClear(pOut);
7501177225
}else{
7501277226
pOut->flags = MEM_Int;
7501377227
return pOut;
7501477228
}
@@ -75136,41 +77350,43 @@
7513677350
}
7513777351
#endif
7513877352
7513977353
/* Sanity checking on other operands */
7514077354
#ifdef SQLITE_DEBUG
75141
- assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
75142
- if( (pOp->opflags & OPFLG_IN1)!=0 ){
75143
- assert( pOp->p1>0 );
75144
- assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
75145
- assert( memIsValid(&aMem[pOp->p1]) );
75146
- assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
75147
- REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
75148
- }
75149
- if( (pOp->opflags & OPFLG_IN2)!=0 ){
75150
- assert( pOp->p2>0 );
75151
- assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
75152
- assert( memIsValid(&aMem[pOp->p2]) );
75153
- assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
75154
- REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
75155
- }
75156
- if( (pOp->opflags & OPFLG_IN3)!=0 ){
75157
- assert( pOp->p3>0 );
75158
- assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
75159
- assert( memIsValid(&aMem[pOp->p3]) );
75160
- assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
75161
- REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
75162
- }
75163
- if( (pOp->opflags & OPFLG_OUT2)!=0 ){
75164
- assert( pOp->p2>0 );
75165
- assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
75166
- memAboutToChange(p, &aMem[pOp->p2]);
75167
- }
75168
- if( (pOp->opflags & OPFLG_OUT3)!=0 ){
75169
- assert( pOp->p3>0 );
75170
- assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
75171
- memAboutToChange(p, &aMem[pOp->p3]);
77355
+ {
77356
+ u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77357
+ if( (opProperty & OPFLG_IN1)!=0 ){
77358
+ assert( pOp->p1>0 );
77359
+ assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77360
+ assert( memIsValid(&aMem[pOp->p1]) );
77361
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77362
+ REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77363
+ }
77364
+ if( (opProperty & OPFLG_IN2)!=0 ){
77365
+ assert( pOp->p2>0 );
77366
+ assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77367
+ assert( memIsValid(&aMem[pOp->p2]) );
77368
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77369
+ REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77370
+ }
77371
+ if( (opProperty & OPFLG_IN3)!=0 ){
77372
+ assert( pOp->p3>0 );
77373
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77374
+ assert( memIsValid(&aMem[pOp->p3]) );
77375
+ assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77376
+ REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77377
+ }
77378
+ if( (opProperty & OPFLG_OUT2)!=0 ){
77379
+ assert( pOp->p2>0 );
77380
+ assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77381
+ memAboutToChange(p, &aMem[pOp->p2]);
77382
+ }
77383
+ if( (opProperty & OPFLG_OUT3)!=0 ){
77384
+ assert( pOp->p3>0 );
77385
+ assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77386
+ memAboutToChange(p, &aMem[pOp->p3]);
77387
+ }
7517277388
}
7517377389
#endif
7517477390
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
7517577391
pOrigOp = pOp;
7517677392
#endif
@@ -75406,12 +77622,10 @@
7540677622
** There is an implied "Halt 0 0 0" instruction inserted at the very end of
7540777623
** every program. So a jump past the last instruction of the program
7540877624
** is the same as executing Halt.
7540977625
*/
7541077626
case OP_Halt: {
75411
- const char *zType;
75412
- const char *zLogFmt;
7541377627
VdbeFrame *pFrame;
7541477628
int pcx;
7541577629
7541677630
pcx = (int)(pOp - aOp);
7541777631
if( pOp->p1==SQLITE_OK && p->pFrame ){
@@ -75436,38 +77650,32 @@
7543677650
break;
7543777651
}
7543877652
p->rc = pOp->p1;
7543977653
p->errorAction = (u8)pOp->p2;
7544077654
p->pc = pcx;
77655
+ assert( pOp->p5>=0 && pOp->p5<=4 );
7544177656
if( p->rc ){
7544277657
if( pOp->p5 ){
7544377658
static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
7544477659
"FOREIGN KEY" };
75445
- assert( pOp->p5>=1 && pOp->p5<=4 );
7544677660
testcase( pOp->p5==1 );
7544777661
testcase( pOp->p5==2 );
7544877662
testcase( pOp->p5==3 );
7544977663
testcase( pOp->p5==4 );
75450
- zType = azType[pOp->p5-1];
77664
+ sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
77665
+ if( pOp->p4.z ){
77666
+ p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
77667
+ }
7545177668
}else{
75452
- zType = 0;
75453
- }
75454
- assert( zType!=0 || pOp->p4.z!=0 );
75455
- zLogFmt = "abort at %d in [%s]: %s";
75456
- if( zType && pOp->p4.z ){
75457
- sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
75458
- }else if( pOp->p4.z ){
7545977669
sqlite3VdbeError(p, "%s", pOp->p4.z);
75460
- }else{
75461
- sqlite3VdbeError(p, "%s constraint failed", zType);
7546277670
}
75463
- sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
77671
+ sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
7546477672
}
7546577673
rc = sqlite3VdbeHalt(p);
7546677674
assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
7546777675
if( rc==SQLITE_BUSY ){
75468
- p->rc = rc = SQLITE_BUSY;
77676
+ p->rc = SQLITE_BUSY;
7546977677
}else{
7547077678
assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
7547177679
assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
7547277680
rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
7547377681
}
@@ -75529,14 +77737,11 @@
7552977737
pOp->p1 = sqlite3Strlen30(pOp->p4.z);
7553077738
7553177739
#ifndef SQLITE_OMIT_UTF16
7553277740
if( encoding!=SQLITE_UTF8 ){
7553377741
rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
75534
- if( rc ){
75535
- assert( rc==SQLITE_TOOBIG ); /* This is the only possible error here */
75536
- goto too_big;
75537
- }
77742
+ assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
7553877743
if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
7553977744
assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
7554077745
assert( VdbeMemDynamic(pOut)==0 );
7554177746
pOut->szMalloc = 0;
7554277747
pOut->flags |= MEM_Static;
@@ -75545,26 +77750,30 @@
7554577750
}
7554677751
pOp->p4type = P4_DYNAMIC;
7554777752
pOp->p4.z = pOut->z;
7554877753
pOp->p1 = pOut->n;
7554977754
}
77755
+ testcase( rc==SQLITE_TOOBIG );
7555077756
#endif
7555177757
if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
7555277758
goto too_big;
7555377759
}
77760
+ assert( rc==SQLITE_OK );
7555477761
/* Fall through to the next case, OP_String */
7555577762
}
7555677763
7555777764
/* Opcode: String P1 P2 P3 P4 P5
7555877765
** Synopsis: r[P2]='P4' (len=P1)
7555977766
**
7556077767
** The string value P4 of length P1 (bytes) is stored in register P2.
7556177768
**
75562
-** If P5!=0 and the content of register P3 is greater than zero, then
77769
+** If P3 is not zero and the content of register P3 is equal to P5, then
7556377770
** the datatype of the register P2 is converted to BLOB. The content is
7556477771
** the same sequence of bytes, it is merely interpreted as a BLOB instead
75565
-** of a string, as if it had been CAST.
77772
+** of a string, as if it had been CAST. In other words:
77773
+**
77774
+** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
7556677775
*/
7556777776
case OP_String: { /* out2 */
7556877777
assert( pOp->p4.z!=0 );
7556977778
pOut = out2Prerelease(p, pOp);
7557077779
pOut->flags = MEM_Str|MEM_Static|MEM_Term;
@@ -75571,16 +77780,15 @@
7557177780
pOut->z = pOp->p4.z;
7557277781
pOut->n = pOp->p1;
7557377782
pOut->enc = encoding;
7557477783
UPDATE_MAX_BLOBSIZE(pOut);
7557577784
#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
75576
- if( pOp->p5 ){
75577
- assert( pOp->p3>0 );
77785
+ if( pOp->p3>0 ){
7557877786
assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
7557977787
pIn3 = &aMem[pOp->p3];
7558077788
assert( pIn3->flags & MEM_Int );
75581
- if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
77789
+ if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
7558277790
}
7558377791
#endif
7558477792
break;
7558577793
}
7558677794
@@ -76478,15 +78686,17 @@
7647878686
}
7647978687
}else{
7648078688
/* Neither operand is NULL. Do a comparison. */
7648178689
affinity = pOp->p5 & SQLITE_AFF_MASK;
7648278690
if( affinity>=SQLITE_AFF_NUMERIC ){
76483
- if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76484
- applyNumericAffinity(pIn1,0);
76485
- }
76486
- if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76487
- applyNumericAffinity(pIn3,0);
78691
+ if( (flags1 | flags3)&MEM_Str ){
78692
+ if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78693
+ applyNumericAffinity(pIn1,0);
78694
+ }
78695
+ if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78696
+ applyNumericAffinity(pIn3,0);
78697
+ }
7648878698
}
7648978699
}else if( affinity==SQLITE_AFF_TEXT ){
7649078700
if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
7649178701
testcase( pIn1->flags & MEM_Int );
7649278702
testcase( pIn1->flags & MEM_Real );
@@ -77215,11 +79425,13 @@
7721579425
}
7721679426
nData += len;
7721779427
testcase( serial_type==127 );
7721879428
testcase( serial_type==128 );
7721979429
nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
77220
- }while( (--pRec)>=pData0 );
79430
+ if( pRec==pData0 ) break;
79431
+ pRec--;
79432
+ }while(1);
7722179433
7722279434
/* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
7722379435
** which determines the total number of bytes in the header. The varint
7722479436
** value is the size of the header in bytes including the size varint
7722579437
** itself. */
@@ -77363,11 +79575,11 @@
7736379575
db->autoCommit = 0;
7736479576
db->isTransactionSavepoint = 1;
7736579577
}else{
7736679578
db->nSavepoint++;
7736779579
}
77368
-
79580
+
7736979581
/* Link the new savepoint into the database handle's list. */
7737079582
pNew->pNext = db->pSavepoint;
7737179583
db->pSavepoint = pNew;
7737279584
pNew->nDeferredCons = db->nDeferredCons;
7737379585
pNew->nDeferredImmCons = db->nDeferredImmCons;
@@ -78720,13 +80932,13 @@
7872080932
** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
7872180933
** UPDATE operation. Otherwise (if the flag is clear) then this opcode
7872280934
** is part of an INSERT operation. The difference is only important to
7872380935
** the update hook.
7872480936
**
78725
-** Parameter P4 may point to a string containing the table-name, or
78726
-** may be NULL. If it is not NULL, then the update-hook
78727
-** (sqlite3.xUpdateCallback) is invoked following a successful insert.
80937
+** Parameter P4 may point to a Table structure, or may be NULL. If it is
80938
+** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
80939
+** following a successful insert.
7872880940
**
7872980941
** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
7873080942
** allocated, then ownership of P2 is transferred to the pseudo-cursor
7873180943
** and register P2 becomes ephemeral. If the cursor is changed, the
7873280944
** value of register P2 will then change. Make sure this does not
@@ -78748,21 +80960,23 @@
7874880960
i64 iKey; /* The integer ROWID or key for the record to be inserted */
7874980961
VdbeCursor *pC; /* Cursor to table into which insert is written */
7875080962
int nZero; /* Number of zero-bytes to append */
7875180963
int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
7875280964
const char *zDb; /* database name - used by the update hook */
78753
- const char *zTbl; /* Table name - used by the opdate hook */
80965
+ Table *pTab; /* Table structure - used by update and pre-update hooks */
7875480966
int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
7875580967
80968
+ op = 0;
7875680969
pData = &aMem[pOp->p2];
7875780970
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7875880971
assert( memIsValid(pData) );
7875980972
pC = p->apCsr[pOp->p1];
7876080973
assert( pC!=0 );
7876180974
assert( pC->eCurType==CURTYPE_BTREE );
7876280975
assert( pC->uc.pCursor!=0 );
7876380976
assert( pC->isTable );
80977
+ assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
7876480978
REGISTER_TRACE(pOp->p2, pData);
7876580979
7876680980
if( pOp->opcode==OP_Insert ){
7876780981
pKey = &aMem[pOp->p3];
7876880982
assert( pKey->flags & MEM_Int );
@@ -78771,10 +80985,32 @@
7877180985
iKey = pKey->u.i;
7877280986
}else{
7877380987
assert( pOp->opcode==OP_InsertInt );
7877480988
iKey = pOp->p3;
7877580989
}
80990
+
80991
+ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
80992
+ assert( pC->isTable );
80993
+ assert( pC->iDb>=0 );
80994
+ zDb = db->aDb[pC->iDb].zName;
80995
+ pTab = pOp->p4.pTab;
80996
+ assert( HasRowid(pTab) );
80997
+ op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
80998
+ }else{
80999
+ pTab = 0; /* Not needed. Silence a comiler warning. */
81000
+ zDb = 0; /* Not needed. Silence a compiler warning. */
81001
+ }
81002
+
81003
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81004
+ /* Invoke the pre-update hook, if any */
81005
+ if( db->xPreUpdateCallback
81006
+ && pOp->p4type==P4_TABLE
81007
+ && !(pOp->p5 & OPFLAG_ISUPDATE)
81008
+ ){
81009
+ sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, iKey, pOp->p2);
81010
+ }
81011
+#endif
7877681012
7877781013
if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
7877881014
if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
7877981015
if( pData->flags & MEM_Null ){
7878081016
pData->z = 0;
@@ -78795,22 +81031,17 @@
7879581031
pC->deferredMoveto = 0;
7879681032
pC->cacheStatus = CACHE_STALE;
7879781033
7879881034
/* Invoke the update-hook if required. */
7879981035
if( rc ) goto abort_due_to_error;
78800
- if( db->xUpdateCallback && pOp->p4.z ){
78801
- zDb = db->aDb[pC->iDb].zName;
78802
- zTbl = pOp->p4.z;
78803
- op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
78804
- assert( pC->isTable );
78805
- db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
78806
- assert( pC->iDb>=0 );
81036
+ if( db->xUpdateCallback && op ){
81037
+ db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, iKey);
7880781038
}
7880881039
break;
7880981040
}
7881081041
78811
-/* Opcode: Delete P1 P2 * P4 P5
81042
+/* Opcode: Delete P1 P2 P3 P4 P5
7881281043
**
7881381044
** Delete the record at which the P1 cursor is currently pointing.
7881481045
**
7881581046
** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
7881681047
** the cursor will be left pointing at either the next or the previous
@@ -78830,42 +81061,77 @@
7883081061
** change count is incremented (otherwise not).
7883181062
**
7883281063
** P1 must not be pseudo-table. It has to be a real table with
7883381064
** multiple rows.
7883481065
**
78835
-** If P4 is not NULL, then it is the name of the table that P1 is
78836
-** pointing to. The update hook will be invoked, if it exists.
78837
-** If P4 is not NULL then the P1 cursor must have been positioned
78838
-** using OP_NotFound prior to invoking this opcode.
81066
+** If P4 is not NULL then it points to a Table struture. In this case either
81067
+** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81068
+** have been positioned using OP_NotFound prior to invoking this opcode in
81069
+** this case. Specifically, if one is configured, the pre-update hook is
81070
+** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81071
+** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81072
+**
81073
+** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81074
+** of the memory cell that contains the value that the rowid of the row will
81075
+** be set to by the update.
7883981076
*/
7884081077
case OP_Delete: {
7884181078
VdbeCursor *pC;
78842
- u8 hasUpdateCallback;
81079
+ const char *zDb;
81080
+ Table *pTab;
81081
+ int opflags;
7884381082
81083
+ opflags = pOp->p2;
7884481084
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
7884581085
pC = p->apCsr[pOp->p1];
7884681086
assert( pC!=0 );
7884781087
assert( pC->eCurType==CURTYPE_BTREE );
7884881088
assert( pC->uc.pCursor!=0 );
7884981089
assert( pC->deferredMoveto==0 );
7885081090
78851
- hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
78852
- if( pOp->p5 && hasUpdateCallback ){
78853
- sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
78854
- }
78855
-
7885681091
#ifdef SQLITE_DEBUG
78857
- /* The seek operation that positioned the cursor prior to OP_Delete will
78858
- ** have also set the pC->movetoTarget field to the rowid of the row that
78859
- ** is being deleted */
78860
- if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
81092
+ if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81093
+ /* If p5 is zero, the seek operation that positioned the cursor prior to
81094
+ ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81095
+ ** the row that is being deleted */
7886181096
i64 iKey = 0;
7886281097
sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
78863
- assert( pC->movetoTarget==iKey );
81098
+ assert( pC->movetoTarget==iKey );
7886481099
}
7886581100
#endif
7886681101
81102
+ /* If the update-hook or pre-update-hook will be invoked, set zDb to
81103
+ ** the name of the db to pass as to it. Also set local pTab to a copy
81104
+ ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81105
+ ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81106
+ ** VdbeCursor.movetoTarget to the current rowid. */
81107
+ if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81108
+ assert( pC->iDb>=0 );
81109
+ assert( pOp->p4.pTab!=0 );
81110
+ zDb = db->aDb[pC->iDb].zName;
81111
+ pTab = pOp->p4.pTab;
81112
+ if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81113
+ sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
81114
+ }
81115
+ }else{
81116
+ zDb = 0; /* Not needed. Silence a compiler warning. */
81117
+ pTab = 0; /* Not needed. Silence a compiler warning. */
81118
+ }
81119
+
81120
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81121
+ /* Invoke the pre-update-hook if required. */
81122
+ if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81123
+ assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81124
+ sqlite3VdbePreUpdateHook(p, pC,
81125
+ (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81126
+ zDb, pTab, pC->movetoTarget,
81127
+ pOp->p3
81128
+ );
81129
+ }
81130
+ if( opflags & OPFLAG_ISNOOP ) break;
81131
+#endif
81132
+
7886781133
/* Only flags that can be set are SAVEPOISTION and AUXDELETE */
7886881134
assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
7886981135
assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
7887081136
assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
7887181137
@@ -78883,19 +81149,22 @@
7888381149
}
7888481150
#endif
7888581151
7888681152
rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
7888781153
pC->cacheStatus = CACHE_STALE;
81154
+ if( rc ) goto abort_due_to_error;
7888881155
7888981156
/* Invoke the update-hook if required. */
78890
- if( rc ) goto abort_due_to_error;
78891
- if( hasUpdateCallback ){
78892
- db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
78893
- db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
78894
- assert( pC->iDb>=0 );
81157
+ if( opflags & OPFLAG_NCHANGE ){
81158
+ p->nChange++;
81159
+ if( db->xUpdateCallback && HasRowid(pTab) ){
81160
+ db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81161
+ pC->movetoTarget);
81162
+ assert( pC->iDb>=0 );
81163
+ }
7889581164
}
78896
- if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
81165
+
7889781166
break;
7889881167
}
7889981168
/* Opcode: ResetCount * * * * *
7890081169
**
7890181170
** The value of the change counter is copied to the database handle
@@ -80371,25 +82640,10 @@
8037182640
if( pIn1->u.i==0 ) goto jump_to_p2;
8037282641
break;
8037382642
}
8037482643
8037582644
80376
-/* Opcode: JumpZeroIncr P1 P2 * * *
80377
-** Synopsis: if (r[P1]++)==0 ) goto P2
80378
-**
80379
-** The register P1 must contain an integer. If register P1 is initially
80380
-** zero, then jump to P2. Increment register P1 regardless of whether or
80381
-** not the jump is taken.
80382
-*/
80383
-case OP_JumpZeroIncr: { /* jump, in1 */
80384
- pIn1 = &aMem[pOp->p1];
80385
- assert( pIn1->flags&MEM_Int );
80386
- VdbeBranchTaken(pIn1->u.i==0, 2);
80387
- if( (pIn1->u.i++)==0 ) goto jump_to_p2;
80388
- break;
80389
-}
80390
-
8039182645
/* Opcode: AggStep0 * P2 P3 P4 P5
8039282646
** Synopsis: accum=r[P3] step(r[P2@P5])
8039382647
**
8039482648
** Execute the step function for an aggregate. The
8039582649
** function has P5 arguments. P4 is a pointer to the FuncDef
@@ -81278,15 +83532,16 @@
8127883532
#ifndef NDEBUG
8127983533
assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
8128083534
8128183535
#ifdef SQLITE_DEBUG
8128283536
if( db->flags & SQLITE_VdbeTrace ){
83537
+ u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
8128383538
if( rc!=0 ) printf("rc=%d\n",rc);
81284
- if( pOrigOp->opflags & (OPFLG_OUT2) ){
83539
+ if( opProperty & (OPFLG_OUT2) ){
8128583540
registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
8128683541
}
81287
- if( pOrigOp->opflags & OPFLG_OUT3 ){
83542
+ if( opProperty & OPFLG_OUT3 ){
8128883543
registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
8128983544
}
8129083545
}
8129183546
#endif /* SQLITE_DEBUG */
8129283547
#endif /* NDEBUG */
@@ -81386,10 +83641,12 @@
8138683641
int iOffset; /* Byte offset of blob in cursor data */
8138783642
int iCol; /* Table column this handle is open on */
8138883643
BtCursor *pCsr; /* Cursor pointing at blob row */
8138983644
sqlite3_stmt *pStmt; /* Statement holding cursor open */
8139083645
sqlite3 *db; /* The associated database */
83646
+ char *zDb; /* Database name */
83647
+ Table *pTab; /* Table object */
8139183648
};
8139283649
8139383650
8139483651
/*
8139583652
** This function is used by both blob_open() and blob_reopen(). It seeks
@@ -81529,10 +83786,12 @@
8152983786
}
8153083787
rc = SQLITE_ERROR;
8153183788
sqlite3BtreeLeaveAll(db);
8153283789
goto blob_open_out;
8153383790
}
83791
+ pBlob->pTab = pTab;
83792
+ pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
8153483793
8153583794
/* Now search pTab for the exact column. */
8153683795
for(iCol=0; iCol<pTab->nCol; iCol++) {
8153783796
if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
8153883797
break;
@@ -81750,10 +84009,34 @@
8175084009
/* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
8175184010
** returned, clean-up the statement handle.
8175284011
*/
8175384012
assert( db == v->db );
8175484013
sqlite3BtreeEnterCursor(p->pCsr);
84014
+
84015
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84016
+ if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84017
+ /* If a pre-update hook is registered and this is a write cursor,
84018
+ ** invoke it here.
84019
+ **
84020
+ ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84021
+ ** operation should really be an SQLITE_UPDATE. This is probably
84022
+ ** incorrect, but is convenient because at this point the new.* values
84023
+ ** are not easily obtainable. And for the sessions module, an
84024
+ ** SQLITE_UPDATE where the PK columns do not change is handled in the
84025
+ ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84026
+ ** slightly more efficient). Since you cannot write to a PK column
84027
+ ** using the incremental-blob API, this works. For the sessions module
84028
+ ** anyhow.
84029
+ */
84030
+ sqlite3_int64 iKey;
84031
+ sqlite3BtreeKeySize(p->pCsr, &iKey);
84032
+ sqlite3VdbePreUpdateHook(
84033
+ v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84034
+ );
84035
+ }
84036
+#endif
84037
+
8175584038
rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
8175684039
sqlite3BtreeLeaveCursor(p->pCsr);
8175784040
if( rc==SQLITE_ABORT ){
8175884041
sqlite3VdbeFinalize(v);
8175984042
p->pStmt = 0;
@@ -82767,11 +85050,10 @@
8276785050
int nField, /* Number of key fields in each record */
8276885051
VdbeCursor *pCsr /* Cursor that holds the new sorter */
8276985052
){
8277085053
int pgsz; /* Page size of main database */
8277185054
int i; /* Used to iterate through aTask[] */
82772
- int mxCache; /* Cache size */
8277385055
VdbeSorter *pSorter; /* The new sorter */
8277485056
KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
8277585057
int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
8277685058
int sz; /* Size of pSorter in bytes */
8277785059
int rc = SQLITE_OK;
@@ -82824,15 +85106,24 @@
8282485106
SortSubtask *pTask = &pSorter->aTask[i];
8282585107
pTask->pSorter = pSorter;
8282685108
}
8282785109
8282885110
if( !sqlite3TempInMemory(db) ){
85111
+ i64 mxCache; /* Cache size in bytes*/
8282985112
u32 szPma = sqlite3GlobalConfig.szPma;
8283085113
pSorter->mnPmaSize = szPma * pgsz;
85114
+
8283185115
mxCache = db->aDb[0].pSchema->cache_size;
82832
- if( mxCache<(int)szPma ) mxCache = (int)szPma;
82833
- pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
85116
+ if( mxCache<0 ){
85117
+ /* A negative cache-size value C indicates that the cache is abs(C)
85118
+ ** KiB in size. */
85119
+ mxCache = mxCache * -1024;
85120
+ }else{
85121
+ mxCache = mxCache * pgsz;
85122
+ }
85123
+ mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85124
+ pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
8283485125
8283585126
/* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
8283685127
** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
8283785128
** large heap allocations.
8283885129
*/
@@ -84592,10 +86883,19 @@
8459286883
*************************************************************************
8459386884
**
8459486885
** This file contains code use to implement an in-memory rollback journal.
8459586886
** The in-memory rollback journal is used to journal transactions for
8459686887
** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
86888
+**
86889
+** Update: The in-memory journal is also used to temporarily cache
86890
+** smaller journals that are not critical for power-loss recovery.
86891
+** For example, statement journals that are not too big will be held
86892
+** entirely in memory, thus reducing the number of file I/O calls, and
86893
+** more importantly, reducing temporary file creation events. If these
86894
+** journals become too large for memory, they are spilled to disk. But
86895
+** in the common case, they are usually small and no file I/O needs to
86896
+** occur.
8459786897
*/
8459886898
/* #include "sqliteInt.h" */
8459986899
8460086900
/* Forward references to internal structures */
8460186901
typedef struct MemJournal MemJournal;
@@ -85918,10 +88218,11 @@
8591888218
notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
8591988219
sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
8592088220
assert( pNC->nRef>=nRef );
8592188221
if( nRef!=pNC->nRef ){
8592288222
ExprSetProperty(pExpr, EP_VarSelect);
88223
+ pNC->ncFlags |= NC_VarSelect;
8592388224
}
8592488225
}
8592588226
break;
8592688227
}
8592788228
case TK_VARIABLE: {
@@ -87125,19 +89426,17 @@
8712589426
if( pToken ){
8712689427
if( nExtra==0 ){
8712789428
pNew->flags |= EP_IntValue;
8712889429
pNew->u.iValue = iValue;
8712989430
}else{
87130
- int c;
8713189431
pNew->u.zToken = (char*)&pNew[1];
8713289432
assert( pToken->z!=0 || pToken->n==0 );
8713389433
if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
8713489434
pNew->u.zToken[pToken->n] = 0;
87135
- if( dequote && nExtra>=3
87136
- && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
89435
+ if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89436
+ if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
8713789437
sqlite3Dequote(pNew->u.zToken);
87138
- if( c=='"' ) pNew->flags |= EP_DblQuoted;
8713989438
}
8714089439
}
8714189440
}
8714289441
#if SQLITE_MAX_EXPR_DEPTH>0
8714389442
pNew->nHeight = 1;
@@ -87215,10 +89514,26 @@
8721589514
if( p ) {
8721689515
sqlite3ExprCheckHeight(pParse, p->nHeight);
8721789516
}
8721889517
return p;
8721989518
}
89519
+
89520
+/*
89521
+** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
89522
+** do a memory allocation failure) then delete the pSelect object.
89523
+*/
89524
+SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
89525
+ if( pExpr ){
89526
+ pExpr->x.pSelect = pSelect;
89527
+ ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
89528
+ sqlite3ExprSetHeightAndFlags(pParse, pExpr);
89529
+ }else{
89530
+ assert( pParse->db->mallocFailed );
89531
+ sqlite3SelectDelete(pParse->db, pSelect);
89532
+ }
89533
+}
89534
+
8722089535
8722189536
/*
8722289537
** If the expression is always either TRUE or FALSE (respectively),
8722389538
** then return 1. If one cannot determine the truth value of the
8722489539
** expression at compile-time return 0.
@@ -87376,12 +89691,12 @@
8737689691
}
8737789692
8737889693
/*
8737989694
** Recursively delete an expression tree.
8738089695
*/
87381
-SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
87382
- if( p==0 ) return;
89696
+static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
89697
+ assert( p!=0 );
8738389698
/* Sanity check: Assert that the IntValue is non-negative if it exists */
8738489699
assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
8738589700
if( !ExprHasProperty(p, EP_TokenOnly) ){
8738689701
/* The Expr.x union is never used at the same time as Expr.pRight */
8738789702
assert( p->x.pList==0 || p->pRight==0 );
@@ -87395,10 +89710,13 @@
8739589710
}
8739689711
}
8739789712
if( !ExprHasProperty(p, EP_Static) ){
8739889713
sqlite3DbFree(db, p);
8739989714
}
89715
+}
89716
+SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
89717
+ if( p ) sqlite3ExprDeleteNN(db, p);
8740089718
}
8740189719
8740289720
/*
8740389721
** Return the number of bytes allocated for the expression structure
8740489722
** passed as the first argument. This is always one of EXPR_FULLSIZE,
@@ -87447,11 +89765,11 @@
8744789765
static int dupedExprStructSize(Expr *p, int flags){
8744889766
int nSize;
8744989767
assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
8745089768
assert( EXPR_FULLSIZE<=0xfff );
8745189769
assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
87452
- if( 0==(flags&EXPRDUP_REDUCE) ){
89770
+ if( 0==flags ){
8745389771
nSize = EXPR_FULLSIZE;
8745489772
}else{
8745589773
assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
8745689774
assert( !ExprHasProperty(p, EP_FromJoin) );
8745789775
assert( !ExprHasProperty(p, EP_MemToken) );
@@ -87509,92 +89827,92 @@
8750989827
** to store the copy of expression p, the copies of p->u.zToken
8751089828
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
8751189829
** if any. Before returning, *pzBuffer is set to the first byte past the
8751289830
** portion of the buffer copied into by this function.
8751389831
*/
87514
-static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
87515
- Expr *pNew = 0; /* Value to return */
87516
- assert( flags==0 || flags==EXPRDUP_REDUCE );
89832
+static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
89833
+ Expr *pNew; /* Value to return */
89834
+ u8 *zAlloc; /* Memory space from which to build Expr object */
89835
+ u32 staticFlag; /* EP_Static if space not obtained from malloc */
89836
+
8751789837
assert( db!=0 );
87518
- if( p ){
87519
- const int isReduced = (flags&EXPRDUP_REDUCE);
87520
- u8 *zAlloc;
87521
- u32 staticFlag = 0;
87522
-
87523
- assert( pzBuffer==0 || isReduced );
87524
-
87525
- /* Figure out where to write the new Expr structure. */
87526
- if( pzBuffer ){
87527
- zAlloc = *pzBuffer;
87528
- staticFlag = EP_Static;
87529
- }else{
87530
- zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, flags));
87531
- }
87532
- pNew = (Expr *)zAlloc;
87533
-
87534
- if( pNew ){
87535
- /* Set nNewSize to the size allocated for the structure pointed to
87536
- ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
87537
- ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
87538
- ** by the copy of the p->u.zToken string (if any).
87539
- */
87540
- const unsigned nStructSize = dupedExprStructSize(p, flags);
87541
- const int nNewSize = nStructSize & 0xfff;
87542
- int nToken;
87543
- if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
87544
- nToken = sqlite3Strlen30(p->u.zToken) + 1;
87545
- }else{
87546
- nToken = 0;
87547
- }
87548
- if( isReduced ){
87549
- assert( ExprHasProperty(p, EP_Reduced)==0 );
87550
- memcpy(zAlloc, p, nNewSize);
87551
- }else{
87552
- u32 nSize = (u32)exprStructSize(p);
87553
- memcpy(zAlloc, p, nSize);
87554
- if( nSize<EXPR_FULLSIZE ){
87555
- memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
87556
- }
87557
- }
87558
-
87559
- /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
87560
- pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
87561
- pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
87562
- pNew->flags |= staticFlag;
87563
-
87564
- /* Copy the p->u.zToken string, if any. */
87565
- if( nToken ){
87566
- char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
87567
- memcpy(zToken, p->u.zToken, nToken);
87568
- }
87569
-
87570
- if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
87571
- /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
87572
- if( ExprHasProperty(p, EP_xIsSelect) ){
87573
- pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
87574
- }else{
87575
- pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
87576
- }
87577
- }
87578
-
87579
- /* Fill in pNew->pLeft and pNew->pRight. */
87580
- if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
87581
- zAlloc += dupedExprNodeSize(p, flags);
87582
- if( ExprHasProperty(pNew, EP_Reduced) ){
87583
- pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
87584
- pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
87585
- }
87586
- if( pzBuffer ){
87587
- *pzBuffer = zAlloc;
87588
- }
87589
- }else{
87590
- if( !ExprHasProperty(p, EP_TokenOnly) ){
87591
- pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
87592
- pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
87593
- }
87594
- }
87595
-
89838
+ assert( p );
89839
+ assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
89840
+ assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
89841
+
89842
+ /* Figure out where to write the new Expr structure. */
89843
+ if( pzBuffer ){
89844
+ zAlloc = *pzBuffer;
89845
+ staticFlag = EP_Static;
89846
+ }else{
89847
+ zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
89848
+ staticFlag = 0;
89849
+ }
89850
+ pNew = (Expr *)zAlloc;
89851
+
89852
+ if( pNew ){
89853
+ /* Set nNewSize to the size allocated for the structure pointed to
89854
+ ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
89855
+ ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
89856
+ ** by the copy of the p->u.zToken string (if any).
89857
+ */
89858
+ const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
89859
+ const int nNewSize = nStructSize & 0xfff;
89860
+ int nToken;
89861
+ if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89862
+ nToken = sqlite3Strlen30(p->u.zToken) + 1;
89863
+ }else{
89864
+ nToken = 0;
89865
+ }
89866
+ if( dupFlags ){
89867
+ assert( ExprHasProperty(p, EP_Reduced)==0 );
89868
+ memcpy(zAlloc, p, nNewSize);
89869
+ }else{
89870
+ u32 nSize = (u32)exprStructSize(p);
89871
+ memcpy(zAlloc, p, nSize);
89872
+ if( nSize<EXPR_FULLSIZE ){
89873
+ memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
89874
+ }
89875
+ }
89876
+
89877
+ /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
89878
+ pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
89879
+ pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
89880
+ pNew->flags |= staticFlag;
89881
+
89882
+ /* Copy the p->u.zToken string, if any. */
89883
+ if( nToken ){
89884
+ char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
89885
+ memcpy(zToken, p->u.zToken, nToken);
89886
+ }
89887
+
89888
+ if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
89889
+ /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
89890
+ if( ExprHasProperty(p, EP_xIsSelect) ){
89891
+ pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
89892
+ }else{
89893
+ pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
89894
+ }
89895
+ }
89896
+
89897
+ /* Fill in pNew->pLeft and pNew->pRight. */
89898
+ if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
89899
+ zAlloc += dupedExprNodeSize(p, dupFlags);
89900
+ if( ExprHasProperty(pNew, EP_Reduced) ){
89901
+ pNew->pLeft = p->pLeft ?
89902
+ exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
89903
+ pNew->pRight = p->pRight ?
89904
+ exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
89905
+ }
89906
+ if( pzBuffer ){
89907
+ *pzBuffer = zAlloc;
89908
+ }
89909
+ }else{
89910
+ if( !ExprHasProperty(p, EP_TokenOnly) ){
89911
+ pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
89912
+ pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
89913
+ }
8759689914
}
8759789915
}
8759889916
return pNew;
8759989917
}
8760089918
@@ -87642,11 +89960,11 @@
8764289960
** truncated version of the usual Expr structure that will be stored as
8764389961
** part of the in-memory representation of the database schema.
8764489962
*/
8764589963
SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
8764689964
assert( flags==0 || flags==EXPRDUP_REDUCE );
87647
- return exprDup(db, p, flags, 0);
89965
+ return p ? exprDup(db, p, flags, 0) : 0;
8764889966
}
8764989967
SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
8765089968
ExprList *pNew;
8765189969
struct ExprList_item *pItem, *pOldItem;
8765289970
int i;
@@ -87864,11 +90182,11 @@
8786490182
struct ExprList_item *pItem;
8786590183
assert( pList->nExpr>0 );
8786690184
pItem = &pList->a[pList->nExpr-1];
8786790185
assert( pItem->zName==0 );
8786890186
pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
87869
- if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
90187
+ if( dequote ) sqlite3Dequote(pItem->zName);
8787090188
}
8787190189
}
8787290190
8787390191
/*
8787490192
** Set the ExprList.a[].zSpan element of the most recently added item
@@ -87913,22 +90231,24 @@
8791390231
}
8791490232
8791590233
/*
8791690234
** Delete an entire expression list.
8791790235
*/
87918
-SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90236
+static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
8791990237
int i;
8792090238
struct ExprList_item *pItem;
87921
- if( pList==0 ) return;
8792290239
assert( pList->a!=0 || pList->nExpr==0 );
8792390240
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
8792490241
sqlite3ExprDelete(db, pItem->pExpr);
8792590242
sqlite3DbFree(db, pItem->zName);
8792690243
sqlite3DbFree(db, pItem->zSpan);
8792790244
}
8792890245
sqlite3DbFree(db, pList->a);
8792990246
sqlite3DbFree(db, pList);
90247
+}
90248
+SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90249
+ if( pList ) exprListDeleteNN(db, pList);
8793090250
}
8793190251
8793290252
/*
8793390253
** Return the bitwise-OR of all Expr.flags fields in the given
8793490254
** ExprList.
@@ -88970,10 +91290,23 @@
8897091290
#endif
8897191291
}
8897291292
}
8897391293
}
8897491294
91295
+#if defined(SQLITE_DEBUG)
91296
+/*
91297
+** Verify the consistency of the column cache
91298
+*/
91299
+static int cacheIsValid(Parse *pParse){
91300
+ int i, n;
91301
+ for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91302
+ if( pParse->aColCache[i].iReg>0 ) n++;
91303
+ }
91304
+ return n==pParse->nColCache;
91305
+}
91306
+#endif
91307
+
8897591308
/*
8897691309
** Clear a cache entry.
8897791310
*/
8897891311
static void cacheEntryClear(Parse *pParse, struct yColCache *p){
8897991312
if( p->tempReg ){
@@ -88980,10 +91313,13 @@
8898091313
if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
8898191314
pParse->aTempReg[pParse->nTempReg++] = p->iReg;
8898291315
}
8898391316
p->tempReg = 0;
8898491317
}
91318
+ p->iReg = 0;
91319
+ pParse->nColCache--;
91320
+ assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
8898591321
}
8898691322
8898791323
8898891324
/*
8898991325
** Record in the column cache that a particular column from a
@@ -89023,10 +91359,12 @@
8902391359
p->iTable = iTab;
8902491360
p->iColumn = iCol;
8902591361
p->iReg = iReg;
8902691362
p->tempReg = 0;
8902791363
p->lru = pParse->iCacheCnt++;
91364
+ pParse->nColCache++;
91365
+ assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
8902891366
return;
8902991367
}
8903091368
}
8903191369
8903291370
/* Replace the last recently used */
@@ -89044,28 +91382,27 @@
8904491382
p->iTable = iTab;
8904591383
p->iColumn = iCol;
8904691384
p->iReg = iReg;
8904791385
p->tempReg = 0;
8904891386
p->lru = pParse->iCacheCnt++;
91387
+ assert( cacheIsValid(pParse) );
8904991388
return;
8905091389
}
8905191390
}
8905291391
8905391392
/*
8905491393
** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
8905591394
** Purge the range of registers from the column cache.
8905691395
*/
8905791396
SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
89058
- int i;
89059
- int iLast = iReg + nReg - 1;
8906091397
struct yColCache *p;
89061
- for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89062
- int r = p->iReg;
89063
- if( r>=iReg && r<=iLast ){
89064
- cacheEntryClear(pParse, p);
89065
- p->iReg = 0;
89066
- }
91398
+ if( iReg<=0 || pParse->nColCache==0 ) return;
91399
+ p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91400
+ while(1){
91401
+ if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91402
+ if( p==pParse->aColCache ) break;
91403
+ p--;
8906791404
}
8906891405
}
8906991406
8907091407
/*
8907191408
** Remember the current column cache context. Any new entries added
@@ -89097,11 +91434,10 @@
8909791434
}
8909891435
#endif
8909991436
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
8910091437
if( p->iReg && p->iLevel>pParse->iCacheLevel ){
8910191438
cacheEntryClear(pParse, p);
89102
- p->iReg = 0;
8910391439
}
8910491440
}
8910591441
}
8910691442
8910791443
/*
@@ -89232,11 +91568,10 @@
8923291568
}
8923391569
#endif
8923491570
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
8923591571
if( p->iReg ){
8923691572
cacheEntryClear(pParse, p);
89237
- p->iReg = 0;
8923891573
}
8923991574
}
8924091575
}
8924191576
8924291577
/*
@@ -89273,10 +91608,11 @@
8927391608
if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
8927491609
}
8927591610
return 0;
8927691611
}
8927791612
#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
91613
+
8927891614
8927991615
/*
8928091616
** Convert an expression node to a TK_REGISTER
8928191617
*/
8928291618
static void exprToRegister(Expr *p, int iReg){
@@ -93567,43 +95903,46 @@
9356795903
*/
9356895904
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
9356995905
analysisInfo sInfo;
9357095906
HashElem *i;
9357195907
char *zSql;
93572
- int rc;
95908
+ int rc = SQLITE_OK;
9357395909
9357495910
assert( iDb>=0 && iDb<db->nDb );
9357595911
assert( db->aDb[iDb].pBt!=0 );
9357695912
9357795913
/* Clear any prior statistics */
9357895914
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
9357995915
for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
9358095916
Index *pIdx = sqliteHashData(i);
93581
- sqlite3DefaultRowEst(pIdx);
95917
+ pIdx->aiRowLogEst[0] = 0;
9358295918
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
9358395919
sqlite3DeleteIndexSamples(db, pIdx);
9358495920
pIdx->aSample = 0;
9358595921
#endif
9358695922
}
9358795923
93588
- /* Check to make sure the sqlite_stat1 table exists */
95924
+ /* Load new statistics out of the sqlite_stat1 table */
9358995925
sInfo.db = db;
9359095926
sInfo.zDatabase = db->aDb[iDb].zName;
93591
- if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
93592
- return SQLITE_ERROR;
95927
+ if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
95928
+ zSql = sqlite3MPrintf(db,
95929
+ "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
95930
+ if( zSql==0 ){
95931
+ rc = SQLITE_NOMEM_BKPT;
95932
+ }else{
95933
+ rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
95934
+ sqlite3DbFree(db, zSql);
95935
+ }
9359395936
}
9359495937
93595
- /* Load new statistics out of the sqlite_stat1 table */
93596
- zSql = sqlite3MPrintf(db,
93597
- "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
93598
- if( zSql==0 ){
93599
- rc = SQLITE_NOMEM_BKPT;
93600
- }else{
93601
- rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
93602
- sqlite3DbFree(db, zSql);
93603
- }
93604
-
95938
+ /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
95939
+ assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95940
+ for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95941
+ Index *pIdx = sqliteHashData(i);
95942
+ if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
95943
+ }
9360595944
9360695945
/* Load the statistics from the sqlite_stat4 table. */
9360795946
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
9360895947
if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
9360995948
db->lookaside.bDisable++;
@@ -95067,20 +97406,14 @@
9506797406
** contains lookaside memory. (Table objects in the schema do not use
9506897407
** lookaside memory, but some ephemeral Table objects do.) Or the
9506997408
** db parameter can be used with db->pnBytesFreed to measure the memory
9507097409
** used by the Table object.
9507197410
*/
95072
-SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
97411
+static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
9507397412
Index *pIndex, *pNext;
9507497413
TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
9507597414
95076
- assert( !pTable || pTable->nRef>0 );
95077
-
95078
- /* Do not delete the table until the reference count reaches zero. */
95079
- if( !pTable ) return;
95080
- if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
95081
-
9508297415
/* Record the number of outstanding lookaside allocations in schema Tables
9508397416
** prior to doing any free() operations. Since schema Tables do not use
9508497417
** lookaside, this number should not change. */
9508597418
TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
9508697419
db->lookaside.nOut : 0 );
@@ -95116,10 +97449,17 @@
9511697449
sqlite3DbFree(db, pTable);
9511797450
9511897451
/* Verify that no lookaside memory was used by schema tables */
9511997452
assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
9512097453
}
97454
+SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
97455
+ /* Do not delete the table until the reference count reaches zero. */
97456
+ if( !pTable ) return;
97457
+ if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
97458
+ deleteTable(db, pTable);
97459
+}
97460
+
9512197461
9512297462
/*
9512397463
** Unlink the given table from the hash tables and the delete the
9512497464
** table structure with all its indices and foreign keys.
9512597465
*/
@@ -95561,10 +97901,11 @@
9556197901
pCol->szEst = 1;
9556297902
}else{
9556397903
zType = z + sqlite3Strlen30(z) + 1;
9556497904
memcpy(zType, pType->z, pType->n);
9556597905
zType[pType->n] = 0;
97906
+ sqlite3Dequote(zType);
9556697907
pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
9556797908
pCol->colFlags |= COLFLAG_HASTYPE;
9556897909
}
9556997910
p->nCol++;
9557097911
pParse->constraintName.n = 0;
@@ -96695,11 +99036,11 @@
9669599036
assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
9669699037
}else{
9669799038
pTable->nCol = 0;
9669899039
nErr++;
9669999040
}
96700
- if( pSelTab ) sqlite3DeleteTable(db, pSelTab);
99041
+ sqlite3DeleteTable(db, pSelTab);
9670199042
sqlite3SelectDelete(db, pSel);
9670299043
db->lookaside.bDisable--;
9670399044
} else {
9670499045
nErr++;
9670599046
}
@@ -97248,10 +99589,11 @@
9724899589
tnum = memRootPage;
9724999590
}else{
9725099591
tnum = pIndex->tnum;
9725199592
}
9725299593
pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
99594
+ assert( pKey!=0 || db->mallocFailed || pParse->nErr );
9725399595
9725499596
/* Open the sorter cursor if we are to use one. */
9725599597
iSorter = pParse->nTab++;
9725699598
sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
9725799599
sqlite3KeyInfoRef(pKey), P4_KEYINFO);
@@ -97271,12 +99613,11 @@
9727199613
sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
9727299614
(char *)pKey, P4_KEYINFO);
9727399615
sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
9727499616
9727599617
addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
97276
- assert( pKey!=0 || db->mallocFailed || pParse->nErr );
97277
- if( IsUniqueIndex(pIndex) && pKey!=0 ){
99618
+ if( IsUniqueIndex(pIndex) ){
9727899619
int j2 = sqlite3VdbeCurrentAddr(v) + 3;
9727999620
sqlite3VdbeGoto(v, j2);
9728099621
addr2 = sqlite3VdbeCurrentAddr(v);
9728199622
sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
9728299623
pIndex->nKeyCol); VdbeCoverage(v);
@@ -99526,11 +101867,11 @@
99526101867
99527101868
/* Check that there isn't an ORDER BY without a LIMIT clause.
99528101869
*/
99529101870
if( pOrderBy && (pLimit == 0) ) {
99530101871
sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
99531
- goto limit_where_cleanup_2;
101872
+ goto limit_where_cleanup;
99532101873
}
99533101874
99534101875
/* We only need to generate a select expression if there
99535101876
** is a limit/offset term to enforce.
99536101877
*/
@@ -99548,44 +101889,34 @@
99548101889
** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
99549101890
** );
99550101891
*/
99551101892
99552101893
pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
99553
- if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
101894
+ if( pSelectRowid == 0 ) goto limit_where_cleanup;
99554101895
pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
99555
- if( pEList == 0 ) goto limit_where_cleanup_2;
101896
+ if( pEList == 0 ) goto limit_where_cleanup;
99556101897
99557101898
/* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
99558101899
** and the SELECT subtree. */
99559101900
pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
99560101901
if( pSelectSrc == 0 ) {
99561101902
sqlite3ExprListDelete(pParse->db, pEList);
99562
- goto limit_where_cleanup_2;
101903
+ goto limit_where_cleanup;
99563101904
}
99564101905
99565101906
/* generate the SELECT expression tree. */
99566101907
pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
99567101908
pOrderBy,0,pLimit,pOffset);
99568101909
if( pSelect == 0 ) return 0;
99569101910
99570101911
/* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
99571101912
pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
99572
- if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
99573
- pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
99574
- if( pInClause == 0 ) goto limit_where_cleanup_1;
99575
-
99576
- pInClause->x.pSelect = pSelect;
99577
- pInClause->flags |= EP_xIsSelect;
99578
- sqlite3ExprSetHeightAndFlags(pParse, pInClause);
101913
+ pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
101914
+ sqlite3PExprAddSelect(pParse, pInClause, pSelect);
99579101915
return pInClause;
99580101916
99581
- /* something went wrong. clean up anything allocated. */
99582
-limit_where_cleanup_1:
99583
- sqlite3SelectDelete(pParse->db, pSelect);
99584
- return 0;
99585
-
99586
-limit_where_cleanup_2:
101917
+limit_where_cleanup:
99587101918
sqlite3ExprDelete(pParse->db, pWhere);
99588101919
sqlite3ExprListDelete(pParse->db, pOrderBy);
99589101920
sqlite3ExprDelete(pParse->db, pLimit);
99590101921
sqlite3ExprDelete(pParse->db, pOffset);
99591101922
return 0;
@@ -99632,15 +101963,16 @@
99632101963
int iEphCur = 0; /* Ephemeral table holding all primary key values */
99633101964
int iRowSet = 0; /* Register for rowset of rows to delete */
99634101965
int addrBypass = 0; /* Address of jump over the delete logic */
99635101966
int addrLoop = 0; /* Top of the delete loop */
99636101967
int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
101968
+ int bComplex; /* True if there are triggers or FKs or
101969
+ ** subqueries in the WHERE clause */
99637101970
99638101971
#ifndef SQLITE_OMIT_TRIGGER
99639101972
int isView; /* True if attempting to delete from a view */
99640101973
Trigger *pTrigger; /* List of table triggers, if required */
99641
- int bComplex; /* True if there are either triggers or FKs */
99642101974
#endif
99643101975
99644101976
memset(&sContext, 0, sizeof(sContext));
99645101977
db = pParse->db;
99646101978
if( pParse->nErr || db->mallocFailed ){
@@ -99664,11 +101996,10 @@
99664101996
isView = pTab->pSelect!=0;
99665101997
bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
99666101998
#else
99667101999
# define pTrigger 0
99668102000
# define isView 0
99669
-# define bComplex 0
99670102001
#endif
99671102002
#ifdef SQLITE_OMIT_VIEW
99672102003
# undef isView
99673102004
# define isView 0
99674102005
#endif
@@ -99749,10 +102080,13 @@
99749102080
** API function sqlite3_count_changes) to be set incorrectly. */
99750102081
if( rcauth==SQLITE_OK
99751102082
&& pWhere==0
99752102083
&& !bComplex
99753102084
&& !IsVirtual(pTab)
102085
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102086
+ && db->xPreUpdateCallback==0
102087
+#endif
99754102088
){
99755102089
assert( !isView );
99756102090
sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
99757102091
if( HasRowid(pTab) ){
99758102092
sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
@@ -99763,11 +102097,12 @@
99763102097
sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
99764102098
}
99765102099
}else
99766102100
#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
99767102101
{
99768
- u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
102102
+ u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
102103
+ if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
99769102104
wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
99770102105
if( HasRowid(pTab) ){
99771102106
/* For a rowid table, initialize the RowSet to an empty set */
99772102107
pPk = 0;
99773102108
nPk = 1;
@@ -100098,18 +102433,23 @@
100098102433
sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
100099102434
}
100100102435
100101102436
/* Delete the index and table entries. Skip this step if pTab is really
100102102437
** a view (in which case the only effect of the DELETE statement is to
100103
- ** fire the INSTEAD OF triggers). */
102438
+ ** fire the INSTEAD OF triggers).
102439
+ **
102440
+ ** If variable 'count' is non-zero, then this OP_Delete instruction should
102441
+ ** invoke the update-hook. The pre-update-hook, on the other hand should
102442
+ ** be invoked unless table pTab is a system table. The difference is that
102443
+ ** the update-hook is not invoked for rows removed by REPLACE, but the
102444
+ ** pre-update-hook is.
102445
+ */
100104102446
if( pTab->pSelect==0 ){
100105102447
u8 p5 = 0;
100106102448
sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
100107102449
sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
100108
- if( count ){
100109
- sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
100110
- }
102450
+ sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
100111102451
if( eMode!=ONEPASS_OFF ){
100112102452
sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
100113102453
}
100114102454
if( iIdxNoSeek>=0 ){
100115102455
sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
@@ -101669,10 +104009,18 @@
101669104009
static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
101670104010
const char *zFile = (const char *)sqlite3_value_text(argv[0]);
101671104011
const char *zProc;
101672104012
sqlite3 *db = sqlite3_context_db_handle(context);
101673104013
char *zErrMsg = 0;
104014
+
104015
+ /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
104016
+ ** flag is set. See the sqlite3_enable_load_extension() API.
104017
+ */
104018
+ if( (db->flags & SQLITE_LoadExtFunc)==0 ){
104019
+ sqlite3_result_error(context, "not authorized", -1);
104020
+ return;
104021
+ }
101674104022
101675104023
if( argc==2 ){
101676104024
zProc = (const char *)sqlite3_value_text(argv[1]);
101677104025
}else{
101678104026
zProc = 0;
@@ -103268,11 +105616,10 @@
103268105616
103269105617
action = pFKey->aAction[iAction];
103270105618
if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
103271105619
return 0;
103272105620
}
103273
-
103274105621
pTrigger = pFKey->apTrigger[iAction];
103275105622
103276105623
if( action!=OE_None && !pTrigger ){
103277105624
char const *zFrom; /* Name of child table */
103278105625
int nFrom; /* Length in bytes of zFrom */
@@ -104945,13 +107292,22 @@
104945107292
pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
104946107293
}
104947107294
if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
104948107295
sqlite3MultiWrite(pParse);
104949107296
sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
104950
- regNewData, 1, 0, OE_Replace,
104951
- ONEPASS_SINGLE, -1);
107297
+ regNewData, 1, 0, OE_Replace, 1, -1);
104952107298
}else{
107299
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107300
+ if( HasRowid(pTab) ){
107301
+ /* This OP_Delete opcode fires the pre-update-hook only. It does
107302
+ ** not modify the b-tree. It is more efficient to let the coming
107303
+ ** OP_Insert replace the existing entry than it is to delete the
107304
+ ** existing entry and then insert a new one. */
107305
+ sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107306
+ sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107307
+ }
107308
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
104953107309
if( pTab->pIndex ){
104954107310
sqlite3MultiWrite(pParse);
104955107311
sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
104956107312
}
104957107313
}
@@ -105217,11 +107573,11 @@
105217107573
if( useSeekResult ){
105218107574
pik_flags |= OPFLAG_USESEEKRESULT;
105219107575
}
105220107576
sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
105221107577
if( !pParse->nested ){
105222
- sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
107578
+ sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
105223107579
}
105224107580
sqlite3VdbeChangeP5(v, pik_flags);
105225107581
}
105226107582
105227107583
/*
@@ -105617,11 +107973,11 @@
105617107973
addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
105618107974
assert( (pDest->tabFlags & TF_Autoincrement)==0 );
105619107975
}
105620107976
sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
105621107977
sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
105622
- pDest->zName, 0);
107978
+ (char*)pDest, P4_TABLE);
105623107979
sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
105624107980
sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
105625107981
sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
105626107982
sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
105627107983
}else{
@@ -106856,12 +109212,13 @@
106856109212
if( pzErrMsg ) *pzErrMsg = 0;
106857109213
106858109214
/* Ticket #1863. To avoid a creating security problems for older
106859109215
** applications that relink against newer versions of SQLite, the
106860109216
** ability to run load_extension is turned off by default. One
106861
- ** must call sqlite3_enable_load_extension() to turn on extension
106862
- ** loading. Otherwise you get the following error.
109217
+ ** must call either sqlite3_enable_load_extension(db) or
109218
+ ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109219
+ ** to turn on extension loading.
106863109220
*/
106864109221
if( (db->flags & SQLITE_LoadExtension)==0 ){
106865109222
if( pzErrMsg ){
106866109223
*pzErrMsg = sqlite3_mprintf("not authorized");
106867109224
}
@@ -106996,13 +109353,13 @@
106996109353
** default so as not to open security holes in older applications.
106997109354
*/
106998109355
SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
106999109356
sqlite3_mutex_enter(db->mutex);
107000109357
if( onoff ){
107001
- db->flags |= SQLITE_LoadExtension;
109358
+ db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
107002109359
}else{
107003
- db->flags &= ~SQLITE_LoadExtension;
109360
+ db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
107004109361
}
107005109362
sqlite3_mutex_leave(db->mutex);
107006109363
return SQLITE_OK;
107007109364
}
107008109365
@@ -110575,11 +112932,11 @@
110575112932
sqlite3ExprListDelete(db, p->pGroupBy);
110576112933
sqlite3ExprDelete(db, p->pHaving);
110577112934
sqlite3ExprListDelete(db, p->pOrderBy);
110578112935
sqlite3ExprDelete(db, p->pLimit);
110579112936
sqlite3ExprDelete(db, p->pOffset);
110580
- sqlite3WithDelete(db, p->pWith);
112937
+ if( p->pWith ) sqlite3WithDelete(db, p->pWith);
110581112938
if( bFree ) sqlite3DbFree(db, p);
110582112939
p = pPrior;
110583112940
bFree = 1;
110584112941
}
110585112942
}
@@ -110670,11 +113027,11 @@
110670113027
110671113028
/*
110672113029
** Delete the given Select structure and all of its substructures.
110673113030
*/
110674113031
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
110675
- clearSelect(db, p, 1);
113032
+ if( p ) clearSelect(db, p, 1);
110676113033
}
110677113034
110678113035
/*
110679113036
** Return a pointer to the right-most SELECT statement in a compound.
110680113037
*/
@@ -112290,23 +114647,23 @@
112290114647
112291114648
/*
112292114649
** Get a VDBE for the given parser context. Create a new one if necessary.
112293114650
** If an error occurs, return NULL and leave a message in pParse.
112294114651
*/
112295
-SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
112296
- Vdbe *v = pParse->pVdbe;
112297
- if( v==0 ){
112298
- v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
112299
- if( v ) sqlite3VdbeAddOp0(v, OP_Init);
112300
- if( pParse->pToplevel==0
112301
- && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
112302
- ){
112303
- pParse->okConstFactor = 1;
112304
- }
112305
-
114652
+static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
114653
+ Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
114654
+ if( v ) sqlite3VdbeAddOp0(v, OP_Init);
114655
+ if( pParse->pToplevel==0
114656
+ && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
114657
+ ){
114658
+ pParse->okConstFactor = 1;
112306114659
}
112307114660
return v;
114661
+}
114662
+SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
114663
+ Vdbe *v = pParse->pVdbe;
114664
+ return v ? v : allocVdbe(pParse);
112308114665
}
112309114666
112310114667
112311114668
/*
112312114669
** Compute the iLimit and iOffset fields of the SELECT based on the
@@ -114286,16 +116643,22 @@
114286116643
Expr *pWhere, /* The WHERE clause of the outer query */
114287116644
int iCursor /* Cursor number of the subquery */
114288116645
){
114289116646
Expr *pNew;
114290116647
int nChng = 0;
116648
+ Select *pX; /* For looping over compound SELECTs in pSubq */
114291116649
if( pWhere==0 ) return 0;
114292
- if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
114293
- return 0; /* restrictions (1) and (2) */
116650
+ for(pX=pSubq; pX; pX=pX->pPrior){
116651
+ if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
116652
+ testcase( pX->selFlags & SF_Aggregate );
116653
+ testcase( pX->selFlags & SF_Recursive );
116654
+ testcase( pX!=pSubq );
116655
+ return 0; /* restrictions (1) and (2) */
116656
+ }
114294116657
}
114295116658
if( pSubq->pLimit!=0 ){
114296
- return 0; /* restriction (3) */
116659
+ return 0; /* restriction (3) */
114297116660
}
114298116661
while( pWhere->op==TK_AND ){
114299116662
nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
114300116663
pWhere = pWhere->pLeft;
114301116664
}
@@ -115593,10 +117956,17 @@
115593117956
pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
115594117957
/* Notice that even thought SF_Distinct has been cleared from p->selFlags,
115595117958
** the sDistinct.isTnct is still set. Hence, isTnct represents the
115596117959
** original setting of the SF_Distinct flag, not the current setting */
115597117960
assert( sDistinct.isTnct );
117961
+
117962
+#if SELECTTRACE_ENABLED
117963
+ if( sqlite3SelectTrace & 0x400 ){
117964
+ SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
117965
+ sqlite3TreeViewSelect(0, p, 0);
117966
+ }
117967
+#endif
115598117968
}
115599117969
115600117970
/* If there is an ORDER BY clause, then create an ephemeral index to
115601117971
** do the sorting. But this sorting ephemeral index might end up
115602117972
** being unused if the data can be extracted in pre-sorted order.
@@ -117831,11 +120201,12 @@
117831120201
/* Begin the database scan
117832120202
*/
117833120203
if( HasRowid(pTab) ){
117834120204
sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
117835120205
pWInfo = sqlite3WhereBegin(
117836
- pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
120206
+ pParse, pTabList, pWhere, 0, 0,
120207
+ WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
117837120208
);
117838120209
if( pWInfo==0 ) goto update_cleanup;
117839120210
okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
117840120211
117841120212
/* Remember the rowid of every item to be updated.
@@ -118069,15 +120440,34 @@
118069120440
addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
118070120441
}
118071120442
VdbeCoverageNeverTaken(v);
118072120443
}
118073120444
sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
118074
-
118075
- /* If changing the record number, delete the old record. */
120445
+
120446
+ /* If changing the rowid value, or if there are foreign key constraints
120447
+ ** to process, delete the old record. Otherwise, add a noop OP_Delete
120448
+ ** to invoke the pre-update hook.
120449
+ **
120450
+ ** That (regNew==regnewRowid+1) is true is also important for the
120451
+ ** pre-update hook. If the caller invokes preupdate_new(), the returned
120452
+ ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
120453
+ ** is the column index supplied by the user.
120454
+ */
120455
+ assert( regNew==regNewRowid+1 );
120456
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
120457
+ sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
120458
+ OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
120459
+ regNewRowid
120460
+ );
120461
+ if( !pParse->nested ){
120462
+ sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
120463
+ }
120464
+#else
118076120465
if( hasFK || chngKey || pPk!=0 ){
118077120466
sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
118078120467
}
120468
+#endif
118079120469
if( bReplace || chngKey ){
118080120470
sqlite3VdbeJumpHere(v, addr1);
118081120471
}
118082120472
118083120473
if( hasFK ){
@@ -119969,11 +122359,11 @@
119969122359
int addrSkip; /* Jump here for next iteration of skip-scan */
119970122360
int addrCont; /* Jump here to continue with the next loop cycle */
119971122361
int addrFirst; /* First instruction of interior of the loop */
119972122362
int addrBody; /* Beginning of the body of this loop */
119973122363
#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
119974
- int iLikeRepCntr; /* LIKE range processing counter register */
122364
+ u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
119975122365
int addrLikeRep; /* LIKE range processing address */
119976122366
#endif
119977122367
u8 iFrom; /* Which entry in the FROM clause */
119978122368
u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
119979122369
int p1, p2; /* Operands of the opcode used to ends the loop */
@@ -120307,11 +122697,11 @@
120307122697
*/
120308122698
struct WhereInfo {
120309122699
Parse *pParse; /* Parsing and code generating context */
120310122700
SrcList *pTabList; /* List of tables in the join */
120311122701
ExprList *pOrderBy; /* The ORDER BY clause or NULL */
120312
- ExprList *pResultSet; /* Result set. DISTINCT operates on these */
122702
+ ExprList *pDistinctSet; /* DISTINCT over all these values */
120313122703
WhereLoop *pLoops; /* List of all WhereLoop objects */
120314122704
Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
120315122705
LogEst nRowOut; /* Estimated number of output rows */
120316122706
LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
120317122707
u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
@@ -120391,10 +122781,18 @@
120391122781
/*
120392122782
** Bitmasks for the operators on WhereTerm objects. These are all
120393122783
** operators that are of interest to the query planner. An
120394122784
** OR-ed combination of these values can be used when searching for
120395122785
** particular WhereTerms within a WhereClause.
122786
+**
122787
+** Value constraints:
122788
+** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
122789
+** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
122790
+** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
122791
+** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
122792
+** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
122793
+** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
120396122794
*/
120397122795
#define WO_IN 0x0001
120398122796
#define WO_EQ 0x0002
120399122797
#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
120400122798
#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -120977,13 +123375,14 @@
120977123375
return regBase;
120978123376
}
120979123377
120980123378
#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
120981123379
/*
120982
-** If the most recently coded instruction is a constant range contraint
120983
-** that originated from the LIKE optimization, then change the P3 to be
120984
-** pLoop->iLikeRepCntr and set P5.
123380
+** If the most recently coded instruction is a constant range constraint
123381
+** (a string literal) that originated from the LIKE optimization, then
123382
+** set P3 and P5 on the OP_String opcode so that the string will be cast
123383
+** to a BLOB at appropriate times.
120985123384
**
120986123385
** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
120987123386
** expression: "x>='ABC' AND x<'abd'". But this requires that the range
120988123387
** scan loop run twice, once for strings and a second time for BLOBs.
120989123388
** The OP_String opcodes on the second pass convert the upper and lower
@@ -121004,12 +123403,12 @@
121004123403
assert( pLevel->iLikeRepCntr>0 );
121005123404
pOp = sqlite3VdbeGetOp(v, -1);
121006123405
assert( pOp!=0 );
121007123406
assert( pOp->opcode==OP_String8
121008123407
|| pTerm->pWC->pWInfo->pParse->db->mallocFailed );
121009
- pOp->p3 = pLevel->iLikeRepCntr;
121010
- pOp->p5 = 1;
123408
+ pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
123409
+ pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
121011123410
}
121012123411
}
121013123412
#else
121014123413
# define whereLikeOptimizationStringFixup(A,B,C)
121015123414
#endif
@@ -121358,11 +123757,17 @@
121358123757
pCompare->pLeft = 0;
121359123758
sqlite3ExprDelete(db, pCompare);
121360123759
}
121361123760
}
121362123761
}
121363
- sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
123762
+ /* These registers need to be preserved in case there is an IN operator
123763
+ ** loop. So we could deallocate the registers here (and potentially
123764
+ ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
123765
+ ** simpler and safer to simply not reuse the registers.
123766
+ **
123767
+ ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
123768
+ */
121364123769
sqlite3ExprCachePop(pParse);
121365123770
}else
121366123771
#endif /* SQLITE_OMIT_VIRTUALTABLE */
121367123772
121368123773
if( (pLoop->wsFlags & WHERE_IPK)!=0
@@ -121586,18 +123991,21 @@
121586123991
nExtraReg = 1;
121587123992
#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
121588123993
if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
121589123994
assert( pRangeStart!=0 ); /* LIKE opt constraints */
121590123995
assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
121591
- pLevel->iLikeRepCntr = ++pParse->nMem;
123996
+ pLevel->iLikeRepCntr = (u32)++pParse->nMem;
123997
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
123998
+ VdbeComment((v, "LIKE loop counter"));
123999
+ pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124000
+ /* iLikeRepCntr actually stores 2x the counter register number. The
124001
+ ** bottom bit indicates whether the search order is ASC or DESC. */
121592124002
testcase( bRev );
121593124003
testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
121594
- sqlite3VdbeAddOp2(v, OP_Integer,
121595
- bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
121596
- pLevel->iLikeRepCntr);
121597
- VdbeComment((v, "LIKE loop counter"));
121598
- pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124004
+ assert( (bRev & ~1)==0 );
124005
+ pLevel->iLikeRepCntr <<=1;
124006
+ pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
121599124007
}
121600124008
#endif
121601124009
if( pRangeStart==0
121602124010
&& (j = pIdx->aiColumn[nEq])>=0
121603124011
&& pIdx->pTable->aCol[j].notNull==0
@@ -121731,11 +124139,11 @@
121731124139
disableTerm(pLevel, pRangeStart);
121732124140
disableTerm(pLevel, pRangeEnd);
121733124141
if( omitTable ){
121734124142
/* pIdx is a covering index. No need to access the main table. */
121735124143
}else if( HasRowid(pIdx->pTable) ){
121736
- if( pWInfo->eOnePass!=ONEPASS_OFF ){
124144
+ if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
121737124145
iRowidReg = ++pParse->nMem;
121738124146
sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
121739124147
sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
121740124148
sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
121741124149
VdbeCoverage(v);
@@ -121927,11 +124335,12 @@
121927124335
** sub-WHERE clause is to to invoke the main loop body as a subroutine.
121928124336
*/
121929124337
wctrlFlags = WHERE_OMIT_OPEN_CLOSE
121930124338
| WHERE_FORCE_TABLE
121931124339
| WHERE_ONETABLE_ONLY
121932
- | WHERE_NO_AUTOINDEX;
124340
+ | WHERE_NO_AUTOINDEX
124341
+ | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
121933124342
for(ii=0; ii<pOrWc->nTerm; ii++){
121934124343
WhereTerm *pOrTerm = &pOrWc->a[ii];
121935124344
if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
121936124345
WhereInfo *pSubWInfo; /* Info for single OR-term scan */
121937124346
Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
@@ -122107,15 +124516,21 @@
122107124516
assert( pE!=0 );
122108124517
if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
122109124518
continue;
122110124519
}
122111124520
if( pTerm->wtFlags & TERM_LIKECOND ){
124521
+ /* If the TERM_LIKECOND flag is set, that means that the range search
124522
+ ** is sufficient to guarantee that the LIKE operator is true, so we
124523
+ ** can skip the call to the like(A,B) function. But this only works
124524
+ ** for strings. So do not skip the call to the function on the pass
124525
+ ** that compares BLOBs. */
122112124526
#ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
122113124527
continue;
122114124528
#else
122115
- assert( pLevel->iLikeRepCntr>0 );
122116
- skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
124529
+ u32 x = pLevel->iLikeRepCntr;
124530
+ assert( x>0 );
124531
+ skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
122117124532
VdbeCoverage(v);
122118124533
#endif
122119124534
}
122120124535
sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
122121124536
if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
@@ -123467,14 +125882,14 @@
123467125882
if( p->op==TK_COLUMN ){
123468125883
mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
123469125884
return mask;
123470125885
}
123471125886
mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
123472
- mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
125887
+ if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
123473125888
if( ExprHasProperty(p, EP_xIsSelect) ){
123474125889
mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
123475
- }else{
125890
+ }else if( p->x.pList ){
123476125891
mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
123477125892
}
123478125893
return mask;
123479125894
}
123480125895
SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
@@ -123810,11 +126225,14 @@
123810126225
** Initialize a WHERE clause scanner object. Return a pointer to the
123811126226
** first match. Return NULL if there are no matches.
123812126227
**
123813126228
** The scanner will be searching the WHERE clause pWC. It will look
123814126229
** for terms of the form "X <op> <expr>" where X is column iColumn of table
123815
-** iCur. The <op> must be one of the operators described by opMask.
126230
+** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
126231
+** must be one of the indexes of table iCur.
126232
+**
126233
+** The <op> must be one of the operators described by opMask.
123816126234
**
123817126235
** If the search is for X and the WHERE clause contains terms of the
123818126236
** form X=Y then this routine might also return terms of the form
123819126237
** "Y <op> <expr>". The number of levels of transitivity is limited,
123820126238
** but is enough to handle most commonly occurring SQL statements.
@@ -123858,15 +126276,16 @@
123858126276
return whereScanNext(pScan);
123859126277
}
123860126278
123861126279
/*
123862126280
** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
123863
-** where X is a reference to the iColumn of table iCur and <op> is one of
123864
-** the WO_xx operator codes specified by the op parameter.
123865
-** Return a pointer to the term. Return 0 if not found.
126281
+** where X is a reference to the iColumn of table iCur or of index pIdx
126282
+** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
126283
+** the op parameter. Return a pointer to the term. Return 0 if not found.
123866126284
**
123867
-** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
126285
+** If pIdx!=0 then it must be one of the indexes of table iCur.
126286
+** Search for terms matching the iColumn-th column of pIdx
123868126287
** rather than the iColumn-th column of table iCur.
123869126288
**
123870126289
** The term returned might by Y=<expr> if there is another constraint in
123871126290
** the WHERE clause that specifies that X=Y. Any such constraints will be
123872126291
** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
@@ -125200,15 +127619,16 @@
125200127619
/*
125201127620
** Print a WhereLoop object for debugging purposes
125202127621
*/
125203127622
static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
125204127623
WhereInfo *pWInfo = pWC->pWInfo;
125205
- int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
127624
+ int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
125206127625
struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
125207127626
Table *pTab = pItem->pTab;
127627
+ Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
125208127628
sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
125209
- p->iTab, nb, p->maskSelf, nb, p->prereq);
127629
+ p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
125210127630
sqlite3DebugPrintf(" %12s",
125211127631
pItem->zAlias ? pItem->zAlias : pTab->zName);
125212127632
if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
125213127633
const char *zName;
125214127634
if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
@@ -127429,13 +129849,13 @@
127429129849
&& (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
127430129850
&& pWInfo->eDistinct==WHERE_DISTINCT_NOOP
127431129851
&& nRowEst
127432129852
){
127433129853
Bitmask notUsed;
127434
- int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
129854
+ int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
127435129855
WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
127436
- if( rc==pWInfo->pResultSet->nExpr ){
129856
+ if( rc==pWInfo->pDistinctSet->nExpr ){
127437129857
pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
127438129858
}
127439129859
}
127440129860
if( pWInfo->pOrderBy ){
127441129861
if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
@@ -127646,18 +130066,18 @@
127646130066
** the first cursor in an array of cursors for all indices. iIdxCur should
127647130067
** be used to compute the appropriate cursor depending on which index is
127648130068
** used.
127649130069
*/
127650130070
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
127651
- Parse *pParse, /* The parser context */
127652
- SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
127653
- Expr *pWhere, /* The WHERE clause */
127654
- ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
127655
- ExprList *pResultSet, /* Result set of the query */
127656
- u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
127657
- int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number,
127658
- ** If WHERE_USE_LIMIT, then the limit amount */
130071
+ Parse *pParse, /* The parser context */
130072
+ SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
130073
+ Expr *pWhere, /* The WHERE clause */
130074
+ ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
130075
+ ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130076
+ u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
130077
+ int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number
130078
+ ** If WHERE_USE_LIMIT, then the limit amount */
127659130079
){
127660130080
int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
127661130081
int nTabList; /* Number of elements in pTabList */
127662130082
WhereInfo *pWInfo; /* Will become the return value of this function */
127663130083
Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -127728,11 +130148,11 @@
127728130148
pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
127729130149
pWInfo->nLevel = nTabList;
127730130150
pWInfo->pParse = pParse;
127731130151
pWInfo->pTabList = pTabList;
127732130152
pWInfo->pOrderBy = pOrderBy;
127733
- pWInfo->pResultSet = pResultSet;
130153
+ pWInfo->pDistinctSet = pDistinctSet;
127734130154
pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
127735130155
pWInfo->wctrlFlags = wctrlFlags;
127736130156
pWInfo->iLimit = iAuxArg;
127737130157
pWInfo->savedNQueryLoop = pParse->nQueryLoop;
127738130158
assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
@@ -127801,17 +130221,17 @@
127801130221
/* Analyze all of the subexpressions. */
127802130222
sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
127803130223
if( db->mallocFailed ) goto whereBeginError;
127804130224
127805130225
if( wctrlFlags & WHERE_WANT_DISTINCT ){
127806
- if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
130226
+ if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
127807130227
/* The DISTINCT marking is pointless. Ignore it. */
127808130228
pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
127809130229
}else if( pOrderBy==0 ){
127810130230
/* Try to ORDER BY the result set to make distinct processing easier */
127811130231
pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
127812
- pWInfo->pOrderBy = pResultSet;
130232
+ pWInfo->pOrderBy = pDistinctSet;
127813130233
}
127814130234
}
127815130235
127816130236
/* Construct the WhereLoop objects */
127817130237
#if defined(WHERETRACE_ENABLED)
@@ -127886,14 +130306,14 @@
127886130306
}
127887130307
}
127888130308
#endif
127889130309
/* Attempt to omit tables from the join that do not effect the result */
127890130310
if( pWInfo->nLevel>=2
127891
- && pResultSet!=0
130311
+ && pDistinctSet!=0
127892130312
&& OptimizationEnabled(db, SQLITE_OmitNoopJoin)
127893130313
){
127894
- Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
130314
+ Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
127895130315
if( sWLB.pOrderBy ){
127896130316
tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
127897130317
}
127898130318
while( pWInfo->nLevel>=2 ){
127899130319
WhereTerm *pTerm, *pEnd;
@@ -128155,17 +130575,12 @@
128155130575
sqlite3VdbeJumpHere(v, pLevel->addrSkip);
128156130576
sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
128157130577
}
128158130578
#ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128159130579
if( pLevel->addrLikeRep ){
128160
- int op;
128161
- if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
128162
- op = OP_DecrJumpZero;
128163
- }else{
128164
- op = OP_JumpZeroIncr;
128165
- }
128166
- sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
130580
+ sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
130581
+ pLevel->addrLikeRep);
128167130582
VdbeCoverage(v);
128168130583
}
128169130584
#endif
128170130585
if( pLevel->iLeftJoin ){
128171130586
addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
@@ -128567,11 +130982,11 @@
128567130982
#endif
128568130983
/************* Begin control #defines *****************************************/
128569130984
#define YYCODETYPE unsigned char
128570130985
#define YYNOCODE 251
128571130986
#define YYACTIONTYPE unsigned short int
128572
-#define YYWILDCARD 70
130987
+#define YYWILDCARD 96
128573130988
#define sqlite3ParserTOKENTYPE Token
128574130989
typedef union {
128575130990
int yyinit;
128576130991
sqlite3ParserTOKENTYPE yy0;
128577130992
struct LimitVal yy64;
@@ -128671,402 +131086,404 @@
128671131086
** yy_reduce_ofst[] For each state, the offset into yy_action for
128672131087
** shifting non-terminals after a reduce.
128673131088
** yy_default[] Default action for each state.
128674131089
**
128675131090
*********** Begin parsing tables **********************************************/
128676
-#define YY_ACTTAB_COUNT (1499)
131091
+#define YY_ACTTAB_COUNT (1501)
128677131092
static const YYACTIONTYPE yy_action[] = {
128678
- /* 0 */ 315, 1302, 146, 921, 2, 194, 922, 342, 952, 91,
128679
- /* 10 */ 91, 91, 91, 84, 89, 89, 89, 89, 88, 88,
128680
- /* 20 */ 87, 87, 87, 86, 339, 87, 87, 87, 86, 339,
128681
- /* 30 */ 331, 819, 819, 91, 91, 91, 91, 339, 89, 89,
128682
- /* 40 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 319,
128683
- /* 50 */ 933, 933, 92, 93, 83, 831, 834, 823, 823, 90,
128684
- /* 60 */ 90, 91, 91, 91, 91, 123, 89, 89, 89, 89,
128685
- /* 70 */ 88, 88, 87, 87, 87, 86, 339, 315, 952, 89,
128686
- /* 80 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
128687
- /* 90 */ 365, 772, 360, 24, 933, 933, 947, 694, 933, 933,
128688
- /* 100 */ 773, 937, 933, 933, 434, 715, 328, 434, 819, 819,
128689
- /* 110 */ 203, 160, 278, 391, 273, 390, 190, 933, 933, 370,
128690
- /* 120 */ 934, 935, 367, 271, 953, 48, 679, 953, 48, 92,
128691
- /* 130 */ 93, 83, 831, 834, 823, 823, 90, 90, 91, 91,
128692
- /* 140 */ 91, 91, 123, 89, 89, 89, 89, 88, 88, 87,
128693
- /* 150 */ 87, 87, 86, 339, 315, 682, 337, 336, 218, 412,
128694
- /* 160 */ 398, 68, 412, 403, 934, 935, 743, 959, 934, 935,
128695
- /* 170 */ 810, 937, 934, 935, 957, 221, 958, 88, 88, 87,
128696
- /* 180 */ 87, 87, 86, 339, 291, 819, 819, 934, 935, 185,
128697
- /* 190 */ 94, 792, 388, 385, 384, 1240, 1240, 792, 804, 960,
128698
- /* 200 */ 960, 290, 798, 383, 123, 315, 92, 93, 83, 831,
128699
- /* 210 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
128700
- /* 220 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
128701
- /* 230 */ 339, 681, 741, 803, 803, 803, 819, 819, 944, 56,
128702
- /* 240 */ 253, 353, 242, 85, 82, 168, 253, 358, 252, 110,
128703
- /* 250 */ 96, 233, 397, 698, 677, 683, 683, 92, 93, 83,
128704
- /* 260 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
128705
- /* 270 */ 433, 89, 89, 89, 89, 88, 88, 87, 87, 87,
128706
- /* 280 */ 86, 339, 315, 434, 439, 651, 396, 57, 733, 733,
128707
- /* 290 */ 234, 291, 107, 287, 395, 86, 339, 810, 427, 728,
128708
- /* 300 */ 933, 933, 185, 953, 30, 388, 385, 384, 215, 949,
128709
- /* 310 */ 434, 933, 933, 819, 819, 697, 383, 162, 161, 407,
128710
- /* 320 */ 400, 85, 82, 168, 677, 804, 335, 113, 771, 798,
128711
- /* 330 */ 953, 48, 22, 351, 92, 93, 83, 831, 834, 823,
128712
- /* 340 */ 823, 90, 90, 91, 91, 91, 91, 870, 89, 89,
128713
- /* 350 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 315,
128714
- /* 360 */ 803, 803, 803, 268, 123, 412, 394, 1, 933, 933,
128715
- /* 370 */ 934, 935, 933, 933, 85, 82, 168, 232, 5, 343,
128716
- /* 380 */ 194, 934, 935, 952, 85, 82, 168, 54, 956, 434,
128717
- /* 390 */ 819, 819, 431, 938, 939, 792, 67, 759, 350, 144,
128718
- /* 400 */ 166, 770, 123, 896, 889, 955, 348, 288, 758, 953,
128719
- /* 410 */ 47, 92, 93, 83, 831, 834, 823, 823, 90, 90,
128720
- /* 420 */ 91, 91, 91, 91, 892, 89, 89, 89, 89, 88,
128721
- /* 430 */ 88, 87, 87, 87, 86, 339, 315, 113, 934, 935,
128722
- /* 440 */ 687, 893, 934, 935, 253, 358, 252, 85, 82, 168,
128723
- /* 450 */ 820, 820, 956, 952, 338, 938, 939, 894, 701, 721,
128724
- /* 460 */ 359, 289, 233, 397, 434, 349, 434, 819, 819, 955,
128725
- /* 470 */ 866, 722, 23, 389, 832, 835, 692, 357, 904, 667,
128726
- /* 480 */ 194, 702, 402, 952, 953, 48, 953, 48, 92, 93,
128727
- /* 490 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
128728
- /* 500 */ 91, 824, 89, 89, 89, 89, 88, 88, 87, 87,
128729
- /* 510 */ 87, 86, 339, 315, 434, 113, 434, 680, 434, 332,
128730
- /* 520 */ 434, 408, 889, 356, 380, 940, 401, 720, 948, 864,
128731
- /* 530 */ 191, 165, 329, 689, 953, 9, 953, 9, 953, 9,
128732
- /* 540 */ 953, 9, 718, 948, 819, 819, 953, 8, 325, 111,
128733
- /* 550 */ 327, 153, 224, 952, 410, 113, 189, 337, 336, 913,
128734
- /* 560 */ 1295, 852, 75, 1295, 73, 92, 93, 83, 831, 834,
128735
- /* 570 */ 823, 823, 90, 90, 91, 91, 91, 91, 359, 89,
128736
- /* 580 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
128737
- /* 590 */ 315, 730, 148, 236, 797, 366, 789, 892, 1179, 434,
128738
- /* 600 */ 960, 960, 400, 148, 314, 212, 873, 911, 757, 404,
128739
- /* 610 */ 872, 300, 320, 434, 893, 311, 237, 271, 405, 953,
128740
- /* 620 */ 34, 819, 819, 225, 371, 945, 360, 913, 1296, 113,
128741
- /* 630 */ 894, 1296, 417, 953, 35, 1245, 922, 342, 259, 247,
128742
- /* 640 */ 290, 315, 92, 93, 83, 831, 834, 823, 823, 90,
128743
- /* 650 */ 90, 91, 91, 91, 91, 148, 89, 89, 89, 89,
128744
- /* 660 */ 88, 88, 87, 87, 87, 86, 339, 310, 434, 796,
128745
- /* 670 */ 434, 240, 819, 819, 266, 911, 876, 876, 373, 346,
128746
- /* 680 */ 167, 654, 655, 656, 259, 244, 19, 246, 953, 11,
128747
- /* 690 */ 953, 26, 222, 92, 93, 83, 831, 834, 823, 823,
128748
- /* 700 */ 90, 90, 91, 91, 91, 91, 757, 89, 89, 89,
128749
- /* 710 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 434,
128750
- /* 720 */ 261, 434, 264, 696, 434, 241, 434, 344, 971, 308,
128751
- /* 730 */ 757, 434, 796, 434, 324, 434, 393, 423, 434, 953,
128752
- /* 740 */ 36, 953, 37, 20, 953, 38, 953, 27, 434, 819,
128753
- /* 750 */ 819, 953, 28, 953, 39, 953, 40, 738, 953, 41,
128754
- /* 760 */ 71, 738, 737, 245, 307, 973, 737, 259, 953, 10,
128755
- /* 770 */ 92, 93, 83, 831, 834, 823, 823, 90, 90, 91,
128756
- /* 780 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
128757
- /* 790 */ 87, 87, 87, 86, 339, 315, 434, 372, 434, 259,
128758
- /* 800 */ 149, 434, 167, 953, 42, 188, 187, 186, 219, 434,
128759
- /* 810 */ 748, 434, 974, 434, 796, 434, 953, 98, 953, 43,
128760
- /* 820 */ 862, 953, 44, 434, 920, 2, 819, 819, 757, 953,
128761
- /* 830 */ 31, 953, 45, 953, 46, 953, 32, 74, 307, 912,
128762
- /* 840 */ 220, 259, 259, 953, 115, 909, 315, 92, 93, 83,
128763
- /* 850 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
128764
- /* 860 */ 434, 89, 89, 89, 89, 88, 88, 87, 87, 87,
128765
- /* 870 */ 86, 339, 434, 248, 434, 215, 949, 819, 819, 333,
128766
- /* 880 */ 953, 116, 895, 860, 176, 259, 974, 400, 361, 259,
128767
- /* 890 */ 951, 887, 953, 117, 953, 52, 884, 315, 92, 93,
128768
- /* 900 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
128769
- /* 910 */ 91, 434, 89, 89, 89, 89, 88, 88, 87, 87,
128770
- /* 920 */ 87, 86, 339, 434, 113, 434, 258, 883, 819, 819,
128771
- /* 930 */ 727, 953, 33, 363, 259, 673, 321, 189, 430, 321,
128772
- /* 940 */ 368, 365, 364, 953, 99, 953, 49, 365, 315, 92,
128773
- /* 950 */ 81, 83, 831, 834, 823, 823, 90, 90, 91, 91,
128774
- /* 960 */ 91, 91, 434, 89, 89, 89, 89, 88, 88, 87,
128775
- /* 970 */ 87, 87, 86, 339, 434, 723, 434, 214, 165, 819,
128776
- /* 980 */ 819, 772, 953, 100, 322, 124, 1269, 158, 65, 710,
128777
- /* 990 */ 773, 700, 699, 320, 953, 101, 953, 97, 255, 315,
128778
- /* 1000 */ 216, 93, 83, 831, 834, 823, 823, 90, 90, 91,
128779
- /* 1010 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
128780
- /* 1020 */ 87, 87, 87, 86, 339, 434, 251, 434, 707, 708,
128781
- /* 1030 */ 819, 819, 223, 953, 114, 908, 794, 254, 309, 193,
128782
- /* 1040 */ 67, 381, 869, 869, 199, 953, 112, 953, 105, 269,
128783
- /* 1050 */ 726, 260, 67, 83, 831, 834, 823, 823, 90, 90,
128784
- /* 1060 */ 91, 91, 91, 91, 263, 89, 89, 89, 89, 88,
128785
- /* 1070 */ 88, 87, 87, 87, 86, 339, 79, 429, 690, 3,
128786
- /* 1080 */ 1174, 228, 434, 113, 340, 340, 868, 868, 265, 79,
128787
- /* 1090 */ 429, 735, 3, 859, 70, 432, 434, 340, 340, 434,
128788
- /* 1100 */ 1259, 434, 953, 104, 434, 670, 416, 766, 432, 434,
128789
- /* 1110 */ 193, 434, 413, 434, 418, 806, 953, 102, 420, 953,
128790
- /* 1120 */ 103, 953, 48, 123, 953, 51, 810, 418, 424, 953,
128791
- /* 1130 */ 53, 953, 50, 953, 25, 267, 123, 711, 113, 810,
128792
- /* 1140 */ 428, 277, 695, 272, 764, 113, 76, 77, 690, 434,
128793
- /* 1150 */ 795, 113, 276, 78, 436, 435, 412, 414, 798, 76,
128794
- /* 1160 */ 77, 113, 855, 859, 376, 199, 78, 436, 435, 953,
128795
- /* 1170 */ 29, 798, 744, 113, 755, 79, 429, 675, 3, 415,
128796
- /* 1180 */ 109, 292, 293, 340, 340, 806, 802, 678, 672, 803,
128797
- /* 1190 */ 803, 803, 805, 18, 432, 661, 660, 662, 927, 209,
128798
- /* 1200 */ 150, 352, 803, 803, 803, 805, 18, 6, 306, 280,
128799
- /* 1210 */ 282, 284, 786, 418, 250, 386, 243, 886, 694, 362,
128800
- /* 1220 */ 286, 163, 275, 79, 429, 810, 3, 857, 856, 159,
128801
- /* 1230 */ 419, 340, 340, 298, 930, 968, 126, 196, 965, 903,
128802
- /* 1240 */ 901, 323, 432, 136, 55, 76, 77, 742, 147, 58,
128803
- /* 1250 */ 121, 129, 78, 436, 435, 65, 783, 798, 354, 131,
128804
- /* 1260 */ 355, 418, 379, 132, 133, 134, 175, 139, 151, 369,
128805
- /* 1270 */ 888, 180, 791, 810, 61, 851, 871, 69, 429, 375,
128806
- /* 1280 */ 3, 756, 210, 257, 181, 340, 340, 145, 803, 803,
128807
- /* 1290 */ 803, 805, 18, 76, 77, 377, 432, 262, 182, 183,
128808
- /* 1300 */ 78, 436, 435, 663, 312, 798, 392, 714, 713, 712,
128809
- /* 1310 */ 330, 705, 692, 313, 704, 418, 686, 406, 752, 685,
128810
- /* 1320 */ 274, 684, 942, 64, 279, 195, 281, 810, 753, 839,
128811
- /* 1330 */ 751, 283, 72, 750, 285, 422, 803, 803, 803, 805,
128812
- /* 1340 */ 18, 334, 426, 95, 411, 229, 409, 76, 77, 230,
128813
- /* 1350 */ 734, 66, 231, 294, 78, 436, 435, 204, 295, 798,
128814
- /* 1360 */ 217, 296, 297, 669, 21, 305, 304, 303, 206, 301,
128815
- /* 1370 */ 437, 928, 664, 205, 208, 207, 438, 658, 657, 652,
128816
- /* 1380 */ 118, 108, 119, 226, 650, 341, 157, 170, 169, 239,
128817
- /* 1390 */ 803, 803, 803, 805, 18, 125, 120, 235, 238, 317,
128818
- /* 1400 */ 318, 345, 106, 790, 867, 127, 865, 128, 130, 724,
128819
- /* 1410 */ 249, 172, 174, 882, 135, 137, 59, 138, 173, 60,
128820
- /* 1420 */ 885, 123, 171, 177, 178, 881, 7, 12, 179, 256,
128821
- /* 1430 */ 874, 140, 193, 962, 374, 141, 666, 152, 378, 276,
128822
- /* 1440 */ 184, 382, 142, 122, 62, 13, 387, 703, 270, 14,
128823
- /* 1450 */ 63, 227, 809, 808, 837, 732, 15, 841, 736, 4,
128824
- /* 1460 */ 765, 211, 399, 164, 213, 143, 760, 201, 70, 316,
128825
- /* 1470 */ 67, 838, 836, 891, 198, 192, 16, 197, 890, 917,
128826
- /* 1480 */ 154, 17, 202, 421, 918, 155, 200, 156, 425, 840,
128827
- /* 1490 */ 807, 1261, 676, 80, 302, 299, 347, 1260, 923,
131093
+ /* 0 */ 315, 810, 339, 804, 5, 194, 194, 798, 92, 93,
131094
+ /* 10 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131095
+ /* 20 */ 91, 91, 91, 290, 89, 89, 89, 89, 88, 88,
131096
+ /* 30 */ 87, 87, 87, 86, 339, 315, 952, 952, 803, 803,
131097
+ /* 40 */ 803, 922, 342, 92, 93, 83, 819, 819, 831, 834,
131098
+ /* 50 */ 823, 823, 90, 90, 91, 91, 91, 91, 123, 89,
131099
+ /* 60 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131100
+ /* 70 */ 88, 88, 87, 87, 87, 86, 339, 772, 952, 952,
131101
+ /* 80 */ 315, 87, 87, 87, 86, 339, 773, 68, 92, 93,
131102
+ /* 90 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131103
+ /* 100 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
131104
+ /* 110 */ 87, 87, 87, 86, 339, 1302, 146, 921, 2, 315,
131105
+ /* 120 */ 427, 24, 679, 953, 48, 86, 339, 92, 93, 83,
131106
+ /* 130 */ 819, 819, 831, 834, 823, 823, 90, 90, 91, 91,
131107
+ /* 140 */ 91, 91, 94, 89, 89, 89, 89, 88, 88, 87,
131108
+ /* 150 */ 87, 87, 86, 339, 933, 933, 315, 259, 412, 398,
131109
+ /* 160 */ 396, 57, 733, 733, 92, 93, 83, 819, 819, 831,
131110
+ /* 170 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 56,
131111
+ /* 180 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131112
+ /* 190 */ 339, 315, 1245, 922, 342, 268, 934, 935, 241, 92,
131113
+ /* 200 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131114
+ /* 210 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131115
+ /* 220 */ 88, 87, 87, 87, 86, 339, 315, 913, 1295, 682,
131116
+ /* 230 */ 687, 1295, 233, 397, 92, 93, 83, 819, 819, 831,
131117
+ /* 240 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
131118
+ /* 250 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131119
+ /* 260 */ 339, 315, 85, 82, 168, 680, 431, 938, 939, 92,
131120
+ /* 270 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131121
+ /* 280 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131122
+ /* 290 */ 88, 87, 87, 87, 86, 339, 315, 319, 913, 1296,
131123
+ /* 300 */ 797, 911, 1296, 681, 92, 93, 83, 819, 819, 831,
131124
+ /* 310 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 335,
131125
+ /* 320 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131126
+ /* 330 */ 339, 315, 876, 876, 373, 85, 82, 168, 944, 92,
131127
+ /* 340 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131128
+ /* 350 */ 91, 91, 91, 91, 896, 89, 89, 89, 89, 88,
131129
+ /* 360 */ 88, 87, 87, 87, 86, 339, 315, 370, 307, 973,
131130
+ /* 370 */ 367, 1, 911, 433, 92, 93, 83, 819, 819, 831,
131131
+ /* 380 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 189,
131132
+ /* 390 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131133
+ /* 400 */ 339, 315, 720, 948, 933, 933, 149, 718, 948, 92,
131134
+ /* 410 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131135
+ /* 420 */ 91, 91, 91, 91, 434, 89, 89, 89, 89, 88,
131136
+ /* 430 */ 88, 87, 87, 87, 86, 339, 338, 938, 939, 947,
131137
+ /* 440 */ 694, 940, 974, 315, 953, 48, 934, 935, 715, 689,
131138
+ /* 450 */ 71, 92, 93, 83, 819, 819, 831, 834, 823, 823,
131139
+ /* 460 */ 90, 90, 91, 91, 91, 91, 320, 89, 89, 89,
131140
+ /* 470 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 412,
131141
+ /* 480 */ 403, 820, 820, 832, 835, 74, 92, 81, 83, 819,
131142
+ /* 490 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131143
+ /* 500 */ 91, 698, 89, 89, 89, 89, 88, 88, 87, 87,
131144
+ /* 510 */ 87, 86, 339, 315, 259, 654, 655, 656, 393, 111,
131145
+ /* 520 */ 331, 153, 93, 83, 819, 819, 831, 834, 823, 823,
131146
+ /* 530 */ 90, 90, 91, 91, 91, 91, 434, 89, 89, 89,
131147
+ /* 540 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 188,
131148
+ /* 550 */ 187, 186, 824, 937, 328, 219, 953, 48, 83, 819,
131149
+ /* 560 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131150
+ /* 570 */ 91, 956, 89, 89, 89, 89, 88, 88, 87, 87,
131151
+ /* 580 */ 87, 86, 339, 79, 429, 738, 3, 1174, 955, 348,
131152
+ /* 590 */ 737, 332, 792, 933, 933, 937, 79, 429, 730, 3,
131153
+ /* 600 */ 203, 160, 278, 391, 273, 390, 190, 892, 434, 400,
131154
+ /* 610 */ 741, 76, 77, 271, 287, 253, 353, 242, 78, 340,
131155
+ /* 620 */ 340, 85, 82, 168, 76, 77, 233, 397, 953, 48,
131156
+ /* 630 */ 432, 78, 340, 340, 277, 934, 935, 185, 439, 651,
131157
+ /* 640 */ 388, 385, 384, 432, 234, 276, 107, 418, 349, 337,
131158
+ /* 650 */ 336, 383, 893, 728, 215, 949, 123, 971, 308, 810,
131159
+ /* 660 */ 418, 436, 435, 412, 394, 798, 400, 873, 894, 123,
131160
+ /* 670 */ 721, 872, 810, 889, 436, 435, 215, 949, 798, 351,
131161
+ /* 680 */ 722, 697, 380, 434, 771, 371, 22, 434, 400, 79,
131162
+ /* 690 */ 429, 232, 3, 189, 413, 870, 803, 803, 803, 805,
131163
+ /* 700 */ 18, 54, 148, 953, 48, 956, 113, 953, 9, 803,
131164
+ /* 710 */ 803, 803, 805, 18, 310, 123, 748, 76, 77, 742,
131165
+ /* 720 */ 123, 325, 955, 866, 78, 340, 340, 113, 350, 359,
131166
+ /* 730 */ 85, 82, 168, 343, 960, 960, 432, 770, 412, 414,
131167
+ /* 740 */ 407, 23, 1240, 1240, 79, 429, 357, 3, 166, 91,
131168
+ /* 750 */ 91, 91, 91, 418, 89, 89, 89, 89, 88, 88,
131169
+ /* 760 */ 87, 87, 87, 86, 339, 810, 434, 436, 435, 792,
131170
+ /* 770 */ 320, 798, 76, 77, 789, 271, 123, 434, 360, 78,
131171
+ /* 780 */ 340, 340, 864, 85, 82, 168, 953, 9, 395, 743,
131172
+ /* 790 */ 360, 432, 253, 358, 252, 933, 933, 953, 30, 889,
131173
+ /* 800 */ 327, 216, 803, 803, 803, 805, 18, 113, 418, 89,
131174
+ /* 810 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131175
+ /* 820 */ 810, 113, 436, 435, 792, 185, 798, 288, 388, 385,
131176
+ /* 830 */ 384, 123, 113, 920, 2, 796, 696, 934, 935, 383,
131177
+ /* 840 */ 69, 429, 434, 3, 218, 110, 738, 253, 358, 252,
131178
+ /* 850 */ 434, 737, 933, 933, 892, 359, 222, 803, 803, 803,
131179
+ /* 860 */ 805, 18, 953, 47, 933, 933, 933, 933, 76, 77,
131180
+ /* 870 */ 953, 9, 366, 904, 217, 78, 340, 340, 677, 305,
131181
+ /* 880 */ 304, 303, 206, 301, 224, 259, 664, 432, 337, 336,
131182
+ /* 890 */ 434, 228, 247, 144, 934, 935, 933, 933, 667, 893,
131183
+ /* 900 */ 324, 1259, 96, 434, 418, 796, 934, 935, 934, 935,
131184
+ /* 910 */ 953, 48, 401, 148, 289, 894, 810, 417, 436, 435,
131185
+ /* 920 */ 677, 759, 798, 953, 9, 314, 220, 162, 161, 170,
131186
+ /* 930 */ 402, 239, 953, 8, 194, 683, 683, 410, 934, 935,
131187
+ /* 940 */ 238, 959, 933, 933, 225, 408, 945, 365, 957, 212,
131188
+ /* 950 */ 958, 172, 757, 803, 803, 803, 805, 18, 173, 365,
131189
+ /* 960 */ 176, 123, 171, 113, 244, 952, 246, 434, 356, 796,
131190
+ /* 970 */ 372, 365, 236, 960, 960, 810, 290, 804, 191, 165,
131191
+ /* 980 */ 852, 798, 259, 316, 934, 935, 237, 953, 34, 404,
131192
+ /* 990 */ 91, 91, 91, 91, 84, 89, 89, 89, 89, 88,
131193
+ /* 1000 */ 88, 87, 87, 87, 86, 339, 701, 952, 434, 240,
131194
+ /* 1010 */ 347, 758, 803, 803, 803, 434, 245, 1179, 434, 389,
131195
+ /* 1020 */ 434, 376, 434, 895, 167, 434, 405, 702, 953, 35,
131196
+ /* 1030 */ 673, 321, 221, 434, 333, 953, 11, 434, 953, 26,
131197
+ /* 1040 */ 953, 36, 953, 37, 251, 953, 38, 434, 259, 434,
131198
+ /* 1050 */ 757, 434, 329, 953, 27, 434, 223, 953, 28, 434,
131199
+ /* 1060 */ 690, 434, 67, 434, 65, 434, 862, 953, 39, 953,
131200
+ /* 1070 */ 40, 953, 41, 423, 434, 953, 10, 434, 772, 953,
131201
+ /* 1080 */ 42, 953, 98, 953, 43, 953, 44, 773, 434, 346,
131202
+ /* 1090 */ 434, 75, 434, 73, 953, 31, 434, 953, 45, 434,
131203
+ /* 1100 */ 259, 434, 690, 434, 757, 434, 887, 434, 953, 46,
131204
+ /* 1110 */ 953, 32, 953, 115, 434, 266, 953, 116, 951, 953,
131205
+ /* 1120 */ 117, 953, 52, 953, 33, 953, 99, 953, 49, 726,
131206
+ /* 1130 */ 434, 909, 434, 19, 953, 100, 434, 344, 434, 113,
131207
+ /* 1140 */ 434, 258, 692, 434, 259, 434, 670, 434, 20, 434,
131208
+ /* 1150 */ 953, 101, 953, 97, 434, 259, 953, 114, 953, 112,
131209
+ /* 1160 */ 953, 105, 113, 953, 104, 953, 102, 953, 103, 953,
131210
+ /* 1170 */ 51, 434, 148, 434, 953, 53, 167, 434, 259, 113,
131211
+ /* 1180 */ 300, 307, 912, 363, 311, 860, 248, 261, 209, 264,
131212
+ /* 1190 */ 416, 953, 50, 953, 25, 420, 727, 953, 29, 430,
131213
+ /* 1200 */ 321, 424, 757, 428, 322, 124, 1269, 214, 165, 710,
131214
+ /* 1210 */ 859, 908, 806, 794, 309, 158, 193, 361, 254, 723,
131215
+ /* 1220 */ 364, 67, 381, 269, 735, 199, 67, 70, 113, 700,
131216
+ /* 1230 */ 699, 707, 708, 884, 113, 766, 113, 855, 193, 883,
131217
+ /* 1240 */ 199, 869, 869, 675, 868, 868, 109, 368, 255, 260,
131218
+ /* 1250 */ 263, 280, 859, 265, 806, 974, 267, 711, 695, 272,
131219
+ /* 1260 */ 764, 282, 795, 284, 150, 744, 755, 415, 292, 293,
131220
+ /* 1270 */ 802, 678, 672, 661, 660, 662, 927, 6, 306, 386,
131221
+ /* 1280 */ 352, 786, 243, 250, 886, 362, 163, 286, 419, 298,
131222
+ /* 1290 */ 930, 159, 968, 196, 126, 903, 901, 965, 55, 58,
131223
+ /* 1300 */ 323, 275, 857, 136, 147, 694, 856, 121, 65, 354,
131224
+ /* 1310 */ 355, 379, 175, 61, 151, 369, 180, 871, 375, 129,
131225
+ /* 1320 */ 257, 756, 210, 181, 145, 131, 132, 377, 262, 663,
131226
+ /* 1330 */ 133, 134, 139, 783, 791, 182, 392, 183, 312, 330,
131227
+ /* 1340 */ 714, 888, 713, 851, 692, 195, 712, 406, 686, 705,
131228
+ /* 1350 */ 313, 685, 64, 839, 274, 72, 684, 334, 942, 95,
131229
+ /* 1360 */ 752, 279, 281, 704, 753, 751, 422, 283, 411, 750,
131230
+ /* 1370 */ 426, 66, 204, 409, 21, 285, 928, 669, 437, 205,
131231
+ /* 1380 */ 207, 208, 438, 658, 657, 652, 118, 108, 119, 226,
131232
+ /* 1390 */ 650, 341, 157, 235, 169, 345, 106, 734, 790, 296,
131233
+ /* 1400 */ 294, 295, 120, 297, 867, 865, 127, 128, 130, 724,
131234
+ /* 1410 */ 229, 174, 249, 882, 137, 230, 138, 135, 885, 231,
131235
+ /* 1420 */ 59, 60, 177, 881, 7, 178, 12, 179, 256, 874,
131236
+ /* 1430 */ 140, 193, 962, 374, 141, 152, 666, 378, 276, 184,
131237
+ /* 1440 */ 270, 122, 142, 382, 387, 62, 13, 14, 703, 63,
131238
+ /* 1450 */ 125, 317, 318, 227, 809, 808, 837, 732, 15, 164,
131239
+ /* 1460 */ 736, 4, 765, 211, 399, 213, 192, 143, 760, 70,
131240
+ /* 1470 */ 67, 16, 17, 838, 836, 891, 841, 890, 198, 197,
131241
+ /* 1480 */ 917, 154, 421, 923, 918, 155, 200, 977, 425, 840,
131242
+ /* 1490 */ 156, 201, 807, 676, 80, 302, 299, 977, 202, 1261,
131243
+ /* 1500 */ 1260,
128828131244
};
128829131245
static const YYCODETYPE yy_lookahead[] = {
128830
- /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
128831
- /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
128832
- /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
128833
- /* 30 */ 19, 50, 51, 80, 81, 82, 83, 95, 85, 86,
128834
- /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 157,
128835
- /* 50 */ 27, 28, 71, 72, 73, 74, 75, 76, 77, 78,
128836
- /* 60 */ 79, 80, 81, 82, 83, 66, 85, 86, 87, 88,
128837
- /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
128838
- /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
128839
- /* 90 */ 152, 33, 152, 22, 27, 28, 179, 180, 27, 28,
128840
- /* 100 */ 42, 27, 27, 28, 152, 188, 95, 152, 50, 51,
128841
- /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 227,
128842
- /* 120 */ 97, 98, 230, 112, 172, 173, 172, 172, 173, 71,
128843
- /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
128844
- /* 140 */ 82, 83, 66, 85, 86, 87, 88, 89, 90, 91,
128845
- /* 150 */ 92, 93, 94, 95, 19, 172, 89, 90, 218, 207,
128846
- /* 160 */ 208, 26, 207, 208, 97, 98, 91, 100, 97, 98,
128847
- /* 170 */ 69, 97, 97, 98, 107, 237, 109, 89, 90, 91,
128848
- /* 180 */ 92, 93, 94, 95, 152, 50, 51, 97, 98, 99,
128849
- /* 190 */ 55, 59, 102, 103, 104, 119, 120, 59, 97, 132,
128850
- /* 200 */ 133, 152, 101, 113, 66, 19, 71, 72, 73, 74,
128851
- /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 187,
128852
- /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
128853
- /* 230 */ 95, 172, 210, 132, 133, 134, 50, 51, 185, 53,
128854
- /* 240 */ 108, 109, 110, 221, 222, 223, 108, 109, 110, 22,
128855
- /* 250 */ 22, 119, 120, 181, 27, 27, 28, 71, 72, 73,
128856
- /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
128857
- /* 270 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
128858
- /* 280 */ 94, 95, 19, 152, 148, 149, 115, 24, 117, 118,
128859
- /* 290 */ 154, 152, 156, 152, 163, 94, 95, 69, 249, 163,
128860
- /* 300 */ 27, 28, 99, 172, 173, 102, 103, 104, 194, 195,
128861
- /* 310 */ 152, 27, 28, 50, 51, 181, 113, 89, 90, 152,
128862
- /* 320 */ 206, 221, 222, 223, 97, 97, 187, 196, 175, 101,
128863
- /* 330 */ 172, 173, 196, 219, 71, 72, 73, 74, 75, 76,
128864
- /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
128865
- /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
128866
- /* 360 */ 132, 133, 134, 23, 66, 207, 208, 22, 27, 28,
128867
- /* 370 */ 97, 98, 27, 28, 221, 222, 223, 199, 22, 243,
128868
- /* 380 */ 24, 97, 98, 27, 221, 222, 223, 209, 152, 152,
128869
- /* 390 */ 50, 51, 168, 169, 170, 59, 26, 124, 100, 58,
128870
- /* 400 */ 152, 175, 66, 240, 163, 169, 170, 152, 124, 172,
128871
- /* 410 */ 173, 71, 72, 73, 74, 75, 76, 77, 78, 79,
128872
- /* 420 */ 80, 81, 82, 83, 12, 85, 86, 87, 88, 89,
128873
- /* 430 */ 90, 91, 92, 93, 94, 95, 19, 196, 97, 98,
128874
- /* 440 */ 23, 29, 97, 98, 108, 109, 110, 221, 222, 223,
128875
- /* 450 */ 50, 51, 152, 97, 168, 169, 170, 45, 37, 47,
128876
- /* 460 */ 219, 224, 119, 120, 152, 229, 152, 50, 51, 169,
128877
- /* 470 */ 170, 59, 231, 52, 74, 75, 106, 236, 152, 21,
128878
- /* 480 */ 24, 60, 163, 27, 172, 173, 172, 173, 71, 72,
128879
- /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
128880
- /* 500 */ 83, 101, 85, 86, 87, 88, 89, 90, 91, 92,
128881
- /* 510 */ 93, 94, 95, 19, 152, 196, 152, 23, 152, 207,
128882
- /* 520 */ 152, 207, 163, 65, 19, 171, 152, 190, 191, 229,
128883
- /* 530 */ 211, 212, 111, 179, 172, 173, 172, 173, 172, 173,
128884
- /* 540 */ 172, 173, 190, 191, 50, 51, 172, 173, 186, 22,
128885
- /* 550 */ 186, 24, 186, 97, 186, 196, 51, 89, 90, 22,
128886
- /* 560 */ 23, 103, 137, 26, 139, 71, 72, 73, 74, 75,
128887
- /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 219, 85,
128888
- /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
128889
- /* 590 */ 19, 195, 152, 152, 23, 236, 163, 12, 140, 152,
128890
- /* 600 */ 132, 133, 206, 152, 164, 23, 31, 70, 26, 19,
128891
- /* 610 */ 35, 160, 107, 152, 29, 164, 152, 112, 28, 172,
128892
- /* 620 */ 173, 50, 51, 183, 49, 185, 152, 22, 23, 196,
128893
- /* 630 */ 45, 26, 47, 172, 173, 0, 1, 2, 152, 16,
128894
- /* 640 */ 152, 19, 71, 72, 73, 74, 75, 76, 77, 78,
128895
- /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
128896
- /* 660 */ 89, 90, 91, 92, 93, 94, 95, 164, 152, 152,
128897
- /* 670 */ 152, 152, 50, 51, 16, 70, 108, 109, 110, 193,
128898
- /* 680 */ 98, 7, 8, 9, 152, 62, 22, 64, 172, 173,
128899
- /* 690 */ 172, 173, 218, 71, 72, 73, 74, 75, 76, 77,
128900
- /* 700 */ 78, 79, 80, 81, 82, 83, 124, 85, 86, 87,
128901
- /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
128902
- /* 720 */ 62, 152, 64, 181, 152, 193, 152, 241, 246, 247,
128903
- /* 730 */ 26, 152, 152, 152, 217, 152, 91, 249, 152, 172,
128904
- /* 740 */ 173, 172, 173, 79, 172, 173, 172, 173, 152, 50,
128905
- /* 750 */ 51, 172, 173, 172, 173, 172, 173, 116, 172, 173,
128906
- /* 760 */ 138, 116, 121, 140, 22, 23, 121, 152, 172, 173,
128907
- /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
128908
- /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
128909
- /* 790 */ 91, 92, 93, 94, 95, 19, 152, 217, 152, 152,
128910
- /* 800 */ 24, 152, 98, 172, 173, 108, 109, 110, 193, 152,
128911
- /* 810 */ 213, 152, 70, 152, 152, 152, 172, 173, 172, 173,
128912
- /* 820 */ 152, 172, 173, 152, 146, 147, 50, 51, 124, 172,
128913
- /* 830 */ 173, 172, 173, 172, 173, 172, 173, 138, 22, 23,
128914
- /* 840 */ 193, 152, 152, 172, 173, 152, 19, 71, 72, 73,
128915
- /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
128916
- /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
128917
- /* 870 */ 94, 95, 152, 152, 152, 194, 195, 50, 51, 217,
128918
- /* 880 */ 172, 173, 193, 193, 26, 152, 70, 206, 152, 152,
128919
- /* 890 */ 26, 163, 172, 173, 172, 173, 152, 19, 71, 72,
128920
- /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
128921
- /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
128922
- /* 920 */ 93, 94, 95, 152, 196, 152, 193, 152, 50, 51,
128923
- /* 930 */ 193, 172, 173, 19, 152, 166, 167, 51, 166, 167,
128924
- /* 940 */ 152, 152, 28, 172, 173, 172, 173, 152, 19, 71,
128925
- /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
128926
- /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
128927
- /* 970 */ 92, 93, 94, 95, 152, 193, 152, 211, 212, 50,
128928
- /* 980 */ 51, 33, 172, 173, 244, 245, 23, 123, 130, 26,
128929
- /* 990 */ 42, 100, 101, 107, 172, 173, 172, 173, 152, 19,
128930
- /* 1000 */ 22, 72, 73, 74, 75, 76, 77, 78, 79, 80,
128931
- /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
128932
- /* 1020 */ 91, 92, 93, 94, 95, 152, 237, 152, 7, 8,
128933
- /* 1030 */ 50, 51, 237, 172, 173, 23, 23, 23, 26, 26,
128934
- /* 1040 */ 26, 23, 132, 133, 26, 172, 173, 172, 173, 23,
128935
- /* 1050 */ 163, 152, 26, 73, 74, 75, 76, 77, 78, 79,
128936
- /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
128937
- /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 27, 22,
128938
- /* 1080 */ 23, 210, 152, 196, 27, 28, 132, 133, 152, 19,
128939
- /* 1090 */ 20, 23, 22, 27, 26, 38, 152, 27, 28, 152,
128940
- /* 1100 */ 122, 152, 172, 173, 152, 163, 191, 23, 38, 152,
128941
- /* 1110 */ 26, 152, 163, 152, 57, 27, 172, 173, 163, 172,
128942
- /* 1120 */ 173, 172, 173, 66, 172, 173, 69, 57, 163, 172,
128943
- /* 1130 */ 173, 172, 173, 172, 173, 152, 66, 152, 196, 69,
128944
- /* 1140 */ 163, 101, 152, 152, 152, 196, 89, 90, 97, 152,
128945
- /* 1150 */ 152, 196, 112, 96, 97, 98, 207, 208, 101, 89,
128946
- /* 1160 */ 90, 196, 23, 97, 233, 26, 96, 97, 98, 172,
128947
- /* 1170 */ 173, 101, 152, 196, 152, 19, 20, 23, 22, 152,
128948
- /* 1180 */ 26, 152, 152, 27, 28, 97, 152, 152, 152, 132,
128949
- /* 1190 */ 133, 134, 135, 136, 38, 152, 152, 152, 152, 232,
128950
- /* 1200 */ 197, 214, 132, 133, 134, 135, 136, 198, 150, 210,
128951
- /* 1210 */ 210, 210, 201, 57, 238, 176, 214, 201, 180, 238,
128952
- /* 1220 */ 214, 184, 175, 19, 20, 69, 22, 175, 175, 198,
128953
- /* 1230 */ 226, 27, 28, 200, 155, 39, 242, 122, 41, 159,
128954
- /* 1240 */ 159, 159, 38, 22, 239, 89, 90, 91, 220, 239,
128955
- /* 1250 */ 71, 189, 96, 97, 98, 130, 201, 101, 18, 192,
128956
- /* 1260 */ 159, 57, 18, 192, 192, 192, 158, 189, 220, 159,
128957
- /* 1270 */ 201, 158, 189, 69, 137, 201, 235, 19, 20, 46,
128958
- /* 1280 */ 22, 159, 159, 234, 158, 27, 28, 22, 132, 133,
128959
- /* 1290 */ 134, 135, 136, 89, 90, 177, 38, 159, 158, 158,
128960
- /* 1300 */ 96, 97, 98, 159, 177, 101, 107, 174, 174, 174,
128961
- /* 1310 */ 48, 182, 106, 177, 182, 57, 174, 125, 216, 176,
128962
- /* 1320 */ 174, 174, 174, 107, 215, 159, 215, 69, 216, 159,
128963
- /* 1330 */ 216, 215, 137, 216, 215, 177, 132, 133, 134, 135,
128964
- /* 1340 */ 136, 95, 177, 129, 126, 225, 127, 89, 90, 228,
128965
- /* 1350 */ 205, 128, 228, 204, 96, 97, 98, 25, 203, 101,
128966
- /* 1360 */ 5, 202, 201, 162, 26, 10, 11, 12, 13, 14,
128967
- /* 1370 */ 161, 13, 17, 153, 6, 153, 151, 151, 151, 151,
128968
- /* 1380 */ 165, 178, 165, 178, 4, 3, 22, 32, 15, 34,
128969
- /* 1390 */ 132, 133, 134, 135, 136, 245, 165, 142, 43, 248,
128970
- /* 1400 */ 248, 68, 16, 120, 23, 131, 23, 111, 123, 20,
128971
- /* 1410 */ 16, 56, 125, 1, 123, 131, 79, 111, 63, 79,
128972
- /* 1420 */ 28, 66, 67, 36, 122, 1, 5, 22, 107, 140,
128973
- /* 1430 */ 54, 54, 26, 61, 44, 107, 20, 24, 19, 112,
128974
- /* 1440 */ 105, 53, 22, 40, 22, 22, 53, 30, 23, 22,
128975
- /* 1450 */ 22, 53, 23, 23, 23, 116, 22, 11, 23, 22,
128976
- /* 1460 */ 28, 23, 26, 122, 23, 22, 124, 122, 26, 114,
128977
- /* 1470 */ 26, 23, 23, 23, 22, 36, 36, 26, 23, 23,
128978
- /* 1480 */ 22, 36, 122, 24, 23, 22, 26, 22, 24, 23,
128979
- /* 1490 */ 23, 122, 23, 22, 15, 23, 141, 122, 1,
128980
-};
128981
-#define YY_SHIFT_USE_DFLT (-72)
131246
+ /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28,
131247
+ /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131248
+ /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131249
+ /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133,
131250
+ /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33,
131251
+ /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 92, 43,
131252
+ /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131253
+ /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97,
131254
+ /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28,
131255
+ /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131256
+ /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131257
+ /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19,
131258
+ /* 120 */ 249, 22, 172, 172, 173, 52, 53, 27, 28, 29,
131259
+ /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
131260
+ /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49,
131261
+ /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208,
131262
+ /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32,
131263
+ /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79,
131264
+ /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131265
+ /* 190 */ 53, 19, 0, 1, 2, 23, 97, 98, 193, 27,
131266
+ /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131267
+ /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131268
+ /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172,
131269
+ /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32,
131270
+ /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131271
+ /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131272
+ /* 260 */ 53, 19, 221, 222, 223, 23, 168, 169, 170, 27,
131273
+ /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131274
+ /* 280 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131275
+ /* 290 */ 48, 49, 50, 51, 52, 53, 19, 157, 22, 23,
131276
+ /* 300 */ 23, 96, 26, 172, 27, 28, 29, 30, 31, 32,
131277
+ /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131278
+ /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131279
+ /* 330 */ 53, 19, 108, 109, 110, 221, 222, 223, 185, 27,
131280
+ /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131281
+ /* 350 */ 38, 39, 40, 41, 240, 43, 44, 45, 46, 47,
131282
+ /* 360 */ 48, 49, 50, 51, 52, 53, 19, 227, 22, 23,
131283
+ /* 370 */ 230, 22, 96, 152, 27, 28, 29, 30, 31, 32,
131284
+ /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 30,
131285
+ /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131286
+ /* 400 */ 53, 19, 190, 191, 55, 56, 24, 190, 191, 27,
131287
+ /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131288
+ /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131289
+ /* 430 */ 48, 49, 50, 51, 52, 53, 168, 169, 170, 179,
131290
+ /* 440 */ 180, 171, 96, 19, 172, 173, 97, 98, 188, 179,
131291
+ /* 450 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35,
131292
+ /* 460 */ 36, 37, 38, 39, 40, 41, 107, 43, 44, 45,
131293
+ /* 470 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 207,
131294
+ /* 480 */ 208, 30, 31, 32, 33, 138, 27, 28, 29, 30,
131295
+ /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131296
+ /* 500 */ 41, 181, 43, 44, 45, 46, 47, 48, 49, 50,
131297
+ /* 510 */ 51, 52, 53, 19, 152, 7, 8, 9, 49, 22,
131298
+ /* 520 */ 19, 24, 28, 29, 30, 31, 32, 33, 34, 35,
131299
+ /* 530 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45,
131300
+ /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 108,
131301
+ /* 550 */ 109, 110, 101, 55, 53, 193, 172, 173, 29, 30,
131302
+ /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131303
+ /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
131304
+ /* 580 */ 51, 52, 53, 19, 20, 116, 22, 23, 169, 170,
131305
+ /* 590 */ 121, 207, 85, 55, 56, 97, 19, 20, 195, 22,
131306
+ /* 600 */ 99, 100, 101, 102, 103, 104, 105, 12, 152, 206,
131307
+ /* 610 */ 210, 47, 48, 112, 152, 108, 109, 110, 54, 55,
131308
+ /* 620 */ 56, 221, 222, 223, 47, 48, 119, 120, 172, 173,
131309
+ /* 630 */ 66, 54, 55, 56, 101, 97, 98, 99, 148, 149,
131310
+ /* 640 */ 102, 103, 104, 66, 154, 112, 156, 83, 229, 47,
131311
+ /* 650 */ 48, 113, 57, 163, 194, 195, 92, 246, 247, 95,
131312
+ /* 660 */ 83, 97, 98, 207, 208, 101, 206, 59, 73, 92,
131313
+ /* 670 */ 75, 63, 95, 163, 97, 98, 194, 195, 101, 219,
131314
+ /* 680 */ 85, 181, 19, 152, 175, 77, 196, 152, 206, 19,
131315
+ /* 690 */ 20, 199, 22, 30, 163, 11, 132, 133, 134, 135,
131316
+ /* 700 */ 136, 209, 152, 172, 173, 152, 196, 172, 173, 132,
131317
+ /* 710 */ 133, 134, 135, 136, 164, 92, 213, 47, 48, 49,
131318
+ /* 720 */ 92, 186, 169, 170, 54, 55, 56, 196, 100, 219,
131319
+ /* 730 */ 221, 222, 223, 243, 132, 133, 66, 175, 207, 208,
131320
+ /* 740 */ 152, 231, 119, 120, 19, 20, 236, 22, 152, 38,
131321
+ /* 750 */ 39, 40, 41, 83, 43, 44, 45, 46, 47, 48,
131322
+ /* 760 */ 49, 50, 51, 52, 53, 95, 152, 97, 98, 85,
131323
+ /* 770 */ 107, 101, 47, 48, 163, 112, 92, 152, 152, 54,
131324
+ /* 780 */ 55, 56, 229, 221, 222, 223, 172, 173, 163, 49,
131325
+ /* 790 */ 152, 66, 108, 109, 110, 55, 56, 172, 173, 163,
131326
+ /* 800 */ 186, 22, 132, 133, 134, 135, 136, 196, 83, 43,
131327
+ /* 810 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131328
+ /* 820 */ 95, 196, 97, 98, 85, 99, 101, 152, 102, 103,
131329
+ /* 830 */ 104, 92, 196, 146, 147, 152, 181, 97, 98, 113,
131330
+ /* 840 */ 19, 20, 152, 22, 218, 22, 116, 108, 109, 110,
131331
+ /* 850 */ 152, 121, 55, 56, 12, 219, 218, 132, 133, 134,
131332
+ /* 860 */ 135, 136, 172, 173, 55, 56, 55, 56, 47, 48,
131333
+ /* 870 */ 172, 173, 236, 152, 5, 54, 55, 56, 55, 10,
131334
+ /* 880 */ 11, 12, 13, 14, 186, 152, 17, 66, 47, 48,
131335
+ /* 890 */ 152, 210, 16, 84, 97, 98, 55, 56, 21, 57,
131336
+ /* 900 */ 217, 122, 22, 152, 83, 152, 97, 98, 97, 98,
131337
+ /* 910 */ 172, 173, 152, 152, 224, 73, 95, 75, 97, 98,
131338
+ /* 920 */ 97, 124, 101, 172, 173, 164, 193, 47, 48, 60,
131339
+ /* 930 */ 163, 62, 172, 173, 24, 55, 56, 186, 97, 98,
131340
+ /* 940 */ 71, 100, 55, 56, 183, 207, 185, 152, 107, 23,
131341
+ /* 950 */ 109, 82, 26, 132, 133, 134, 135, 136, 89, 152,
131342
+ /* 960 */ 26, 92, 93, 196, 88, 55, 90, 152, 91, 152,
131343
+ /* 970 */ 217, 152, 152, 132, 133, 95, 152, 97, 211, 212,
131344
+ /* 980 */ 103, 101, 152, 114, 97, 98, 152, 172, 173, 19,
131345
+ /* 990 */ 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
131346
+ /* 1000 */ 48, 49, 50, 51, 52, 53, 65, 97, 152, 152,
131347
+ /* 1010 */ 141, 124, 132, 133, 134, 152, 140, 140, 152, 78,
131348
+ /* 1020 */ 152, 233, 152, 193, 98, 152, 56, 86, 172, 173,
131349
+ /* 1030 */ 166, 167, 237, 152, 217, 172, 173, 152, 172, 173,
131350
+ /* 1040 */ 172, 173, 172, 173, 237, 172, 173, 152, 152, 152,
131351
+ /* 1050 */ 124, 152, 111, 172, 173, 152, 237, 172, 173, 152,
131352
+ /* 1060 */ 55, 152, 26, 152, 130, 152, 152, 172, 173, 172,
131353
+ /* 1070 */ 173, 172, 173, 249, 152, 172, 173, 152, 61, 172,
131354
+ /* 1080 */ 173, 172, 173, 172, 173, 172, 173, 70, 152, 193,
131355
+ /* 1090 */ 152, 137, 152, 139, 172, 173, 152, 172, 173, 152,
131356
+ /* 1100 */ 152, 152, 97, 152, 26, 152, 163, 152, 172, 173,
131357
+ /* 1110 */ 172, 173, 172, 173, 152, 16, 172, 173, 26, 172,
131358
+ /* 1120 */ 173, 172, 173, 172, 173, 172, 173, 172, 173, 163,
131359
+ /* 1130 */ 152, 152, 152, 22, 172, 173, 152, 241, 152, 196,
131360
+ /* 1140 */ 152, 193, 106, 152, 152, 152, 163, 152, 37, 152,
131361
+ /* 1150 */ 172, 173, 172, 173, 152, 152, 172, 173, 172, 173,
131362
+ /* 1160 */ 172, 173, 196, 172, 173, 172, 173, 172, 173, 172,
131363
+ /* 1170 */ 173, 152, 152, 152, 172, 173, 98, 152, 152, 196,
131364
+ /* 1180 */ 160, 22, 23, 19, 164, 193, 152, 88, 232, 90,
131365
+ /* 1190 */ 191, 172, 173, 172, 173, 163, 193, 172, 173, 166,
131366
+ /* 1200 */ 167, 163, 124, 163, 244, 245, 23, 211, 212, 26,
131367
+ /* 1210 */ 55, 23, 55, 23, 26, 123, 26, 152, 23, 193,
131368
+ /* 1220 */ 56, 26, 23, 23, 23, 26, 26, 26, 196, 100,
131369
+ /* 1230 */ 101, 7, 8, 152, 196, 23, 196, 23, 26, 152,
131370
+ /* 1240 */ 26, 132, 133, 23, 132, 133, 26, 152, 152, 152,
131371
+ /* 1250 */ 152, 210, 97, 152, 97, 96, 152, 152, 152, 152,
131372
+ /* 1260 */ 152, 210, 152, 210, 197, 152, 152, 152, 152, 152,
131373
+ /* 1270 */ 152, 152, 152, 152, 152, 152, 152, 198, 150, 176,
131374
+ /* 1280 */ 214, 201, 214, 238, 201, 238, 184, 214, 226, 200,
131375
+ /* 1290 */ 155, 198, 67, 122, 242, 159, 159, 69, 239, 239,
131376
+ /* 1300 */ 159, 175, 175, 22, 220, 180, 175, 27, 130, 18,
131377
+ /* 1310 */ 159, 18, 158, 137, 220, 159, 158, 235, 74, 189,
131378
+ /* 1320 */ 234, 159, 159, 158, 22, 192, 192, 177, 159, 159,
131379
+ /* 1330 */ 192, 192, 189, 201, 189, 158, 107, 158, 177, 76,
131380
+ /* 1340 */ 174, 201, 174, 201, 106, 159, 174, 125, 174, 182,
131381
+ /* 1350 */ 177, 176, 107, 159, 174, 137, 174, 53, 174, 129,
131382
+ /* 1360 */ 216, 215, 215, 182, 216, 216, 177, 215, 126, 216,
131383
+ /* 1370 */ 177, 128, 25, 127, 26, 215, 13, 162, 161, 153,
131384
+ /* 1380 */ 153, 6, 151, 151, 151, 151, 165, 178, 165, 178,
131385
+ /* 1390 */ 4, 3, 22, 142, 15, 94, 16, 205, 120, 202,
131386
+ /* 1400 */ 204, 203, 165, 201, 23, 23, 131, 111, 123, 20,
131387
+ /* 1410 */ 225, 125, 16, 1, 131, 228, 111, 123, 56, 228,
131388
+ /* 1420 */ 37, 37, 64, 1, 5, 122, 22, 107, 140, 80,
131389
+ /* 1430 */ 80, 26, 87, 72, 107, 24, 20, 19, 112, 105,
131390
+ /* 1440 */ 23, 68, 22, 79, 79, 22, 22, 22, 58, 22,
131391
+ /* 1450 */ 245, 248, 248, 79, 23, 23, 23, 116, 22, 122,
131392
+ /* 1460 */ 23, 22, 56, 23, 26, 23, 64, 22, 124, 26,
131393
+ /* 1470 */ 26, 64, 64, 23, 23, 23, 11, 23, 22, 26,
131394
+ /* 1480 */ 23, 22, 24, 1, 23, 22, 26, 250, 24, 23,
131395
+ /* 1490 */ 22, 122, 23, 23, 22, 15, 23, 250, 122, 122,
131396
+ /* 1500 */ 122,
131397
+};
131398
+#define YY_SHIFT_USE_DFLT (-95)
128982131399
#define YY_SHIFT_COUNT (439)
128983
-#define YY_SHIFT_MIN (-71)
128984
-#define YY_SHIFT_MAX (1497)
131400
+#define YY_SHIFT_MIN (-94)
131401
+#define YY_SHIFT_MAX (1482)
128985131402
static const short yy_shift_ofst[] = {
128986
- /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 138, -19, 58,
128987
- /* 10 */ 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 67,
128988
- /* 20 */ 67, 90, 132, 336, 76, 135, 263, 340, 417, 494,
128989
- /* 30 */ 571, 622, 699, 776, 827, 827, 827, 827, 827, 827,
128990
- /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 878,
128991
- /* 50 */ 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204, 1204,
128992
- /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
128993
- /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
128994
- /* 80 */ 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204, 1204,
128995
- /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47, -47,
128996
- /* 100 */ -47, -47, -47, -6, 88, -66, 23, 458, 505, 468,
128997
- /* 110 */ 468, 23, 201, 343, -58, -72, -72, -72, 11, 11,
128998
- /* 120 */ 11, 412, 412, 341, 537, 605, 23, 23, 23, 23,
128999
- /* 130 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
129000
- /* 140 */ 23, 23, 23, 23, 23, 23, 635, 298, 74, 74,
129001
- /* 150 */ 343, -1, -1, -1, -1, -1, -1, -72, -72, -72,
129002
- /* 160 */ 228, 101, 101, 203, 75, 71, 273, 284, 345, 23,
129003
- /* 170 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
129004
- /* 180 */ 23, 23, 23, 23, 23, 23, 421, 421, 421, 23,
129005
- /* 190 */ 23, 582, 23, 23, 23, 356, 23, 23, 585, 23,
129006
- /* 200 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 568,
129007
- /* 210 */ 575, 456, 456, 456, 704, 171, 645, 674, 858, 590,
129008
- /* 220 */ 590, 914, 858, 914, 370, 963, 886, 948, 590, 425,
129009
- /* 230 */ 948, 948, 864, 641, 527, 1196, 1115, 1115, 1197, 1197,
129010
- /* 240 */ 1115, 1221, 1179, 1125, 1240, 1240, 1240, 1240, 1115, 1244,
129011
- /* 250 */ 1125, 1221, 1179, 1179, 1125, 1115, 1244, 1137, 1233, 1115,
129012
- /* 260 */ 1115, 1244, 1265, 1115, 1244, 1115, 1244, 1265, 1199, 1199,
129013
- /* 270 */ 1199, 1262, 1265, 1199, 1206, 1199, 1262, 1199, 1199, 1192,
129014
- /* 280 */ 1216, 1192, 1216, 1192, 1216, 1192, 1216, 1115, 1115, 1195,
129015
- /* 290 */ 1265, 1246, 1246, 1265, 1214, 1218, 1223, 1219, 1125, 1332,
129016
- /* 300 */ 1338, 1358, 1358, 1368, 1368, 1368, 1368, -72, -72, -72,
129017
- /* 310 */ -72, -72, -72, -72, -72, 400, 623, 742, 816, 658,
129018
- /* 320 */ 697, 227, 1012, 664, 1013, 1014, 1018, 1026, 1051, 891,
129019
- /* 330 */ 1021, 1040, 1068, 1084, 1066, 1139, 910, 954, 1154, 1088,
129020
- /* 340 */ 978, 1380, 1382, 1364, 1255, 1373, 1333, 1386, 1381, 1383,
129021
- /* 350 */ 1283, 1274, 1296, 1285, 1389, 1287, 1394, 1412, 1291, 1284,
129022
- /* 360 */ 1337, 1340, 1306, 1392, 1387, 1302, 1424, 1421, 1405, 1321,
129023
- /* 370 */ 1289, 1376, 1406, 1377, 1372, 1390, 1328, 1413, 1416, 1419,
129024
- /* 380 */ 1327, 1335, 1420, 1388, 1422, 1423, 1425, 1427, 1393, 1417,
129025
- /* 390 */ 1428, 1398, 1403, 1429, 1430, 1431, 1339, 1434, 1435, 1437,
129026
- /* 400 */ 1436, 1341, 1438, 1441, 1432, 1439, 1443, 1342, 1442, 1440,
129027
- /* 410 */ 1444, 1445, 1442, 1448, 1449, 1450, 1451, 1455, 1452, 1446,
129028
- /* 420 */ 1456, 1458, 1459, 1460, 1461, 1463, 1464, 1460, 1466, 1465,
129029
- /* 430 */ 1467, 1469, 1471, 1345, 1360, 1369, 1375, 1472, 1479, 1497,
131403
+ /* 0 */ 40, 564, 869, 577, 725, 725, 725, 739, -19, 16,
131404
+ /* 10 */ 16, 100, 725, 725, 725, 725, 725, 725, 725, 841,
131405
+ /* 20 */ 841, 538, 507, 684, 623, 61, 137, 172, 207, 242,
131406
+ /* 30 */ 277, 312, 347, 382, 424, 424, 424, 424, 424, 424,
131407
+ /* 40 */ 424, 424, 424, 424, 424, 424, 424, 424, 424, 459,
131408
+ /* 50 */ 424, 494, 529, 529, 670, 725, 725, 725, 725, 725,
131409
+ /* 60 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131410
+ /* 70 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131411
+ /* 80 */ 725, 725, 725, 821, 725, 725, 725, 725, 725, 725,
131412
+ /* 90 */ 725, 725, 725, 725, 725, 725, 725, 952, 711, 711,
131413
+ /* 100 */ 711, 711, 711, 766, 23, 32, 811, 877, 663, 602,
131414
+ /* 110 */ 602, 811, 73, 113, -51, -95, -95, -95, 501, 501,
131415
+ /* 120 */ 501, 595, 595, 809, 205, 276, 811, 811, 811, 811,
131416
+ /* 130 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131417
+ /* 140 */ 811, 811, 811, 811, 811, 811, 192, 628, 498, 498,
131418
+ /* 150 */ 113, -34, -34, -34, -34, -34, -34, -95, -95, -95,
131419
+ /* 160 */ 880, -94, -94, 726, 740, 99, 797, 887, 349, 811,
131420
+ /* 170 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131421
+ /* 180 */ 811, 811, 811, 811, 811, 811, 941, 941, 941, 811,
131422
+ /* 190 */ 811, 926, 811, 811, 811, -18, 811, 811, 842, 811,
131423
+ /* 200 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 224,
131424
+ /* 210 */ 608, 910, 910, 910, 1078, 45, 469, 508, 934, 970,
131425
+ /* 220 */ 970, 1164, 934, 1164, 1036, 1183, 359, 1017, 970, 954,
131426
+ /* 230 */ 1017, 1017, 1092, 730, 497, 1225, 1171, 1171, 1228, 1228,
131427
+ /* 240 */ 1171, 1281, 1280, 1178, 1291, 1291, 1291, 1291, 1171, 1293,
131428
+ /* 250 */ 1178, 1281, 1280, 1280, 1178, 1171, 1293, 1176, 1244, 1171,
131429
+ /* 260 */ 1171, 1293, 1302, 1171, 1293, 1171, 1293, 1302, 1229, 1229,
131430
+ /* 270 */ 1229, 1263, 1302, 1229, 1238, 1229, 1263, 1229, 1229, 1222,
131431
+ /* 280 */ 1245, 1222, 1245, 1222, 1245, 1222, 1245, 1171, 1171, 1218,
131432
+ /* 290 */ 1302, 1304, 1304, 1302, 1230, 1242, 1243, 1246, 1178, 1347,
131433
+ /* 300 */ 1348, 1363, 1363, 1375, 1375, 1375, 1375, -95, -95, -95,
131434
+ /* 310 */ -95, -95, -95, -95, -95, 451, 876, 346, 1159, 1099,
131435
+ /* 320 */ 441, 823, 1188, 1111, 1190, 1195, 1199, 1200, 1005, 1129,
131436
+ /* 330 */ 1224, 533, 1201, 1212, 1155, 1214, 1109, 1112, 1220, 1157,
131437
+ /* 340 */ 779, 1386, 1388, 1370, 1251, 1379, 1301, 1380, 1381, 1382,
131438
+ /* 350 */ 1278, 1275, 1296, 1285, 1389, 1286, 1396, 1412, 1294, 1283,
131439
+ /* 360 */ 1383, 1384, 1305, 1362, 1358, 1303, 1422, 1419, 1404, 1320,
131440
+ /* 370 */ 1288, 1349, 1405, 1350, 1345, 1361, 1327, 1411, 1416, 1418,
131441
+ /* 380 */ 1326, 1334, 1420, 1364, 1423, 1424, 1417, 1425, 1365, 1390,
131442
+ /* 390 */ 1427, 1374, 1373, 1431, 1432, 1433, 1341, 1436, 1437, 1439,
131443
+ /* 400 */ 1438, 1337, 1440, 1442, 1406, 1402, 1445, 1344, 1443, 1407,
131444
+ /* 410 */ 1444, 1408, 1443, 1450, 1451, 1452, 1453, 1454, 1456, 1465,
131445
+ /* 420 */ 1457, 1459, 1458, 1460, 1461, 1463, 1464, 1460, 1466, 1468,
131446
+ /* 430 */ 1469, 1470, 1472, 1369, 1376, 1377, 1378, 1473, 1480, 1482,
129030131447
};
129031
-#define YY_REDUCE_USE_DFLT (-144)
131448
+#define YY_REDUCE_USE_DFLT (-130)
129032131449
#define YY_REDUCE_COUNT (314)
129033
-#define YY_REDUCE_MIN (-143)
129034
-#define YY_REDUCE_MAX (1231)
131450
+#define YY_REDUCE_MIN (-129)
131451
+#define YY_REDUCE_MAX (1237)
129035131452
static const short yy_reduce_ofst[] = {
129036
- /* 0 */ -143, 949, 136, 131, -48, -45, 158, 241, 22, 153,
129037
- /* 10 */ 226, 163, 362, 364, 366, 312, 314, 368, 237, 236,
129038
- /* 20 */ 300, 440, 114, 359, 319, 100, 100, 100, 100, 100,
129039
- /* 30 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
129040
- /* 40 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
129041
- /* 50 */ 100, 100, 100, 100, 374, 447, 461, 516, 518, 567,
129042
- /* 60 */ 569, 572, 574, 579, 581, 583, 586, 596, 631, 644,
129043
- /* 70 */ 646, 649, 657, 659, 661, 663, 671, 708, 720, 722,
129044
- /* 80 */ 759, 771, 773, 810, 822, 824, 861, 873, 875, 930,
129045
- /* 90 */ 944, 947, 952, 957, 959, 961, 997, 100, 100, 100,
129046
- /* 100 */ 100, 100, 100, 100, 100, 100, 486, -108, -83, 224,
129047
- /* 110 */ 286, 451, 100, 681, 100, 100, 100, 100, 354, 354,
129048
- /* 120 */ 354, 337, 352, 49, 482, 482, 503, 532, -60, 615,
129049
- /* 130 */ 647, 689, 690, 737, 782, -62, 517, 789, 474, 795,
129050
- /* 140 */ 580, 733, 32, 662, 488, 139, 678, 433, 769, 772,
129051
- /* 150 */ 396, 728, 887, 942, 955, 965, 977, 740, 766, 178,
129052
- /* 160 */ -46, -17, 59, 53, 118, 141, 167, 248, 255, 326,
129053
- /* 170 */ 441, 464, 519, 668, 693, 721, 736, 744, 775, 788,
129054
- /* 180 */ 846, 899, 912, 936, 983, 985, 72, 134, 542, 990,
129055
- /* 190 */ 991, 597, 992, 998, 1020, 871, 1022, 1027, 915, 1029,
129056
- /* 200 */ 1030, 1034, 118, 1035, 1036, 1043, 1044, 1045, 1046, 931,
129057
- /* 210 */ 967, 999, 1000, 1001, 597, 1003, 1009, 1058, 1011, 987,
129058
- /* 220 */ 1002, 976, 1016, 981, 1039, 1037, 1038, 1047, 1006, 1004,
129059
- /* 230 */ 1052, 1053, 1033, 1031, 1079, 994, 1080, 1081, 1005, 1010,
129060
- /* 240 */ 1082, 1028, 1062, 1055, 1067, 1071, 1072, 1073, 1101, 1108,
129061
- /* 250 */ 1069, 1048, 1078, 1083, 1074, 1110, 1113, 1041, 1049, 1122,
129062
- /* 260 */ 1123, 1126, 1118, 1138, 1140, 1144, 1141, 1127, 1133, 1134,
129063
- /* 270 */ 1135, 1129, 1136, 1142, 1143, 1146, 1132, 1147, 1148, 1102,
129064
- /* 280 */ 1109, 1112, 1111, 1114, 1116, 1117, 1119, 1166, 1170, 1120,
129065
- /* 290 */ 1158, 1121, 1124, 1165, 1145, 1149, 1155, 1159, 1161, 1201,
129066
- /* 300 */ 1209, 1220, 1222, 1225, 1226, 1227, 1228, 1151, 1152, 1150,
129067
- /* 310 */ 1215, 1217, 1203, 1205, 1231,
131453
+ /* 0 */ -29, 531, 490, 625, -49, 272, 456, 510, 400, 509,
131454
+ /* 10 */ 562, 114, 535, 614, 698, 384, 738, 751, 690, 419,
131455
+ /* 20 */ 553, 761, 460, 636, 767, 41, 41, 41, 41, 41,
131456
+ /* 30 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131457
+ /* 40 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131458
+ /* 50 */ 41, 41, 41, 41, 760, 815, 856, 863, 866, 868,
131459
+ /* 60 */ 870, 873, 881, 885, 895, 897, 899, 903, 907, 909,
131460
+ /* 70 */ 911, 913, 922, 925, 936, 938, 940, 944, 947, 949,
131461
+ /* 80 */ 951, 953, 955, 962, 978, 980, 984, 986, 988, 991,
131462
+ /* 90 */ 993, 995, 997, 1002, 1019, 1021, 1025, 41, 41, 41,
131463
+ /* 100 */ 41, 41, 41, 41, 41, 41, 896, 140, 260, 98,
131464
+ /* 110 */ 268, 1020, 41, 482, 41, 41, 41, 41, 270, 270,
131465
+ /* 120 */ 270, 212, 217, -129, 411, 411, 550, 5, 626, 362,
131466
+ /* 130 */ 733, 830, 992, 1003, 1026, 795, 683, 807, 638, 819,
131467
+ /* 140 */ 753, 948, 62, 817, 824, 132, 687, 611, 864, 1033,
131468
+ /* 150 */ 403, 943, 966, 983, 1032, 1038, 1040, 960, 996, 492,
131469
+ /* 160 */ -50, 57, 131, 153, 221, 462, 588, 596, 675, 721,
131470
+ /* 170 */ 820, 834, 857, 914, 979, 1034, 1065, 1081, 1087, 1095,
131471
+ /* 180 */ 1096, 1097, 1098, 1101, 1104, 1105, 320, 500, 655, 1106,
131472
+ /* 190 */ 1107, 503, 1108, 1110, 1113, 681, 1114, 1115, 999, 1116,
131473
+ /* 200 */ 1117, 1118, 221, 1119, 1120, 1121, 1122, 1123, 1124, 788,
131474
+ /* 210 */ 956, 1041, 1051, 1053, 503, 1067, 1079, 1128, 1080, 1066,
131475
+ /* 220 */ 1068, 1045, 1083, 1047, 1103, 1102, 1125, 1126, 1073, 1062,
131476
+ /* 230 */ 1127, 1131, 1089, 1093, 1135, 1052, 1136, 1137, 1059, 1060,
131477
+ /* 240 */ 1141, 1084, 1130, 1132, 1133, 1134, 1138, 1139, 1151, 1154,
131478
+ /* 250 */ 1140, 1094, 1143, 1145, 1142, 1156, 1158, 1082, 1086, 1162,
131479
+ /* 260 */ 1163, 1165, 1150, 1169, 1177, 1170, 1179, 1161, 1166, 1168,
131480
+ /* 270 */ 1172, 1167, 1173, 1174, 1175, 1180, 1181, 1182, 1184, 1144,
131481
+ /* 280 */ 1146, 1148, 1147, 1149, 1152, 1153, 1160, 1186, 1194, 1185,
131482
+ /* 290 */ 1189, 1187, 1191, 1193, 1192, 1196, 1198, 1197, 1202, 1215,
131483
+ /* 300 */ 1217, 1226, 1227, 1231, 1232, 1233, 1234, 1203, 1204, 1205,
131484
+ /* 310 */ 1221, 1223, 1209, 1211, 1237,
129068131485
};
129069131486
static const YYACTIONTYPE yy_default[] = {
129070131487
/* 0 */ 1250, 1240, 1240, 1240, 1174, 1174, 1174, 1240, 1071, 1100,
129071131488
/* 10 */ 1100, 1224, 1301, 1301, 1301, 1301, 1301, 1301, 1173, 1301,
129072131489
/* 20 */ 1301, 1301, 1301, 1240, 1075, 1106, 1301, 1301, 1301, 1301,
@@ -129130,78 +131547,104 @@
129130131547
*/
129131131548
#ifdef YYFALLBACK
129132131549
static const YYCODETYPE yyFallback[] = {
129133131550
0, /* $ => nothing */
129134131551
0, /* SEMI => nothing */
129135
- 27, /* EXPLAIN => ID */
129136
- 27, /* QUERY => ID */
129137
- 27, /* PLAN => ID */
129138
- 27, /* BEGIN => ID */
131552
+ 55, /* EXPLAIN => ID */
131553
+ 55, /* QUERY => ID */
131554
+ 55, /* PLAN => ID */
131555
+ 55, /* BEGIN => ID */
129139131556
0, /* TRANSACTION => nothing */
129140
- 27, /* DEFERRED => ID */
129141
- 27, /* IMMEDIATE => ID */
129142
- 27, /* EXCLUSIVE => ID */
131557
+ 55, /* DEFERRED => ID */
131558
+ 55, /* IMMEDIATE => ID */
131559
+ 55, /* EXCLUSIVE => ID */
129143131560
0, /* COMMIT => nothing */
129144
- 27, /* END => ID */
129145
- 27, /* ROLLBACK => ID */
129146
- 27, /* SAVEPOINT => ID */
129147
- 27, /* RELEASE => ID */
131561
+ 55, /* END => ID */
131562
+ 55, /* ROLLBACK => ID */
131563
+ 55, /* SAVEPOINT => ID */
131564
+ 55, /* RELEASE => ID */
129148131565
0, /* TO => nothing */
129149131566
0, /* TABLE => nothing */
129150131567
0, /* CREATE => nothing */
129151
- 27, /* IF => ID */
131568
+ 55, /* IF => ID */
129152131569
0, /* NOT => nothing */
129153131570
0, /* EXISTS => nothing */
129154
- 27, /* TEMP => ID */
131571
+ 55, /* TEMP => ID */
129155131572
0, /* LP => nothing */
129156131573
0, /* RP => nothing */
129157131574
0, /* AS => nothing */
129158
- 27, /* WITHOUT => ID */
131575
+ 55, /* WITHOUT => ID */
129159131576
0, /* COMMA => nothing */
131577
+ 0, /* OR => nothing */
131578
+ 0, /* AND => nothing */
131579
+ 0, /* IS => nothing */
131580
+ 55, /* MATCH => ID */
131581
+ 55, /* LIKE_KW => ID */
131582
+ 0, /* BETWEEN => nothing */
131583
+ 0, /* IN => nothing */
131584
+ 0, /* ISNULL => nothing */
131585
+ 0, /* NOTNULL => nothing */
131586
+ 0, /* NE => nothing */
131587
+ 0, /* EQ => nothing */
131588
+ 0, /* GT => nothing */
131589
+ 0, /* LE => nothing */
131590
+ 0, /* LT => nothing */
131591
+ 0, /* GE => nothing */
131592
+ 0, /* ESCAPE => nothing */
131593
+ 0, /* BITAND => nothing */
131594
+ 0, /* BITOR => nothing */
131595
+ 0, /* LSHIFT => nothing */
131596
+ 0, /* RSHIFT => nothing */
131597
+ 0, /* PLUS => nothing */
131598
+ 0, /* MINUS => nothing */
131599
+ 0, /* STAR => nothing */
131600
+ 0, /* SLASH => nothing */
131601
+ 0, /* REM => nothing */
131602
+ 0, /* CONCAT => nothing */
131603
+ 0, /* COLLATE => nothing */
131604
+ 0, /* BITNOT => nothing */
129160131605
0, /* ID => nothing */
129161131606
0, /* INDEXED => nothing */
129162
- 27, /* ABORT => ID */
129163
- 27, /* ACTION => ID */
129164
- 27, /* AFTER => ID */
129165
- 27, /* ANALYZE => ID */
129166
- 27, /* ASC => ID */
129167
- 27, /* ATTACH => ID */
129168
- 27, /* BEFORE => ID */
129169
- 27, /* BY => ID */
129170
- 27, /* CASCADE => ID */
129171
- 27, /* CAST => ID */
129172
- 27, /* COLUMNKW => ID */
129173
- 27, /* CONFLICT => ID */
129174
- 27, /* DATABASE => ID */
129175
- 27, /* DESC => ID */
129176
- 27, /* DETACH => ID */
129177
- 27, /* EACH => ID */
129178
- 27, /* FAIL => ID */
129179
- 27, /* FOR => ID */
129180
- 27, /* IGNORE => ID */
129181
- 27, /* INITIALLY => ID */
129182
- 27, /* INSTEAD => ID */
129183
- 27, /* LIKE_KW => ID */
129184
- 27, /* MATCH => ID */
129185
- 27, /* NO => ID */
129186
- 27, /* KEY => ID */
129187
- 27, /* OF => ID */
129188
- 27, /* OFFSET => ID */
129189
- 27, /* PRAGMA => ID */
129190
- 27, /* RAISE => ID */
129191
- 27, /* RECURSIVE => ID */
129192
- 27, /* REPLACE => ID */
129193
- 27, /* RESTRICT => ID */
129194
- 27, /* ROW => ID */
129195
- 27, /* TRIGGER => ID */
129196
- 27, /* VACUUM => ID */
129197
- 27, /* VIEW => ID */
129198
- 27, /* VIRTUAL => ID */
129199
- 27, /* WITH => ID */
129200
- 27, /* REINDEX => ID */
129201
- 27, /* RENAME => ID */
129202
- 27, /* CTIME_KW => ID */
131607
+ 55, /* ABORT => ID */
131608
+ 55, /* ACTION => ID */
131609
+ 55, /* AFTER => ID */
131610
+ 55, /* ANALYZE => ID */
131611
+ 55, /* ASC => ID */
131612
+ 55, /* ATTACH => ID */
131613
+ 55, /* BEFORE => ID */
131614
+ 55, /* BY => ID */
131615
+ 55, /* CASCADE => ID */
131616
+ 55, /* CAST => ID */
131617
+ 55, /* COLUMNKW => ID */
131618
+ 55, /* CONFLICT => ID */
131619
+ 55, /* DATABASE => ID */
131620
+ 55, /* DESC => ID */
131621
+ 55, /* DETACH => ID */
131622
+ 55, /* EACH => ID */
131623
+ 55, /* FAIL => ID */
131624
+ 55, /* FOR => ID */
131625
+ 55, /* IGNORE => ID */
131626
+ 55, /* INITIALLY => ID */
131627
+ 55, /* INSTEAD => ID */
131628
+ 55, /* NO => ID */
131629
+ 55, /* KEY => ID */
131630
+ 55, /* OF => ID */
131631
+ 55, /* OFFSET => ID */
131632
+ 55, /* PRAGMA => ID */
131633
+ 55, /* RAISE => ID */
131634
+ 55, /* RECURSIVE => ID */
131635
+ 55, /* REPLACE => ID */
131636
+ 55, /* RESTRICT => ID */
131637
+ 55, /* ROW => ID */
131638
+ 55, /* TRIGGER => ID */
131639
+ 55, /* VACUUM => ID */
131640
+ 55, /* VIEW => ID */
131641
+ 55, /* VIRTUAL => ID */
131642
+ 55, /* WITH => ID */
131643
+ 55, /* REINDEX => ID */
131644
+ 55, /* RENAME => ID */
131645
+ 55, /* CTIME_KW => ID */
129203131646
};
129204131647
#endif /* YYFALLBACK */
129205131648
129206131649
/* The following structure represents a single element of the
129207131650
** parser's stack. Information stored includes:
@@ -129288,29 +131731,29 @@
129288131731
"PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
129289131732
"IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
129290131733
"ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
129291131734
"TABLE", "CREATE", "IF", "NOT",
129292131735
"EXISTS", "TEMP", "LP", "RP",
129293
- "AS", "WITHOUT", "COMMA", "ID",
131736
+ "AS", "WITHOUT", "COMMA", "OR",
131737
+ "AND", "IS", "MATCH", "LIKE_KW",
131738
+ "BETWEEN", "IN", "ISNULL", "NOTNULL",
131739
+ "NE", "EQ", "GT", "LE",
131740
+ "LT", "GE", "ESCAPE", "BITAND",
131741
+ "BITOR", "LSHIFT", "RSHIFT", "PLUS",
131742
+ "MINUS", "STAR", "SLASH", "REM",
131743
+ "CONCAT", "COLLATE", "BITNOT", "ID",
129294131744
"INDEXED", "ABORT", "ACTION", "AFTER",
129295131745
"ANALYZE", "ASC", "ATTACH", "BEFORE",
129296131746
"BY", "CASCADE", "CAST", "COLUMNKW",
129297131747
"CONFLICT", "DATABASE", "DESC", "DETACH",
129298131748
"EACH", "FAIL", "FOR", "IGNORE",
129299
- "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
129300
- "NO", "KEY", "OF", "OFFSET",
129301
- "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
129302
- "RESTRICT", "ROW", "TRIGGER", "VACUUM",
129303
- "VIEW", "VIRTUAL", "WITH", "REINDEX",
129304
- "RENAME", "CTIME_KW", "ANY", "OR",
129305
- "AND", "IS", "BETWEEN", "IN",
129306
- "ISNULL", "NOTNULL", "NE", "EQ",
129307
- "GT", "LE", "LT", "GE",
129308
- "ESCAPE", "BITAND", "BITOR", "LSHIFT",
129309
- "RSHIFT", "PLUS", "MINUS", "STAR",
129310
- "SLASH", "REM", "CONCAT", "COLLATE",
129311
- "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
131749
+ "INITIALLY", "INSTEAD", "NO", "KEY",
131750
+ "OF", "OFFSET", "PRAGMA", "RAISE",
131751
+ "RECURSIVE", "REPLACE", "RESTRICT", "ROW",
131752
+ "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
131753
+ "WITH", "REINDEX", "RENAME", "CTIME_KW",
131754
+ "ANY", "STRING", "JOIN_KW", "CONSTRAINT",
129312131755
"DEFAULT", "NULL", "PRIMARY", "UNIQUE",
129313131756
"CHECK", "REFERENCES", "AUTOINCR", "ON",
129314131757
"INSERT", "DELETE", "UPDATE", "SET",
129315131758
"DEFERRABLE", "FOREIGN", "DROP", "UNION",
129316131759
"ALL", "EXCEPT", "INTERSECT", "SELECT",
@@ -131086,26 +133529,27 @@
131086133529
yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
131087133530
}
131088133531
break;
131089133532
case 156: /* expr ::= VARIABLE */
131090133533
{
131091
- Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
131092
- if( t.n>=2 && t.z[0]=='#' && sqlite3Isdigit(t.z[1]) ){
133534
+ if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
133535
+ spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
133536
+ sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
133537
+ }else{
131093133538
/* When doing a nested parse, one can include terms in an expression
131094133539
** that look like this: #1 #2 ... These terms refer to registers
131095133540
** in the virtual machine. #N is the N-th register. */
133541
+ Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
133542
+ assert( t.n>=2 );
131096133543
spanSet(&yymsp[0].minor.yy342, &t, &t);
131097133544
if( pParse->nested==0 ){
131098133545
sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
131099133546
yymsp[0].minor.yy342.pExpr = 0;
131100133547
}else{
131101133548
yymsp[0].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
131102133549
if( yymsp[0].minor.yy342.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy342.pExpr->iTable);
131103133550
}
131104
- }else{
131105
- spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, t);
131106
- sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
131107133551
}
131108133552
}
131109133553
break;
131110133554
case 157: /* expr ::= expr COLLATE ID|STRING */
131111133555
{
@@ -131286,60 +133730,37 @@
131286133730
break;
131287133731
case 188: /* expr ::= LP select RP */
131288133732
{
131289133733
spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
131290133734
yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
131291
- if( yymsp[-2].minor.yy342.pExpr ){
131292
- yymsp[-2].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
131293
- ExprSetProperty(yymsp[-2].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131294
- sqlite3ExprSetHeightAndFlags(pParse, yymsp[-2].minor.yy342.pExpr);
131295
- }else{
131296
- sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131297
- }
133735
+ sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy342.pExpr, yymsp[-1].minor.yy159);
131298133736
}
131299133737
break;
131300133738
case 189: /* expr ::= expr in_op LP select RP */
131301133739
{
131302133740
yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
131303
- if( yymsp[-4].minor.yy342.pExpr ){
131304
- yymsp[-4].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
131305
- ExprSetProperty(yymsp[-4].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131306
- sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
131307
- }else{
131308
- sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131309
- }
133741
+ sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy342.pExpr, yymsp[-1].minor.yy159);
131310133742
exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
131311133743
yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
131312133744
}
131313133745
break;
131314133746
case 190: /* expr ::= expr in_op nm dbnm */
131315133747
{
131316133748
SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
133749
+ Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
131317133750
yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
131318
- if( yymsp[-3].minor.yy342.pExpr ){
131319
- yymsp[-3].minor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
131320
- ExprSetProperty(yymsp[-3].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131321
- sqlite3ExprSetHeightAndFlags(pParse, yymsp[-3].minor.yy342.pExpr);
131322
- }else{
131323
- sqlite3SrcListDelete(pParse->db, pSrc);
131324
- }
133751
+ sqlite3PExprAddSelect(pParse, yymsp[-3].minor.yy342.pExpr, pSelect);
131325133752
exprNot(pParse, yymsp[-2].minor.yy392, &yymsp[-3].minor.yy342);
131326133753
yymsp[-3].minor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
131327133754
}
131328133755
break;
131329133756
case 191: /* expr ::= EXISTS LP select RP */
131330133757
{
131331133758
Expr *p;
131332133759
spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
131333133760
p = yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
131334
- if( p ){
131335
- p->x.pSelect = yymsp[-1].minor.yy159;
131336
- ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
131337
- sqlite3ExprSetHeightAndFlags(pParse, p);
131338
- }else{
131339
- sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131340
- }
133761
+ sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy159);
131341133762
}
131342133763
break;
131343133764
case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
131344133765
{
131345133766
spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
@@ -132820,11 +135241,11 @@
132820135241
** will take responsibility for freeing the Table structure.
132821135242
*/
132822135243
sqlite3DeleteTable(db, pParse->pNewTable);
132823135244
}
132824135245
132825
- sqlite3WithDelete(db, pParse->pWithToFree);
135246
+ if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
132826135247
sqlite3DeleteTrigger(db, pParse->pNewTrigger);
132827135248
for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
132828135249
sqlite3DbFree(db, pParse->azVar);
132829135250
while( pParse->pAinc ){
132830135251
AutoincInfo *p = pParse->pAinc;
@@ -134030,10 +136451,11 @@
134030136451
u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
134031136452
} aFlagOp[] = {
134032136453
{ SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
134033136454
{ SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
134034136455
{ SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
136456
+ { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
134035136457
};
134036136458
unsigned int i;
134037136459
rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
134038136460
for(i=0; i<ArraySize(aFlagOp); i++){
134039136461
if( aFlagOp[i].op==op ){
@@ -135148,10 +137570,31 @@
135148137570
db->pRollbackArg = pArg;
135149137571
sqlite3_mutex_leave(db->mutex);
135150137572
return pRet;
135151137573
}
135152137574
137575
+#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
137576
+/*
137577
+** Register a callback to be invoked each time a row is updated,
137578
+** inserted or deleted using this database connection.
137579
+*/
137580
+SQLITE_API void *SQLITE_STDCALL sqlite3_preupdate_hook(
137581
+ sqlite3 *db, /* Attach the hook to this database */
137582
+ void(*xCallback)( /* Callback function */
137583
+ void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
137584
+ void *pArg /* First callback argument */
137585
+){
137586
+ void *pRet;
137587
+ sqlite3_mutex_enter(db->mutex);
137588
+ pRet = db->pPreUpdateArg;
137589
+ db->xPreUpdateCallback = xCallback;
137590
+ db->pPreUpdateArg = pArg;
137591
+ sqlite3_mutex_leave(db->mutex);
137592
+ return pRet;
137593
+}
137594
+#endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
137595
+
135153137596
#ifndef SQLITE_OMIT_WAL
135154137597
/*
135155137598
** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
135156137599
** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
135157137600
** is greater than sqlite3.pWalArg cast to an integer (the value configured by
@@ -160507,19 +162950,21 @@
160507162950
** lower('I', 'tr_tr') -> 'ı' (small dotless i)
160508162951
**
160509162952
** http://www.icu-project.org/userguide/posix.html#case_mappings
160510162953
*/
160511162954
static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
160512
- const UChar *zInput;
160513
- UChar *zOutput = 0;
160514
- int nInput;
160515
- int nOut;
162955
+ const UChar *zInput; /* Pointer to input string */
162956
+ UChar *zOutput = 0; /* Pointer to output buffer */
162957
+ int nInput; /* Size of utf-16 input string in bytes */
162958
+ int nOut; /* Size of output buffer in bytes */
160516162959
int cnt;
162960
+ int bToUpper; /* True for toupper(), false for tolower() */
160517162961
UErrorCode status;
160518162962
const char *zLocale = 0;
160519162963
160520162964
assert(nArg==1 || nArg==2);
162965
+ bToUpper = (sqlite3_user_data(p)!=0);
160521162966
if( nArg==2 ){
160522162967
zLocale = (const char *)sqlite3_value_text(apArg[1]);
160523162968
}
160524162969
160525162970
zInput = sqlite3_value_text16(apArg[0]);
@@ -160539,23 +162984,27 @@
160539162984
sqlite3_result_error_nomem(p);
160540162985
return;
160541162986
}
160542162987
zOutput = zNew;
160543162988
status = U_ZERO_ERROR;
160544
- if( sqlite3_user_data(p) ){
162989
+ if( bToUpper ){
160545162990
nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
160546162991
}else{
160547162992
nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
160548162993
}
160549
- if( !U_SUCCESS(status) ){
160550
- if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
160551
- icuFunctionError(p,
160552
- sqlite3_user_data(p) ? "u_strToUpper" : "u_strToLower", status);
160553
- return;
160554
- }
160555
- }
160556
- sqlite3_result_text16(p, zOutput, nOut, xFree);
162994
+
162995
+ if( U_SUCCESS(status) ){
162996
+ sqlite3_result_text16(p, zOutput, nOut, xFree);
162997
+ }else if( status==U_BUFFER_OVERFLOW_ERROR ){
162998
+ assert( cnt==0 );
162999
+ continue;
163000
+ }else{
163001
+ icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
163002
+ }
163003
+ return;
163004
+ }
163005
+ assert( 0 ); /* Unreachable */
160557163006
}
160558163007
160559163008
/*
160560163009
** Collation sequence destructor function. The pCtx argument points to
160561163010
** a UCollator structure previously allocated using ucol_open().
@@ -161368,10 +163817,42 @@
161368163817
const char *zTarget,
161369163818
const char *zRbu,
161370163819
const char *zState
161371163820
);
161372163821
163822
+/*
163823
+** Open an RBU handle to perform an RBU vacuum on database file zTarget.
163824
+** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
163825
+** that it can be suspended and resumed like an RBU update.
163826
+**
163827
+** The second argument to this function, which may not be NULL, identifies
163828
+** a database in which to store the state of the RBU vacuum operation if
163829
+** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
163830
+** an RBU vacuum operation, the state database should either not exist or
163831
+** be empty (contain no tables). If an RBU vacuum is suspended by calling
163832
+** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
163833
+** returned SQLITE_DONE, the vacuum state is stored in the state database.
163834
+** The vacuum can be resumed by calling this function to open a new RBU
163835
+** handle specifying the same target and state databases.
163836
+**
163837
+** This function does not delete the state database after an RBU vacuum
163838
+** is completed, even if it created it. However, if the call to
163839
+** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
163840
+** of the state tables within the state database are zeroed. This way,
163841
+** the next call to sqlite3rbu_vacuum() opens a handle that starts a
163842
+** new RBU vacuum operation.
163843
+**
163844
+** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
163845
+** describing the sqlite3rbu_create_vfs() API function below for
163846
+** a description of the complications associated with using RBU with
163847
+** zipvfs databases.
163848
+*/
163849
+SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
163850
+ const char *zTarget,
163851
+ const char *zState
163852
+);
163853
+
161373163854
/*
161374163855
** Internally, each RBU connection uses a separate SQLite database
161375163856
** connection to access the target and rbu update databases. This
161376163857
** API allows the application direct access to these database handles.
161377163858
**
@@ -161646,10 +164127,11 @@
161646164127
typedef struct rbu_file rbu_file;
161647164128
typedef struct RbuUpdateStmt RbuUpdateStmt;
161648164129
161649164130
#if !defined(SQLITE_AMALGAMATION)
161650164131
typedef unsigned int u32;
164132
+typedef unsigned short u16;
161651164133
typedef unsigned char u8;
161652164134
typedef sqlite3_int64 i64;
161653164135
#endif
161654164136
161655164137
/*
@@ -161658,10 +164140,12 @@
161658164140
** format.
161659164141
*/
161660164142
#define WAL_LOCK_WRITE 0
161661164143
#define WAL_LOCK_CKPT 1
161662164144
#define WAL_LOCK_READ0 3
164145
+
164146
+#define SQLITE_FCNTL_RBUCNT 5149216
161663164147
161664164148
/*
161665164149
** A structure to store values read from the rbu_state table in memory.
161666164150
*/
161667164151
struct RbuState {
@@ -161837,10 +164321,14 @@
161837164321
int nFrameAlloc; /* Allocated size of aFrame[] array */
161838164322
RbuFrame *aFrame;
161839164323
int pgsz;
161840164324
u8 *aBuf;
161841164325
i64 iWalCksum;
164326
+
164327
+ /* Used in RBU vacuum mode only */
164328
+ int nRbu; /* Number of RBU VFS in the stack */
164329
+ rbu_file *pRbuFd; /* Fd for main db of dbRbu */
161842164330
};
161843164331
161844164332
/*
161845164333
** An rbu VFS is implemented using an instance of this structure.
161846164334
*/
@@ -161862,10 +164350,11 @@
161862164350
sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
161863164351
161864164352
int openFlags; /* Flags this file was opened with */
161865164353
u32 iCookie; /* Cookie value for main db files */
161866164354
u8 iWriteVer; /* "write-version" value for main db files */
164355
+ u8 bNolock; /* True to fail EXCLUSIVE locks */
161867164356
161868164357
int nShm; /* Number of entries in apShm[] array */
161869164358
char **apShm; /* Array of mmap'd *-shm regions */
161870164359
char *zDel; /* Delete this when closing file */
161871164360
@@ -161872,10 +164361,15 @@
161872164361
const char *zWal; /* Wal filename for this main db file */
161873164362
rbu_file *pWalFd; /* Wal file descriptor for this main db */
161874164363
rbu_file *pMainNext; /* Next MAIN_DB file */
161875164364
};
161876164365
164366
+/*
164367
+** True for an RBU vacuum handle, or false otherwise.
164368
+*/
164369
+#define rbuIsVacuum(p) ((p)->zTarget==0)
164370
+
161877164371
161878164372
/*************************************************************************
161879164373
** The following three functions, found below:
161880164374
**
161881164375
** rbuDeltaGetInt()
@@ -162320,12 +164814,15 @@
162320164814
}
162321164815
162322164816
162323164817
/*
162324164818
** The implementation of the rbu_target_name() SQL function. This function
162325
-** accepts one argument - the name of a table in the RBU database. If the
162326
-** table name matches the pattern:
164819
+** accepts one or two arguments. The first argument is the name of a table -
164820
+** the name of a table in the RBU database. The second, if it is present, is 1
164821
+** for a view or 0 for a table.
164822
+**
164823
+** For a non-vacuum RBU handle, if the table name matches the pattern:
162327164824
**
162328164825
** data[0-9]_<name>
162329164826
**
162330164827
** where <name> is any sequence of 1 or more characters, <name> is returned.
162331164828
** Otherwise, if the only argument does not match the above pattern, an SQL
@@ -162332,25 +164829,37 @@
162332164829
** NULL is returned.
162333164830
**
162334164831
** "data_t1" -> "t1"
162335164832
** "data0123_t2" -> "t2"
162336164833
** "dataAB_t3" -> NULL
164834
+**
164835
+** For an rbu vacuum handle, a copy of the first argument is returned if
164836
+** the second argument is either missing or 0 (not a view).
162337164837
*/
162338164838
static void rbuTargetNameFunc(
162339
- sqlite3_context *context,
164839
+ sqlite3_context *pCtx,
162340164840
int argc,
162341164841
sqlite3_value **argv
162342164842
){
164843
+ sqlite3rbu *p = sqlite3_user_data(pCtx);
162343164844
const char *zIn;
162344
- assert( argc==1 );
164845
+ assert( argc==1 || argc==2 );
162345164846
162346164847
zIn = (const char*)sqlite3_value_text(argv[0]);
162347
- if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
162348
- int i;
162349
- for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
162350
- if( zIn[i]=='_' && zIn[i+1] ){
162351
- sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
164848
+ if( zIn ){
164849
+ if( rbuIsVacuum(p) ){
164850
+ if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
164851
+ sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
164852
+ }
164853
+ }else{
164854
+ if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
164855
+ int i;
164856
+ for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
164857
+ if( zIn[i]=='_' && zIn[i+1] ){
164858
+ sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
164859
+ }
164860
+ }
162352164861
}
162353164862
}
162354164863
}
162355164864
162356164865
/*
@@ -162364,11 +164873,12 @@
162364164873
static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
162365164874
int rc;
162366164875
memset(pIter, 0, sizeof(RbuObjIter));
162367164876
162368164877
rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
162369
- "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
164878
+ "SELECT rbu_target_name(name, type='view') AS target, name "
164879
+ "FROM sqlite_master "
162370164880
"WHERE type IN ('table', 'view') AND target IS NOT NULL "
162371164881
"ORDER BY name"
162372164882
);
162373164883
162374164884
if( rc==SQLITE_OK ){
@@ -162740,10 +165250,11 @@
162740165250
}
162741165251
sqlite3_finalize(pStmt);
162742165252
pStmt = 0;
162743165253
162744165254
if( p->rc==SQLITE_OK
165255
+ && rbuIsVacuum(p)==0
162745165256
&& bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
162746165257
){
162747165258
p->rc = SQLITE_ERROR;
162748165259
p->zErrmsg = sqlite3_mprintf(
162749165260
"table %q %s rbu_rowid column", pIter->zDataTbl,
@@ -162879,10 +165390,12 @@
162879165390
if( pIter->eType==RBU_PK_IPK ){
162880165391
int i;
162881165392
for(i=0; pIter->abTblPk[i]==0; i++);
162882165393
assert( i<pIter->nTblCol );
162883165394
zCol = pIter->azTblCol[i];
165395
+ }else if( rbuIsVacuum(p) ){
165396
+ zCol = "_rowid_";
162884165397
}else{
162885165398
zCol = "rbu_rowid";
162886165399
}
162887165400
zType = "INTEGER";
162888165401
}else{
@@ -163419,20 +165932,29 @@
163419165932
sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
163420165933
);
163421165934
}
163422165935
163423165936
/* And to delete index entries */
163424
- if( p->rc==SQLITE_OK ){
165937
+ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
163425165938
p->rc = prepareFreeAndCollectError(
163426165939
p->dbMain, &pIter->pDelete, &p->zErrmsg,
163427165940
sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
163428165941
);
163429165942
}
163430165943
163431165944
/* Create the SELECT statement to read keys in sorted order */
163432165945
if( p->rc==SQLITE_OK ){
163433165946
char *zSql;
165947
+ if( rbuIsVacuum(p) ){
165948
+ zSql = sqlite3_mprintf(
165949
+ "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
165950
+ zCollist,
165951
+ pIter->zDataTbl,
165952
+ zCollist, zLimit
165953
+ );
165954
+ }else
165955
+
163434165956
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
163435165957
zSql = sqlite3_mprintf(
163436165958
"SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
163437165959
zCollist, p->zStateDb, pIter->zDataTbl,
163438165960
zCollist, zLimit
@@ -163455,11 +165977,13 @@
163455165977
sqlite3_free(zImposterCols);
163456165978
sqlite3_free(zImposterPK);
163457165979
sqlite3_free(zWhere);
163458165980
sqlite3_free(zBind);
163459165981
}else{
163460
- int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
165982
+ int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
165983
+ ||(pIter->eType==RBU_PK_NONE)
165984
+ ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
163461165985
const char *zTbl = pIter->zTbl; /* Table this step applies to */
163462165986
const char *zWrite; /* Imposter table name */
163463165987
163464165988
char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
163465165989
char *zWhere = rbuObjIterGetWhere(p, pIter);
@@ -163482,20 +166006,22 @@
163482166006
zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
163483166007
)
163484166008
);
163485166009
}
163486166010
163487
- /* Create the DELETE statement to write to the target PK b-tree */
163488
- if( p->rc==SQLITE_OK ){
166011
+ /* Create the DELETE statement to write to the target PK b-tree.
166012
+ ** Because it only performs INSERT operations, this is not required for
166013
+ ** an rbu vacuum handle. */
166014
+ if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
163489166015
p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
163490166016
sqlite3_mprintf(
163491166017
"DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
163492166018
)
163493166019
);
163494166020
}
163495166021
163496
- if( pIter->abIndexed ){
166022
+ if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
163497166023
const char *zRbuRowid = "";
163498166024
if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
163499166025
zRbuRowid = ", rbu_rowid";
163500166026
}
163501166027
@@ -163541,14 +166067,20 @@
163541166067
rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
163542166068
}
163543166069
163544166070
/* Create the SELECT statement to read keys from data_xxx */
163545166071
if( p->rc==SQLITE_OK ){
166072
+ const char *zRbuRowid = "";
166073
+ if( bRbuRowid ){
166074
+ zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
166075
+ }
163546166076
p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
163547166077
sqlite3_mprintf(
163548
- "SELECT %s, rbu_control%s FROM '%q'%s",
163549
- zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
166078
+ "SELECT %s,%s rbu_control%s FROM '%q'%s",
166079
+ zCollist,
166080
+ (rbuIsVacuum(p) ? "0 AS " : ""),
166081
+ zRbuRowid,
163550166082
pIter->zDataTbl, zLimit
163551166083
)
163552166084
);
163553166085
}
163554166086
@@ -163639,44 +166171,231 @@
163639166171
}
163640166172
163641166173
return p->rc;
163642166174
}
163643166175
163644
-static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
166176
+static sqlite3 *rbuOpenDbhandle(
166177
+ sqlite3rbu *p,
166178
+ const char *zName,
166179
+ int bUseVfs
166180
+){
163645166181
sqlite3 *db = 0;
163646166182
if( p->rc==SQLITE_OK ){
163647166183
const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
163648
- p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
166184
+ p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
163649166185
if( p->rc ){
163650166186
p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163651166187
sqlite3_close(db);
163652166188
db = 0;
163653166189
}
163654166190
}
163655166191
return db;
163656166192
}
166193
+
166194
+/*
166195
+** Free an RbuState object allocated by rbuLoadState().
166196
+*/
166197
+static void rbuFreeState(RbuState *p){
166198
+ if( p ){
166199
+ sqlite3_free(p->zTbl);
166200
+ sqlite3_free(p->zIdx);
166201
+ sqlite3_free(p);
166202
+ }
166203
+}
166204
+
166205
+/*
166206
+** Allocate an RbuState object and load the contents of the rbu_state
166207
+** table into it. Return a pointer to the new object. It is the
166208
+** responsibility of the caller to eventually free the object using
166209
+** sqlite3_free().
166210
+**
166211
+** If an error occurs, leave an error code and message in the rbu handle
166212
+** and return NULL.
166213
+*/
166214
+static RbuState *rbuLoadState(sqlite3rbu *p){
166215
+ RbuState *pRet = 0;
166216
+ sqlite3_stmt *pStmt = 0;
166217
+ int rc;
166218
+ int rc2;
166219
+
166220
+ pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
166221
+ if( pRet==0 ) return 0;
166222
+
166223
+ rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
166224
+ sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
166225
+ );
166226
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166227
+ switch( sqlite3_column_int(pStmt, 0) ){
166228
+ case RBU_STATE_STAGE:
166229
+ pRet->eStage = sqlite3_column_int(pStmt, 1);
166230
+ if( pRet->eStage!=RBU_STAGE_OAL
166231
+ && pRet->eStage!=RBU_STAGE_MOVE
166232
+ && pRet->eStage!=RBU_STAGE_CKPT
166233
+ ){
166234
+ p->rc = SQLITE_CORRUPT;
166235
+ }
166236
+ break;
166237
+
166238
+ case RBU_STATE_TBL:
166239
+ pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166240
+ break;
166241
+
166242
+ case RBU_STATE_IDX:
166243
+ pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166244
+ break;
166245
+
166246
+ case RBU_STATE_ROW:
166247
+ pRet->nRow = sqlite3_column_int(pStmt, 1);
166248
+ break;
166249
+
166250
+ case RBU_STATE_PROGRESS:
166251
+ pRet->nProgress = sqlite3_column_int64(pStmt, 1);
166252
+ break;
166253
+
166254
+ case RBU_STATE_CKPT:
166255
+ pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
166256
+ break;
166257
+
166258
+ case RBU_STATE_COOKIE:
166259
+ pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
166260
+ break;
166261
+
166262
+ case RBU_STATE_OALSZ:
166263
+ pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
166264
+ break;
166265
+
166266
+ case RBU_STATE_PHASEONESTEP:
166267
+ pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
166268
+ break;
166269
+
166270
+ default:
166271
+ rc = SQLITE_CORRUPT;
166272
+ break;
166273
+ }
166274
+ }
166275
+ rc2 = sqlite3_finalize(pStmt);
166276
+ if( rc==SQLITE_OK ) rc = rc2;
166277
+
166278
+ p->rc = rc;
166279
+ return pRet;
166280
+}
166281
+
163657166282
163658166283
/*
163659166284
** Open the database handle and attach the RBU database as "rbu". If an
163660166285
** error occurs, leave an error code and message in the RBU handle.
163661166286
*/
163662166287
static void rbuOpenDatabase(sqlite3rbu *p){
163663166288
assert( p->rc==SQLITE_OK );
163664166289
assert( p->dbMain==0 && p->dbRbu==0 );
166290
+ assert( rbuIsVacuum(p) || p->zTarget!=0 );
163665166291
163666
- p->eStage = 0;
163667
- p->dbMain = rbuOpenDbhandle(p, p->zTarget);
163668
- p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
166292
+ /* Open the RBU database */
166293
+ p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
166294
+
166295
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166296
+ sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166297
+ }
163669166298
163670166299
/* If using separate RBU and state databases, attach the state database to
163671166300
** the RBU db handle now. */
163672166301
if( p->zState ){
163673166302
rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
163674166303
memcpy(p->zStateDb, "stat", 4);
163675166304
}else{
163676166305
memcpy(p->zStateDb, "main", 4);
163677166306
}
166307
+
166308
+#if 0
166309
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166310
+ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
166311
+ }
166312
+#endif
166313
+
166314
+ /* If it has not already been created, create the rbu_state table */
166315
+ rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
166316
+
166317
+#if 0
166318
+ if( rbuIsVacuum(p) ){
166319
+ if( p->rc==SQLITE_OK ){
166320
+ int rc2;
166321
+ int bOk = 0;
166322
+ sqlite3_stmt *pCnt = 0;
166323
+ p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
166324
+ "SELECT count(*) FROM stat.sqlite_master"
166325
+ );
166326
+ if( p->rc==SQLITE_OK
166327
+ && sqlite3_step(pCnt)==SQLITE_ROW
166328
+ && 1==sqlite3_column_int(pCnt, 0)
166329
+ ){
166330
+ bOk = 1;
166331
+ }
166332
+ rc2 = sqlite3_finalize(pCnt);
166333
+ if( p->rc==SQLITE_OK ) p->rc = rc2;
166334
+
166335
+ if( p->rc==SQLITE_OK && bOk==0 ){
166336
+ p->rc = SQLITE_ERROR;
166337
+ p->zErrmsg = sqlite3_mprintf("invalid state database");
166338
+ }
166339
+
166340
+ if( p->rc==SQLITE_OK ){
166341
+ p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
166342
+ }
166343
+ }
166344
+ }
166345
+#endif
166346
+
166347
+ if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166348
+ int bOpen = 0;
166349
+ int rc;
166350
+ p->nRbu = 0;
166351
+ p->pRbuFd = 0;
166352
+ rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166353
+ if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
166354
+ if( p->eStage>=RBU_STAGE_MOVE ){
166355
+ bOpen = 1;
166356
+ }else{
166357
+ RbuState *pState = rbuLoadState(p);
166358
+ if( pState ){
166359
+ bOpen = (pState->eStage>RBU_STAGE_MOVE);
166360
+ rbuFreeState(pState);
166361
+ }
166362
+ }
166363
+ if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
166364
+ }
166365
+
166366
+ p->eStage = 0;
166367
+ if( p->rc==SQLITE_OK && p->dbMain==0 ){
166368
+ if( !rbuIsVacuum(p) ){
166369
+ p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
166370
+ }else if( p->pRbuFd->pWalFd ){
166371
+ p->rc = SQLITE_ERROR;
166372
+ p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
166373
+ }else{
166374
+ char *zTarget;
166375
+ char *zExtra = 0;
166376
+ if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
166377
+ zExtra = &p->zRbu[5];
166378
+ while( *zExtra ){
166379
+ if( *zExtra++=='?' ) break;
166380
+ }
166381
+ if( *zExtra=='\0' ) zExtra = 0;
166382
+ }
166383
+
166384
+ zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
166385
+ sqlite3_db_filename(p->dbRbu, "main"),
166386
+ (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
166387
+ );
166388
+
166389
+ if( zTarget==0 ){
166390
+ p->rc = SQLITE_NOMEM;
166391
+ return;
166392
+ }
166393
+ p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
166394
+ sqlite3_free(zTarget);
166395
+ }
166396
+ }
163678166397
163679166398
if( p->rc==SQLITE_OK ){
163680166399
p->rc = sqlite3_create_function(p->dbMain,
163681166400
"rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
163682166401
);
@@ -163688,11 +166407,11 @@
163688166407
);
163689166408
}
163690166409
163691166410
if( p->rc==SQLITE_OK ){
163692166411
p->rc = sqlite3_create_function(p->dbRbu,
163693
- "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
166412
+ "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
163694166413
);
163695166414
}
163696166415
163697166416
if( p->rc==SQLITE_OK ){
163698166417
p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
@@ -163947,13 +166666,19 @@
163947166666
** If an error occurs, leave an error code and error message in the rbu
163948166667
** handle.
163949166668
*/
163950166669
static void rbuMoveOalFile(sqlite3rbu *p){
163951166670
const char *zBase = sqlite3_db_filename(p->dbMain, "main");
166671
+ const char *zMove = zBase;
166672
+ char *zOal;
166673
+ char *zWal;
163952166674
163953
- char *zWal = sqlite3_mprintf("%s-wal", zBase);
163954
- char *zOal = sqlite3_mprintf("%s-oal", zBase);
166675
+ if( rbuIsVacuum(p) ){
166676
+ zMove = sqlite3_db_filename(p->dbRbu, "main");
166677
+ }
166678
+ zOal = sqlite3_mprintf("%s-oal", zMove);
166679
+ zWal = sqlite3_mprintf("%s-wal", zMove);
163955166680
163956166681
assert( p->eStage==RBU_STAGE_MOVE );
163957166682
assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
163958166683
if( zWal==0 || zOal==0 ){
163959166684
p->rc = SQLITE_NOMEM;
@@ -163970,12 +166695,12 @@
163970166695
rbuFileSuffix3(zBase, zWal);
163971166696
rbuFileSuffix3(zBase, zOal);
163972166697
163973166698
/* Re-open the databases. */
163974166699
rbuObjIterFinalize(&p->objiter);
163975
- sqlite3_close(p->dbMain);
163976166700
sqlite3_close(p->dbRbu);
166701
+ sqlite3_close(p->dbMain);
163977166702
p->dbMain = 0;
163978166703
p->dbRbu = 0;
163979166704
163980166705
#if defined(_WIN32_WCE)
163981166706
{
@@ -164133,23 +166858,28 @@
164133166858
164134166859
pVal = sqlite3_column_value(pIter->pSelect, i);
164135166860
p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
164136166861
if( p->rc ) return;
164137166862
}
164138
- if( pIter->zIdx==0
164139
- && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
164140
- ){
164141
- /* For a virtual table, or a table with no primary key, the
164142
- ** SELECT statement is:
164143
- **
164144
- ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
164145
- **
164146
- ** Hence column_value(pIter->nCol+1).
164147
- */
164148
- assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
164149
- pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
164150
- p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
166863
+ if( pIter->zIdx==0 ){
166864
+ if( pIter->eType==RBU_PK_VTAB
166865
+ || pIter->eType==RBU_PK_NONE
166866
+ || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
166867
+ ){
166868
+ /* For a virtual table, or a table with no primary key, the
166869
+ ** SELECT statement is:
166870
+ **
166871
+ ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
166872
+ **
166873
+ ** Hence column_value(pIter->nCol+1).
166874
+ */
166875
+ assertColumnName(pIter->pSelect, pIter->nCol+1,
166876
+ rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
166877
+ );
166878
+ pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
166879
+ p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
166880
+ }
164151166881
}
164152166882
if( p->rc==SQLITE_OK ){
164153166883
sqlite3_step(pWriter);
164154166884
p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
164155166885
}
@@ -164224,17 +166954,22 @@
164224166954
return p->rc;
164225166955
}
164226166956
164227166957
/*
164228166958
** Increment the schema cookie of the main database opened by p->dbMain.
166959
+**
166960
+** Or, if this is an RBU vacuum, set the schema cookie of the main db
166961
+** opened by p->dbMain to one more than the schema cookie of the main
166962
+** db opened by p->dbRbu.
164229166963
*/
164230166964
static void rbuIncrSchemaCookie(sqlite3rbu *p){
164231166965
if( p->rc==SQLITE_OK ){
166966
+ sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
164232166967
int iCookie = 1000000;
164233166968
sqlite3_stmt *pStmt;
164234166969
164235
- p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
166970
+ p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
164236166971
"PRAGMA schema_version"
164237166972
);
164238166973
if( p->rc==SQLITE_OK ){
164239166974
/* Coverage: it may be that this sqlite3_step() cannot fail. There
164240166975
** is already a transaction open, so the prepared statement cannot
@@ -164258,10 +166993,11 @@
164258166993
** are determined by inspecting the rbu handle passed as the first argument.
164259166994
*/
164260166995
static void rbuSaveState(sqlite3rbu *p, int eStage){
164261166996
if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
164262166997
sqlite3_stmt *pInsert = 0;
166998
+ rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
164263166999
int rc;
164264167000
164265167001
assert( p->zErrmsg==0 );
164266167002
rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
164267167003
sqlite3_mprintf(
@@ -164280,11 +167016,11 @@
164280167016
RBU_STATE_TBL, p->objiter.zTbl,
164281167017
RBU_STATE_IDX, p->objiter.zIdx,
164282167018
RBU_STATE_ROW, p->nStep,
164283167019
RBU_STATE_PROGRESS, p->nProgress,
164284167020
RBU_STATE_CKPT, p->iWalCksum,
164285
- RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
167021
+ RBU_STATE_COOKIE, (i64)pFd->iCookie,
164286167022
RBU_STATE_OALSZ, p->iOalSz,
164287167023
RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
164288167024
)
164289167025
);
164290167026
assert( pInsert==0 || rc==SQLITE_OK );
@@ -164295,26 +167031,121 @@
164295167031
}
164296167032
if( rc!=SQLITE_OK ) p->rc = rc;
164297167033
}
164298167034
}
164299167035
167036
+
167037
+/*
167038
+** The second argument passed to this function is the name of a PRAGMA
167039
+** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
167040
+** This function executes the following on sqlite3rbu.dbRbu:
167041
+**
167042
+** "PRAGMA main.$zPragma"
167043
+**
167044
+** where $zPragma is the string passed as the second argument, then
167045
+** on sqlite3rbu.dbMain:
167046
+**
167047
+** "PRAGMA main.$zPragma = $val"
167048
+**
167049
+** where $val is the value returned by the first PRAGMA invocation.
167050
+**
167051
+** In short, it copies the value of the specified PRAGMA setting from
167052
+** dbRbu to dbMain.
167053
+*/
167054
+static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
167055
+ if( p->rc==SQLITE_OK ){
167056
+ sqlite3_stmt *pPragma = 0;
167057
+ p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
167058
+ sqlite3_mprintf("PRAGMA main.%s", zPragma)
167059
+ );
167060
+ if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
167061
+ p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
167062
+ zPragma, sqlite3_column_int(pPragma, 0)
167063
+ );
167064
+ }
167065
+ rbuFinalize(p, pPragma);
167066
+ }
167067
+}
167068
+
167069
+/*
167070
+** The RBU handle passed as the only argument has just been opened and
167071
+** the state database is empty. If this RBU handle was opened for an
167072
+** RBU vacuum operation, create the schema in the target db.
167073
+*/
167074
+static void rbuCreateTargetSchema(sqlite3rbu *p){
167075
+ sqlite3_stmt *pSql = 0;
167076
+ sqlite3_stmt *pInsert = 0;
167077
+
167078
+ assert( rbuIsVacuum(p) );
167079
+ p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
167080
+ if( p->rc==SQLITE_OK ){
167081
+ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167082
+ "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
167083
+ " AND name!='sqlite_sequence' "
167084
+ " ORDER BY type DESC"
167085
+ );
167086
+ }
167087
+
167088
+ while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167089
+ const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
167090
+ p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
167091
+ }
167092
+ rbuFinalize(p, pSql);
167093
+ if( p->rc!=SQLITE_OK ) return;
167094
+
167095
+ if( p->rc==SQLITE_OK ){
167096
+ p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167097
+ "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
167098
+ );
167099
+ }
167100
+
167101
+ if( p->rc==SQLITE_OK ){
167102
+ p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
167103
+ "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
167104
+ );
167105
+ }
167106
+
167107
+ while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167108
+ int i;
167109
+ for(i=0; i<5; i++){
167110
+ sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
167111
+ }
167112
+ sqlite3_step(pInsert);
167113
+ p->rc = sqlite3_reset(pInsert);
167114
+ }
167115
+ if( p->rc==SQLITE_OK ){
167116
+ p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
167117
+ }
167118
+
167119
+ rbuFinalize(p, pSql);
167120
+ rbuFinalize(p, pInsert);
167121
+}
164300167122
164301167123
/*
164302167124
** Step the RBU object.
164303167125
*/
164304167126
SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
164305167127
if( p ){
164306167128
switch( p->eStage ){
164307167129
case RBU_STAGE_OAL: {
164308167130
RbuObjIter *pIter = &p->objiter;
167131
+
167132
+ /* If this is an RBU vacuum operation and the state table was empty
167133
+ ** when this handle was opened, create the target database schema. */
167134
+ if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
167135
+ rbuCreateTargetSchema(p);
167136
+ rbuCopyPragma(p, "user_version");
167137
+ rbuCopyPragma(p, "application_id");
167138
+ }
167139
+
164309167140
while( p->rc==SQLITE_OK && pIter->zTbl ){
164310167141
164311167142
if( pIter->bCleanup ){
164312167143
/* Clean up the rbu_tmp_xxx table for the previous table. It
164313167144
** cannot be dropped as there are currently active SQL statements.
164314167145
** But the contents can be deleted. */
164315
- if( pIter->abIndexed ){
167146
+ if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
164316167147
rbuMPrintfExec(p, p->dbRbu,
164317167148
"DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
164318167149
);
164319167150
}
164320167151
}else{
@@ -164397,98 +167228,10 @@
164397167228
}else{
164398167229
return SQLITE_NOMEM;
164399167230
}
164400167231
}
164401167232
164402
-/*
164403
-** Free an RbuState object allocated by rbuLoadState().
164404
-*/
164405
-static void rbuFreeState(RbuState *p){
164406
- if( p ){
164407
- sqlite3_free(p->zTbl);
164408
- sqlite3_free(p->zIdx);
164409
- sqlite3_free(p);
164410
- }
164411
-}
164412
-
164413
-/*
164414
-** Allocate an RbuState object and load the contents of the rbu_state
164415
-** table into it. Return a pointer to the new object. It is the
164416
-** responsibility of the caller to eventually free the object using
164417
-** sqlite3_free().
164418
-**
164419
-** If an error occurs, leave an error code and message in the rbu handle
164420
-** and return NULL.
164421
-*/
164422
-static RbuState *rbuLoadState(sqlite3rbu *p){
164423
- RbuState *pRet = 0;
164424
- sqlite3_stmt *pStmt = 0;
164425
- int rc;
164426
- int rc2;
164427
-
164428
- pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
164429
- if( pRet==0 ) return 0;
164430
-
164431
- rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
164432
- sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
164433
- );
164434
- while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
164435
- switch( sqlite3_column_int(pStmt, 0) ){
164436
- case RBU_STATE_STAGE:
164437
- pRet->eStage = sqlite3_column_int(pStmt, 1);
164438
- if( pRet->eStage!=RBU_STAGE_OAL
164439
- && pRet->eStage!=RBU_STAGE_MOVE
164440
- && pRet->eStage!=RBU_STAGE_CKPT
164441
- ){
164442
- p->rc = SQLITE_CORRUPT;
164443
- }
164444
- break;
164445
-
164446
- case RBU_STATE_TBL:
164447
- pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
164448
- break;
164449
-
164450
- case RBU_STATE_IDX:
164451
- pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
164452
- break;
164453
-
164454
- case RBU_STATE_ROW:
164455
- pRet->nRow = sqlite3_column_int(pStmt, 1);
164456
- break;
164457
-
164458
- case RBU_STATE_PROGRESS:
164459
- pRet->nProgress = sqlite3_column_int64(pStmt, 1);
164460
- break;
164461
-
164462
- case RBU_STATE_CKPT:
164463
- pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
164464
- break;
164465
-
164466
- case RBU_STATE_COOKIE:
164467
- pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
164468
- break;
164469
-
164470
- case RBU_STATE_OALSZ:
164471
- pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
164472
- break;
164473
-
164474
- case RBU_STATE_PHASEONESTEP:
164475
- pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
164476
- break;
164477
-
164478
- default:
164479
- rc = SQLITE_CORRUPT;
164480
- break;
164481
- }
164482
- }
164483
- rc2 = sqlite3_finalize(pStmt);
164484
- if( rc==SQLITE_OK ) rc = rc2;
164485
-
164486
- p->rc = rc;
164487
- return pRet;
164488
-}
164489
-
164490167233
/*
164491167234
** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
164492167235
** otherwise. Either or both argument may be NULL. Two NULL values are
164493167236
** considered equal, and NULL is considered distinct from all other values.
164494167237
*/
@@ -164674,20 +167417,18 @@
164674167417
}
164675167418
}
164676167419
}
164677167420
}
164678167421
164679
-/*
164680
-** Open and return a new RBU handle.
164681
-*/
164682
-SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
167422
+
167423
+static sqlite3rbu *openRbuHandle(
164683167424
const char *zTarget,
164684167425
const char *zRbu,
164685167426
const char *zState
164686167427
){
164687167428
sqlite3rbu *p;
164688
- size_t nTarget = strlen(zTarget);
167429
+ size_t nTarget = zTarget ? strlen(zTarget) : 0;
164689167430
size_t nRbu = strlen(zRbu);
164690167431
size_t nState = zState ? strlen(zState) : 0;
164691167432
size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
164692167433
164693167434
p = (sqlite3rbu*)sqlite3_malloc64(nByte);
@@ -164696,26 +167437,28 @@
164696167437
164697167438
/* Create the custom VFS. */
164698167439
memset(p, 0, sizeof(sqlite3rbu));
164699167440
rbuCreateVfs(p);
164700167441
164701
- /* Open the target database */
167442
+ /* Open the target, RBU and state databases */
164702167443
if( p->rc==SQLITE_OK ){
164703
- p->zTarget = (char*)&p[1];
164704
- memcpy(p->zTarget, zTarget, nTarget+1);
164705
- p->zRbu = &p->zTarget[nTarget+1];
167444
+ char *pCsr = (char*)&p[1];
167445
+ if( zTarget ){
167446
+ p->zTarget = pCsr;
167447
+ memcpy(p->zTarget, zTarget, nTarget+1);
167448
+ pCsr += nTarget+1;
167449
+ }
167450
+ p->zRbu = pCsr;
164706167451
memcpy(p->zRbu, zRbu, nRbu+1);
167452
+ pCsr += nRbu+1;
164707167453
if( zState ){
164708
- p->zState = &p->zRbu[nRbu+1];
167454
+ p->zState = pCsr;
164709167455
memcpy(p->zState, zState, nState+1);
164710167456
}
164711167457
rbuOpenDatabase(p);
164712167458
}
164713167459
164714
- /* If it has not already been created, create the rbu_state table */
164715
- rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
164716
-
164717167460
if( p->rc==SQLITE_OK ){
164718167461
pState = rbuLoadState(p);
164719167462
assert( pState || p->rc!=SQLITE_OK );
164720167463
if( p->rc==SQLITE_OK ){
164721167464
@@ -164741,31 +167484,43 @@
164741167484
p->eStage = RBU_STAGE_CKPT;
164742167485
p->nStep = 0;
164743167486
}
164744167487
}
164745167488
164746
- if( p->rc==SQLITE_OK
167489
+ if( p->rc==SQLITE_OK
164747167490
&& (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
164748
- && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
164749
- ){
164750
- /* At this point (pTargetFd->iCookie) contains the value of the
164751
- ** change-counter cookie (the thing that gets incremented when a
164752
- ** transaction is committed in rollback mode) currently stored on
164753
- ** page 1 of the database file. */
164754
- p->rc = SQLITE_BUSY;
164755
- p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
167491
+ && pState->eStage!=0
167492
+ ){
167493
+ rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167494
+ if( pFd->iCookie!=pState->iCookie ){
167495
+ /* At this point (pTargetFd->iCookie) contains the value of the
167496
+ ** change-counter cookie (the thing that gets incremented when a
167497
+ ** transaction is committed in rollback mode) currently stored on
167498
+ ** page 1 of the database file. */
167499
+ p->rc = SQLITE_BUSY;
167500
+ p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
167501
+ (rbuIsVacuum(p) ? "vacuum" : "update")
167502
+ );
167503
+ }
164756167504
}
164757167505
164758167506
if( p->rc==SQLITE_OK ){
164759167507
if( p->eStage==RBU_STAGE_OAL ){
164760167508
sqlite3 *db = p->dbMain;
167509
+
167510
+ if( pState->eStage==0 && rbuIsVacuum(p) ){
167511
+ rbuCopyPragma(p, "page_size");
167512
+ rbuCopyPragma(p, "auto_vacuum");
167513
+ }
164761167514
164762167515
/* Open transactions both databases. The *-oal file is opened or
164763167516
** created at this point. */
164764
- p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
167517
+ if( p->rc==SQLITE_OK ){
167518
+ p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
167519
+ }
164765167520
if( p->rc==SQLITE_OK ){
164766
- p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
167521
+ p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
164767167522
}
164768167523
164769167524
/* Check if the main database is a zipvfs db. If it is, set the upper
164770167525
** level pager to use "journal_mode=off". This prevents it from
164771167526
** generating a large journal using a temp file. */
@@ -164806,10 +167561,32 @@
164806167561
}
164807167562
164808167563
return p;
164809167564
}
164810167565
167566
+/*
167567
+** Open and return a new RBU handle.
167568
+*/
167569
+SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
167570
+ const char *zTarget,
167571
+ const char *zRbu,
167572
+ const char *zState
167573
+){
167574
+ /* TODO: Check that zTarget and zRbu are non-NULL */
167575
+ return openRbuHandle(zTarget, zRbu, zState);
167576
+}
167577
+
167578
+/*
167579
+** Open a handle to begin or resume an RBU VACUUM operation.
167580
+*/
167581
+SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
167582
+ const char *zTarget,
167583
+ const char *zState
167584
+){
167585
+ /* TODO: Check that both arguments are non-NULL */
167586
+ return openRbuHandle(0, zTarget, zState);
167587
+}
164811167588
164812167589
/*
164813167590
** Return the database handle used by pRbu.
164814167591
*/
164815167592
SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
@@ -164826,11 +167603,11 @@
164826167603
** then edit any error message string so as to remove all occurrences of
164827167604
** the pattern "rbu_imp_[0-9]*".
164828167605
*/
164829167606
static void rbuEditErrmsg(sqlite3rbu *p){
164830167607
if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
164831
- int i;
167608
+ unsigned int i;
164832167609
size_t nErrmsg = strlen(p->zErrmsg);
164833167610
for(i=0; i<(nErrmsg-8); i++){
164834167611
if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
164835167612
int nDel = 8;
164836167613
while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
@@ -164859,14 +167636,24 @@
164859167636
p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
164860167637
}
164861167638
164862167639
/* Close any open statement handles. */
164863167640
rbuObjIterFinalize(&p->objiter);
167641
+
167642
+ /* If this is an RBU vacuum handle and the vacuum has either finished
167643
+ ** successfully or encountered an error, delete the contents of the
167644
+ ** state table. This causes the next call to sqlite3rbu_vacuum()
167645
+ ** specifying the current target and state databases to start a new
167646
+ ** vacuum from scratch. */
167647
+ if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
167648
+ int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
167649
+ if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
167650
+ }
164864167651
164865167652
/* Close the open database handle and VFS object. */
164866
- sqlite3_close(p->dbMain);
164867167653
sqlite3_close(p->dbRbu);
167654
+ sqlite3_close(p->dbMain);
164868167655
rbuDeleteVfs(p);
164869167656
sqlite3_free(p->aBuf);
164870167657
sqlite3_free(p->aFrame);
164871167658
164872167659
rbuEditErrmsg(p);
@@ -165063,10 +167850,26 @@
165063167850
return ((u32)aBuf[0] << 24)
165064167851
+ ((u32)aBuf[1] << 16)
165065167852
+ ((u32)aBuf[2] << 8)
165066167853
+ ((u32)aBuf[3]);
165067167854
}
167855
+
167856
+/*
167857
+** Write an unsigned 32-bit value in big-endian format to the supplied
167858
+** buffer.
167859
+*/
167860
+static void rbuPutU32(u8 *aBuf, u32 iVal){
167861
+ aBuf[0] = (iVal >> 24) & 0xFF;
167862
+ aBuf[1] = (iVal >> 16) & 0xFF;
167863
+ aBuf[2] = (iVal >> 8) & 0xFF;
167864
+ aBuf[3] = (iVal >> 0) & 0xFF;
167865
+}
167866
+
167867
+static void rbuPutU16(u8 *aBuf, u16 iVal){
167868
+ aBuf[0] = (iVal >> 8) & 0xFF;
167869
+ aBuf[1] = (iVal >> 0) & 0xFF;
167870
+}
165068167871
165069167872
/*
165070167873
** Read data from an rbuVfs-file.
165071167874
*/
165072167875
static int rbuVfsRead(
@@ -165089,10 +167892,39 @@
165089167892
){
165090167893
rc = SQLITE_OK;
165091167894
memset(zBuf, 0, iAmt);
165092167895
}else{
165093167896
rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
167897
+#if 1
167898
+ /* If this is being called to read the first page of the target
167899
+ ** database as part of an rbu vacuum operation, synthesize the
167900
+ ** contents of the first page if it does not yet exist. Otherwise,
167901
+ ** SQLite will not check for a *-wal file. */
167902
+ if( pRbu && rbuIsVacuum(pRbu)
167903
+ && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
167904
+ && (p->openFlags & SQLITE_OPEN_MAIN_DB)
167905
+ && pRbu->rc==SQLITE_OK
167906
+ ){
167907
+ sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
167908
+ rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
167909
+ if( rc==SQLITE_OK ){
167910
+ u8 *aBuf = (u8*)zBuf;
167911
+ u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
167912
+ rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
167913
+ rbuPutU32(&aBuf[36], 0); /* number of free pages */
167914
+ rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
167915
+ rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
167916
+ rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
167917
+
167918
+ if( iAmt>100 ){
167919
+ memset(&aBuf[100], 0, iAmt-100);
167920
+ rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
167921
+ aBuf[100] = 0x0D;
167922
+ }
167923
+ }
167924
+ }
167925
+#endif
165094167926
}
165095167927
if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
165096167928
/* These look like magic numbers. But they are stable, as they are part
165097167929
** of the definition of the SQLite file format, which may not change. */
165098167930
u8 *pBuf = (u8*)zBuf;
@@ -165163,11 +167995,24 @@
165163167995
/*
165164167996
** Return the current file-size of an rbuVfs-file.
165165167997
*/
165166167998
static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
165167167999
rbu_file *p = (rbu_file *)pFile;
165168
- return p->pReal->pMethods->xFileSize(p->pReal, pSize);
168000
+ int rc;
168001
+ rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
168002
+
168003
+ /* If this is an RBU vacuum operation and this is the target database,
168004
+ ** pretend that it has at least one page. Otherwise, SQLite will not
168005
+ ** check for the existance of a *-wal file. rbuVfsRead() contains
168006
+ ** similar logic. */
168007
+ if( rc==SQLITE_OK && *pSize==0
168008
+ && p->pRbu && rbuIsVacuum(p->pRbu)
168009
+ && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168010
+ ){
168011
+ *pSize = 1024;
168012
+ }
168013
+ return rc;
165169168014
}
165170168015
165171168016
/*
165172168017
** Lock an rbuVfs-file.
165173168018
*/
@@ -165175,11 +168020,13 @@
165175168020
rbu_file *p = (rbu_file*)pFile;
165176168021
sqlite3rbu *pRbu = p->pRbu;
165177168022
int rc = SQLITE_OK;
165178168023
165179168024
assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
165180
- if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
168025
+ if( eLock==SQLITE_LOCK_EXCLUSIVE
168026
+ && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
168027
+ ){
165181168028
/* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
165182168029
** prevents it from checkpointing the database from sqlite3_close(). */
165183168030
rc = SQLITE_BUSY;
165184168031
}else{
165185168032
rc = p->pReal->pMethods->xLock(p->pReal, eLock);
@@ -165237,10 +168084,16 @@
165237168084
if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
165238168085
rc = SQLITE_OK;
165239168086
}
165240168087
}
165241168088
return rc;
168089
+ }
168090
+ else if( op==SQLITE_FCNTL_RBUCNT ){
168091
+ sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
168092
+ pRbu->nRbu++;
168093
+ pRbu->pRbuFd = p;
168094
+ p->bNolock = 1;
165242168095
}
165243168096
165244168097
rc = xControl(p->pReal, op, pArg);
165245168098
if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
165246168099
rbu_vfs *pRbuVfs = p->pRbuVfs;
@@ -165400,10 +168253,37 @@
165400168253
sqlite3_mutex_enter(pRbuVfs->mutex);
165401168254
for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
165402168255
sqlite3_mutex_leave(pRbuVfs->mutex);
165403168256
return pDb;
165404168257
}
168258
+
168259
+/*
168260
+** A main database named zName has just been opened. The following
168261
+** function returns a pointer to a buffer owned by SQLite that contains
168262
+** the name of the *-wal file this db connection will use. SQLite
168263
+** happens to pass a pointer to this buffer when using xAccess()
168264
+** or xOpen() to operate on the *-wal file.
168265
+*/
168266
+static const char *rbuMainToWal(const char *zName, int flags){
168267
+ int n = (int)strlen(zName);
168268
+ const char *z = &zName[n];
168269
+ if( flags & SQLITE_OPEN_URI ){
168270
+ int odd = 0;
168271
+ while( 1 ){
168272
+ if( z[0]==0 ){
168273
+ odd = 1 - odd;
168274
+ if( odd && z[1]==0 ) break;
168275
+ }
168276
+ z++;
168277
+ }
168278
+ z += 2;
168279
+ }else{
168280
+ while( *z==0 ) z++;
168281
+ }
168282
+ z += (n + 8 + 1);
168283
+ return z;
168284
+}
165405168285
165406168286
/*
165407168287
** Open an rbu file handle.
165408168288
*/
165409168289
static int rbuVfsOpen(
@@ -165436,10 +168316,11 @@
165436168316
rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
165437168317
sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
165438168318
rbu_file *pFd = (rbu_file *)pFile;
165439168319
int rc = SQLITE_OK;
165440168320
const char *zOpen = zName;
168321
+ int oflags = flags;
165441168322
165442168323
memset(pFd, 0, sizeof(rbu_file));
165443168324
pFd->pReal = (sqlite3_file*)&pFd[1];
165444168325
pFd->pRbuVfs = pRbuVfs;
165445168326
pFd->openFlags = flags;
@@ -165448,40 +168329,31 @@
165448168329
/* A main database has just been opened. The following block sets
165449168330
** (pFd->zWal) to point to a buffer owned by SQLite that contains
165450168331
** the name of the *-wal file this db connection will use. SQLite
165451168332
** happens to pass a pointer to this buffer when using xAccess()
165452168333
** or xOpen() to operate on the *-wal file. */
165453
- int n = (int)strlen(zName);
165454
- const char *z = &zName[n];
165455
- if( flags & SQLITE_OPEN_URI ){
165456
- int odd = 0;
165457
- while( 1 ){
165458
- if( z[0]==0 ){
165459
- odd = 1 - odd;
165460
- if( odd && z[1]==0 ) break;
165461
- }
165462
- z++;
165463
- }
165464
- z += 2;
165465
- }else{
165466
- while( *z==0 ) z++;
165467
- }
165468
- z += (n + 8 + 1);
165469
- pFd->zWal = z;
168334
+ pFd->zWal = rbuMainToWal(zName, flags);
165470168335
}
165471168336
else if( flags & SQLITE_OPEN_WAL ){
165472168337
rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
165473168338
if( pDb ){
165474168339
if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
165475168340
/* This call is to open a *-wal file. Intead, open the *-oal. This
165476168341
** code ensures that the string passed to xOpen() is terminated by a
165477168342
** pair of '\0' bytes in case the VFS attempts to extract a URI
165478168343
** parameter from it. */
165479
- size_t nCopy = strlen(zName);
165480
- char *zCopy = sqlite3_malloc64(nCopy+2);
168344
+ const char *zBase = zName;
168345
+ size_t nCopy;
168346
+ char *zCopy;
168347
+ if( rbuIsVacuum(pDb->pRbu) ){
168348
+ zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
168349
+ zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
168350
+ }
168351
+ nCopy = strlen(zBase);
168352
+ zCopy = sqlite3_malloc64(nCopy+2);
165481168353
if( zCopy ){
165482
- memcpy(zCopy, zName, nCopy);
168354
+ memcpy(zCopy, zBase, nCopy);
165483168355
zCopy[nCopy-3] = 'o';
165484168356
zCopy[nCopy] = '\0';
165485168357
zCopy[nCopy+1] = '\0';
165486168358
zOpen = (const char*)(pFd->zDel = zCopy);
165487168359
}else{
@@ -165491,13 +168363,22 @@
165491168363
}
165492168364
pDb->pWalFd = pFd;
165493168365
}
165494168366
}
165495168367
}
168368
+
168369
+ if( oflags & SQLITE_OPEN_MAIN_DB
168370
+ && sqlite3_uri_boolean(zName, "rbu_memory", 0)
168371
+ ){
168372
+ assert( oflags & SQLITE_OPEN_MAIN_DB );
168373
+ oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
168374
+ SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
168375
+ zOpen = 0;
168376
+ }
165496168377
165497168378
if( rc==SQLITE_OK ){
165498
- rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
168379
+ rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
165499168380
}
165500168381
if( pFd->pReal->pMethods ){
165501168382
/* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
165502168383
** pointer and, if the file is a main database file, link it into the
165503168384
** mutex protected linked list of all such files. */
@@ -166457,10 +169338,4654 @@
166457169338
#elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
166458169339
SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
166459169340
#endif /* SQLITE_ENABLE_DBSTAT_VTAB */
166460169341
166461169342
/************** End of dbstat.c **********************************************/
169343
+/************** Begin file sqlite3session.c **********************************/
169344
+
169345
+#if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
169346
+/* #include "sqlite3session.h" */
169347
+/* #include <assert.h> */
169348
+/* #include <string.h> */
169349
+
169350
+#ifndef SQLITE_AMALGAMATION
169351
+/* # include "sqliteInt.h" */
169352
+/* # include "vdbeInt.h" */
169353
+#endif
169354
+
169355
+typedef struct SessionTable SessionTable;
169356
+typedef struct SessionChange SessionChange;
169357
+typedef struct SessionBuffer SessionBuffer;
169358
+typedef struct SessionInput SessionInput;
169359
+
169360
+/*
169361
+** Minimum chunk size used by streaming versions of functions.
169362
+*/
169363
+#ifndef SESSIONS_STRM_CHUNK_SIZE
169364
+# ifdef SQLITE_TEST
169365
+# define SESSIONS_STRM_CHUNK_SIZE 64
169366
+# else
169367
+# define SESSIONS_STRM_CHUNK_SIZE 1024
169368
+# endif
169369
+#endif
169370
+
169371
+typedef struct SessionHook SessionHook;
169372
+struct SessionHook {
169373
+ void *pCtx;
169374
+ int (*xOld)(void*,int,sqlite3_value**);
169375
+ int (*xNew)(void*,int,sqlite3_value**);
169376
+ int (*xCount)(void*);
169377
+ int (*xDepth)(void*);
169378
+};
169379
+
169380
+/*
169381
+** Session handle structure.
169382
+*/
169383
+struct sqlite3_session {
169384
+ sqlite3 *db; /* Database handle session is attached to */
169385
+ char *zDb; /* Name of database session is attached to */
169386
+ int bEnable; /* True if currently recording */
169387
+ int bIndirect; /* True if all changes are indirect */
169388
+ int bAutoAttach; /* True to auto-attach tables */
169389
+ int rc; /* Non-zero if an error has occurred */
169390
+ void *pFilterCtx; /* First argument to pass to xTableFilter */
169391
+ int (*xTableFilter)(void *pCtx, const char *zTab);
169392
+ sqlite3_session *pNext; /* Next session object on same db. */
169393
+ SessionTable *pTable; /* List of attached tables */
169394
+ SessionHook hook; /* APIs to grab new and old data with */
169395
+};
169396
+
169397
+/*
169398
+** Instances of this structure are used to build strings or binary records.
169399
+*/
169400
+struct SessionBuffer {
169401
+ u8 *aBuf; /* Pointer to changeset buffer */
169402
+ int nBuf; /* Size of buffer aBuf */
169403
+ int nAlloc; /* Size of allocation containing aBuf */
169404
+};
169405
+
169406
+/*
169407
+** An object of this type is used internally as an abstraction for
169408
+** input data. Input data may be supplied either as a single large buffer
169409
+** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
169410
+** sqlite3changeset_start_strm()).
169411
+*/
169412
+struct SessionInput {
169413
+ int bNoDiscard; /* If true, discard no data */
169414
+ int iCurrent; /* Offset in aData[] of current change */
169415
+ int iNext; /* Offset in aData[] of next change */
169416
+ u8 *aData; /* Pointer to buffer containing changeset */
169417
+ int nData; /* Number of bytes in aData */
169418
+
169419
+ SessionBuffer buf; /* Current read buffer */
169420
+ int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
169421
+ void *pIn; /* First argument to xInput */
169422
+ int bEof; /* Set to true after xInput finished */
169423
+};
169424
+
169425
+/*
169426
+** Structure for changeset iterators.
169427
+*/
169428
+struct sqlite3_changeset_iter {
169429
+ SessionInput in; /* Input buffer or stream */
169430
+ SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
169431
+ int bPatchset; /* True if this is a patchset */
169432
+ int rc; /* Iterator error code */
169433
+ sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
169434
+ char *zTab; /* Current table */
169435
+ int nCol; /* Number of columns in zTab */
169436
+ int op; /* Current operation */
169437
+ int bIndirect; /* True if current change was indirect */
169438
+ u8 *abPK; /* Primary key array */
169439
+ sqlite3_value **apValue; /* old.* and new.* values */
169440
+};
169441
+
169442
+/*
169443
+** Each session object maintains a set of the following structures, one
169444
+** for each table the session object is monitoring. The structures are
169445
+** stored in a linked list starting at sqlite3_session.pTable.
169446
+**
169447
+** The keys of the SessionTable.aChange[] hash table are all rows that have
169448
+** been modified in any way since the session object was attached to the
169449
+** table.
169450
+**
169451
+** The data associated with each hash-table entry is a structure containing
169452
+** a subset of the initial values that the modified row contained at the
169453
+** start of the session. Or no initial values if the row was inserted.
169454
+*/
169455
+struct SessionTable {
169456
+ SessionTable *pNext;
169457
+ char *zName; /* Local name of table */
169458
+ int nCol; /* Number of columns in table zName */
169459
+ const char **azCol; /* Column names */
169460
+ u8 *abPK; /* Array of primary key flags */
169461
+ int nEntry; /* Total number of entries in hash table */
169462
+ int nChange; /* Size of apChange[] array */
169463
+ SessionChange **apChange; /* Hash table buckets */
169464
+};
169465
+
169466
+/*
169467
+** RECORD FORMAT:
169468
+**
169469
+** The following record format is similar to (but not compatible with) that
169470
+** used in SQLite database files. This format is used as part of the
169471
+** change-set binary format, and so must be architecture independent.
169472
+**
169473
+** Unlike the SQLite database record format, each field is self-contained -
169474
+** there is no separation of header and data. Each field begins with a
169475
+** single byte describing its type, as follows:
169476
+**
169477
+** 0x00: Undefined value.
169478
+** 0x01: Integer value.
169479
+** 0x02: Real value.
169480
+** 0x03: Text value.
169481
+** 0x04: Blob value.
169482
+** 0x05: SQL NULL value.
169483
+**
169484
+** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
169485
+** and so on in sqlite3.h. For undefined and NULL values, the field consists
169486
+** only of the single type byte. For other types of values, the type byte
169487
+** is followed by:
169488
+**
169489
+** Text values:
169490
+** A varint containing the number of bytes in the value (encoded using
169491
+** UTF-8). Followed by a buffer containing the UTF-8 representation
169492
+** of the text value. There is no nul terminator.
169493
+**
169494
+** Blob values:
169495
+** A varint containing the number of bytes in the value, followed by
169496
+** a buffer containing the value itself.
169497
+**
169498
+** Integer values:
169499
+** An 8-byte big-endian integer value.
169500
+**
169501
+** Real values:
169502
+** An 8-byte big-endian IEEE 754-2008 real value.
169503
+**
169504
+** Varint values are encoded in the same way as varints in the SQLite
169505
+** record format.
169506
+**
169507
+** CHANGESET FORMAT:
169508
+**
169509
+** A changeset is a collection of DELETE, UPDATE and INSERT operations on
169510
+** one or more tables. Operations on a single table are grouped together,
169511
+** but may occur in any order (i.e. deletes, updates and inserts are all
169512
+** mixed together).
169513
+**
169514
+** Each group of changes begins with a table header:
169515
+**
169516
+** 1 byte: Constant 0x54 (capital 'T')
169517
+** Varint: Number of columns in the table.
169518
+** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169519
+** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169520
+**
169521
+** Followed by one or more changes to the table.
169522
+**
169523
+** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169524
+** 1 byte: The "indirect-change" flag.
169525
+** old.* record: (delete and update only)
169526
+** new.* record: (insert and update only)
169527
+**
169528
+** The "old.*" and "new.*" records, if present, are N field records in the
169529
+** format described above under "RECORD FORMAT", where N is the number of
169530
+** columns in the table. The i'th field of each record is associated with
169531
+** the i'th column of the table, counting from left to right in the order
169532
+** in which columns were declared in the CREATE TABLE statement.
169533
+**
169534
+** The new.* record that is part of each INSERT change contains the values
169535
+** that make up the new row. Similarly, the old.* record that is part of each
169536
+** DELETE change contains the values that made up the row that was deleted
169537
+** from the database. In the changeset format, the records that are part
169538
+** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
169539
+** fields.
169540
+**
169541
+** Within the old.* record associated with an UPDATE change, all fields
169542
+** associated with table columns that are not PRIMARY KEY columns and are
169543
+** not modified by the UPDATE change are set to "undefined". Other fields
169544
+** are set to the values that made up the row before the UPDATE that the
169545
+** change records took place. Within the new.* record, fields associated
169546
+** with table columns modified by the UPDATE change contain the new
169547
+** values. Fields associated with table columns that are not modified
169548
+** are set to "undefined".
169549
+**
169550
+** PATCHSET FORMAT:
169551
+**
169552
+** A patchset is also a collection of changes. It is similar to a changeset,
169553
+** but leaves undefined those fields that are not useful if no conflict
169554
+** resolution is required when applying the changeset.
169555
+**
169556
+** Each group of changes begins with a table header:
169557
+**
169558
+** 1 byte: Constant 0x50 (capital 'P')
169559
+** Varint: Number of columns in the table.
169560
+** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169561
+** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169562
+**
169563
+** Followed by one or more changes to the table.
169564
+**
169565
+** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169566
+** 1 byte: The "indirect-change" flag.
169567
+** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
169568
+** full record for INSERT).
169569
+**
169570
+** As in the changeset format, each field of the single record that is part
169571
+** of a patchset change is associated with the correspondingly positioned
169572
+** table column, counting from left to right within the CREATE TABLE
169573
+** statement.
169574
+**
169575
+** For a DELETE change, all fields within the record except those associated
169576
+** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
169577
+** contain the values identifying the row to delete.
169578
+**
169579
+** For an UPDATE change, all fields except those associated with PRIMARY KEY
169580
+** columns and columns that are modified by the UPDATE are set to "undefined".
169581
+** PRIMARY KEY fields contain the values identifying the table row to update,
169582
+** and fields associated with modified columns contain the new column values.
169583
+**
169584
+** The records associated with INSERT changes are in the same format as for
169585
+** changesets. It is not possible for a record associated with an INSERT
169586
+** change to contain a field set to "undefined".
169587
+*/
169588
+
169589
+/*
169590
+** For each row modified during a session, there exists a single instance of
169591
+** this structure stored in a SessionTable.aChange[] hash table.
169592
+*/
169593
+struct SessionChange {
169594
+ int op; /* One of UPDATE, DELETE, INSERT */
169595
+ int bIndirect; /* True if this change is "indirect" */
169596
+ int nRecord; /* Number of bytes in buffer aRecord[] */
169597
+ u8 *aRecord; /* Buffer containing old.* record */
169598
+ SessionChange *pNext; /* For hash-table collisions */
169599
+};
169600
+
169601
+/*
169602
+** Write a varint with value iVal into the buffer at aBuf. Return the
169603
+** number of bytes written.
169604
+*/
169605
+static int sessionVarintPut(u8 *aBuf, int iVal){
169606
+ return putVarint32(aBuf, iVal);
169607
+}
169608
+
169609
+/*
169610
+** Return the number of bytes required to store value iVal as a varint.
169611
+*/
169612
+static int sessionVarintLen(int iVal){
169613
+ return sqlite3VarintLen(iVal);
169614
+}
169615
+
169616
+/*
169617
+** Read a varint value from aBuf[] into *piVal. Return the number of
169618
+** bytes read.
169619
+*/
169620
+static int sessionVarintGet(u8 *aBuf, int *piVal){
169621
+ return getVarint32(aBuf, *piVal);
169622
+}
169623
+
169624
+/* Load an unaligned and unsigned 32-bit integer */
169625
+#define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
169626
+
169627
+/*
169628
+** Read a 64-bit big-endian integer value from buffer aRec[]. Return
169629
+** the value read.
169630
+*/
169631
+static sqlite3_int64 sessionGetI64(u8 *aRec){
169632
+ u64 x = SESSION_UINT32(aRec);
169633
+ u32 y = SESSION_UINT32(aRec+4);
169634
+ x = (x<<32) + y;
169635
+ return (sqlite3_int64)x;
169636
+}
169637
+
169638
+/*
169639
+** Write a 64-bit big-endian integer value to the buffer aBuf[].
169640
+*/
169641
+static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
169642
+ aBuf[0] = (i>>56) & 0xFF;
169643
+ aBuf[1] = (i>>48) & 0xFF;
169644
+ aBuf[2] = (i>>40) & 0xFF;
169645
+ aBuf[3] = (i>>32) & 0xFF;
169646
+ aBuf[4] = (i>>24) & 0xFF;
169647
+ aBuf[5] = (i>>16) & 0xFF;
169648
+ aBuf[6] = (i>> 8) & 0xFF;
169649
+ aBuf[7] = (i>> 0) & 0xFF;
169650
+}
169651
+
169652
+/*
169653
+** This function is used to serialize the contents of value pValue (see
169654
+** comment titled "RECORD FORMAT" above).
169655
+**
169656
+** If it is non-NULL, the serialized form of the value is written to
169657
+** buffer aBuf. *pnWrite is set to the number of bytes written before
169658
+** returning. Or, if aBuf is NULL, the only thing this function does is
169659
+** set *pnWrite.
169660
+**
169661
+** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
169662
+** within a call to sqlite3_value_text() (may fail if the db is utf-16))
169663
+** SQLITE_NOMEM is returned.
169664
+*/
169665
+static int sessionSerializeValue(
169666
+ u8 *aBuf, /* If non-NULL, write serialized value here */
169667
+ sqlite3_value *pValue, /* Value to serialize */
169668
+ int *pnWrite /* IN/OUT: Increment by bytes written */
169669
+){
169670
+ int nByte; /* Size of serialized value in bytes */
169671
+
169672
+ if( pValue ){
169673
+ int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
169674
+
169675
+ eType = sqlite3_value_type(pValue);
169676
+ if( aBuf ) aBuf[0] = eType;
169677
+
169678
+ switch( eType ){
169679
+ case SQLITE_NULL:
169680
+ nByte = 1;
169681
+ break;
169682
+
169683
+ case SQLITE_INTEGER:
169684
+ case SQLITE_FLOAT:
169685
+ if( aBuf ){
169686
+ /* TODO: SQLite does something special to deal with mixed-endian
169687
+ ** floating point values (e.g. ARM7). This code probably should
169688
+ ** too. */
169689
+ u64 i;
169690
+ if( eType==SQLITE_INTEGER ){
169691
+ i = (u64)sqlite3_value_int64(pValue);
169692
+ }else{
169693
+ double r;
169694
+ assert( sizeof(double)==8 && sizeof(u64)==8 );
169695
+ r = sqlite3_value_double(pValue);
169696
+ memcpy(&i, &r, 8);
169697
+ }
169698
+ sessionPutI64(&aBuf[1], i);
169699
+ }
169700
+ nByte = 9;
169701
+ break;
169702
+
169703
+ default: {
169704
+ u8 *z;
169705
+ int n;
169706
+ int nVarint;
169707
+
169708
+ assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
169709
+ if( eType==SQLITE_TEXT ){
169710
+ z = (u8 *)sqlite3_value_text(pValue);
169711
+ }else{
169712
+ z = (u8 *)sqlite3_value_blob(pValue);
169713
+ }
169714
+ n = sqlite3_value_bytes(pValue);
169715
+ if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169716
+ nVarint = sessionVarintLen(n);
169717
+
169718
+ if( aBuf ){
169719
+ sessionVarintPut(&aBuf[1], n);
169720
+ memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
169721
+ sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
169722
+ );
169723
+ }
169724
+
169725
+ nByte = 1 + nVarint + n;
169726
+ break;
169727
+ }
169728
+ }
169729
+ }else{
169730
+ nByte = 1;
169731
+ if( aBuf ) aBuf[0] = '\0';
169732
+ }
169733
+
169734
+ if( pnWrite ) *pnWrite += nByte;
169735
+ return SQLITE_OK;
169736
+}
169737
+
169738
+
169739
+/*
169740
+** This macro is used to calculate hash key values for data structures. In
169741
+** order to use this macro, the entire data structure must be represented
169742
+** as a series of unsigned integers. In order to calculate a hash-key value
169743
+** for a data structure represented as three such integers, the macro may
169744
+** then be used as follows:
169745
+**
169746
+** int hash_key_value;
169747
+** hash_key_value = HASH_APPEND(0, <value 1>);
169748
+** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
169749
+** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
169750
+**
169751
+** In practice, the data structures this macro is used for are the primary
169752
+** key values of modified rows.
169753
+*/
169754
+#define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
169755
+
169756
+/*
169757
+** Append the hash of the 64-bit integer passed as the second argument to the
169758
+** hash-key value passed as the first. Return the new hash-key value.
169759
+*/
169760
+static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
169761
+ h = HASH_APPEND(h, i & 0xFFFFFFFF);
169762
+ return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
169763
+}
169764
+
169765
+/*
169766
+** Append the hash of the blob passed via the second and third arguments to
169767
+** the hash-key value passed as the first. Return the new hash-key value.
169768
+*/
169769
+static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
169770
+ int i;
169771
+ for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
169772
+ return h;
169773
+}
169774
+
169775
+/*
169776
+** Append the hash of the data type passed as the second argument to the
169777
+** hash-key value passed as the first. Return the new hash-key value.
169778
+*/
169779
+static unsigned int sessionHashAppendType(unsigned int h, int eType){
169780
+ return HASH_APPEND(h, eType);
169781
+}
169782
+
169783
+/*
169784
+** This function may only be called from within a pre-update callback.
169785
+** It calculates a hash based on the primary key values of the old.* or
169786
+** new.* row currently available and, assuming no error occurs, writes it to
169787
+** *piHash before returning. If the primary key contains one or more NULL
169788
+** values, *pbNullPK is set to true before returning.
169789
+**
169790
+** If an error occurs, an SQLite error code is returned and the final values
169791
+** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
169792
+** and the output variables are set as described above.
169793
+*/
169794
+static int sessionPreupdateHash(
169795
+ sqlite3_session *pSession, /* Session object that owns pTab */
169796
+ SessionTable *pTab, /* Session table handle */
169797
+ int bNew, /* True to hash the new.* PK */
169798
+ int *piHash, /* OUT: Hash value */
169799
+ int *pbNullPK /* OUT: True if there are NULL values in PK */
169800
+){
169801
+ unsigned int h = 0; /* Hash value to return */
169802
+ int i; /* Used to iterate through columns */
169803
+
169804
+ assert( *pbNullPK==0 );
169805
+ assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
169806
+ for(i=0; i<pTab->nCol; i++){
169807
+ if( pTab->abPK[i] ){
169808
+ int rc;
169809
+ int eType;
169810
+ sqlite3_value *pVal;
169811
+
169812
+ if( bNew ){
169813
+ rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
169814
+ }else{
169815
+ rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
169816
+ }
169817
+ if( rc!=SQLITE_OK ) return rc;
169818
+
169819
+ eType = sqlite3_value_type(pVal);
169820
+ h = sessionHashAppendType(h, eType);
169821
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169822
+ i64 iVal;
169823
+ if( eType==SQLITE_INTEGER ){
169824
+ iVal = sqlite3_value_int64(pVal);
169825
+ }else{
169826
+ double rVal = sqlite3_value_double(pVal);
169827
+ assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
169828
+ memcpy(&iVal, &rVal, 8);
169829
+ }
169830
+ h = sessionHashAppendI64(h, iVal);
169831
+ }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
169832
+ const u8 *z;
169833
+ int n;
169834
+ if( eType==SQLITE_TEXT ){
169835
+ z = (const u8 *)sqlite3_value_text(pVal);
169836
+ }else{
169837
+ z = (const u8 *)sqlite3_value_blob(pVal);
169838
+ }
169839
+ n = sqlite3_value_bytes(pVal);
169840
+ if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169841
+ h = sessionHashAppendBlob(h, n, z);
169842
+ }else{
169843
+ assert( eType==SQLITE_NULL );
169844
+ *pbNullPK = 1;
169845
+ }
169846
+ }
169847
+ }
169848
+
169849
+ *piHash = (h % pTab->nChange);
169850
+ return SQLITE_OK;
169851
+}
169852
+
169853
+/*
169854
+** The buffer that the argument points to contains a serialized SQL value.
169855
+** Return the number of bytes of space occupied by the value (including
169856
+** the type byte).
169857
+*/
169858
+static int sessionSerialLen(u8 *a){
169859
+ int e = *a;
169860
+ int n;
169861
+ if( e==0 ) return 1;
169862
+ if( e==SQLITE_NULL ) return 1;
169863
+ if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
169864
+ return sessionVarintGet(&a[1], &n) + 1 + n;
169865
+}
169866
+
169867
+/*
169868
+** Based on the primary key values stored in change aRecord, calculate a
169869
+** hash key. Assume the has table has nBucket buckets. The hash keys
169870
+** calculated by this function are compatible with those calculated by
169871
+** sessionPreupdateHash().
169872
+**
169873
+** The bPkOnly argument is non-zero if the record at aRecord[] is from
169874
+** a patchset DELETE. In this case the non-PK fields are omitted entirely.
169875
+*/
169876
+static unsigned int sessionChangeHash(
169877
+ SessionTable *pTab, /* Table handle */
169878
+ int bPkOnly, /* Record consists of PK fields only */
169879
+ u8 *aRecord, /* Change record */
169880
+ int nBucket /* Assume this many buckets in hash table */
169881
+){
169882
+ unsigned int h = 0; /* Value to return */
169883
+ int i; /* Used to iterate through columns */
169884
+ u8 *a = aRecord; /* Used to iterate through change record */
169885
+
169886
+ for(i=0; i<pTab->nCol; i++){
169887
+ int eType = *a;
169888
+ int isPK = pTab->abPK[i];
169889
+ if( bPkOnly && isPK==0 ) continue;
169890
+
169891
+ /* It is not possible for eType to be SQLITE_NULL here. The session
169892
+ ** module does not record changes for rows with NULL values stored in
169893
+ ** primary key columns. */
169894
+ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
169895
+ || eType==SQLITE_TEXT || eType==SQLITE_BLOB
169896
+ || eType==SQLITE_NULL || eType==0
169897
+ );
169898
+ assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
169899
+
169900
+ if( isPK ){
169901
+ a++;
169902
+ h = sessionHashAppendType(h, eType);
169903
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169904
+ h = sessionHashAppendI64(h, sessionGetI64(a));
169905
+ a += 8;
169906
+ }else{
169907
+ int n;
169908
+ a += sessionVarintGet(a, &n);
169909
+ h = sessionHashAppendBlob(h, n, a);
169910
+ a += n;
169911
+ }
169912
+ }else{
169913
+ a += sessionSerialLen(a);
169914
+ }
169915
+ }
169916
+ return (h % nBucket);
169917
+}
169918
+
169919
+/*
169920
+** Arguments aLeft and aRight are pointers to change records for table pTab.
169921
+** This function returns true if the two records apply to the same row (i.e.
169922
+** have the same values stored in the primary key columns), or false
169923
+** otherwise.
169924
+*/
169925
+static int sessionChangeEqual(
169926
+ SessionTable *pTab, /* Table used for PK definition */
169927
+ int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
169928
+ u8 *aLeft, /* Change record */
169929
+ int bRightPkOnly, /* True if aRight[] contains PK fields only */
169930
+ u8 *aRight /* Change record */
169931
+){
169932
+ u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
169933
+ u8 *a2 = aRight; /* Cursor to iterate through aRight */
169934
+ int iCol; /* Used to iterate through table columns */
169935
+
169936
+ for(iCol=0; iCol<pTab->nCol; iCol++){
169937
+ if( pTab->abPK[iCol] ){
169938
+ int n1 = sessionSerialLen(a1);
169939
+ int n2 = sessionSerialLen(a2);
169940
+
169941
+ if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
169942
+ return 0;
169943
+ }
169944
+ a1 += n1;
169945
+ a2 += n2;
169946
+ }else{
169947
+ if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
169948
+ if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
169949
+ }
169950
+ }
169951
+
169952
+ return 1;
169953
+}
169954
+
169955
+/*
169956
+** Arguments aLeft and aRight both point to buffers containing change
169957
+** records with nCol columns. This function "merges" the two records into
169958
+** a single records which is written to the buffer at *paOut. *paOut is
169959
+** then set to point to one byte after the last byte written before
169960
+** returning.
169961
+**
169962
+** The merging of records is done as follows: For each column, if the
169963
+** aRight record contains a value for the column, copy the value from
169964
+** their. Otherwise, if aLeft contains a value, copy it. If neither
169965
+** record contains a value for a given column, then neither does the
169966
+** output record.
169967
+*/
169968
+static void sessionMergeRecord(
169969
+ u8 **paOut,
169970
+ int nCol,
169971
+ u8 *aLeft,
169972
+ u8 *aRight
169973
+){
169974
+ u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
169975
+ u8 *a2 = aRight; /* Cursor used to iterate through aRight */
169976
+ u8 *aOut = *paOut; /* Output cursor */
169977
+ int iCol; /* Used to iterate from 0 to nCol */
169978
+
169979
+ for(iCol=0; iCol<nCol; iCol++){
169980
+ int n1 = sessionSerialLen(a1);
169981
+ int n2 = sessionSerialLen(a2);
169982
+ if( *a2 ){
169983
+ memcpy(aOut, a2, n2);
169984
+ aOut += n2;
169985
+ }else{
169986
+ memcpy(aOut, a1, n1);
169987
+ aOut += n1;
169988
+ }
169989
+ a1 += n1;
169990
+ a2 += n2;
169991
+ }
169992
+
169993
+ *paOut = aOut;
169994
+}
169995
+
169996
+/*
169997
+** This is a helper function used by sessionMergeUpdate().
169998
+**
169999
+** When this function is called, both *paOne and *paTwo point to a value
170000
+** within a change record. Before it returns, both have been advanced so
170001
+** as to point to the next value in the record.
170002
+**
170003
+** If, when this function is called, *paTwo points to a valid value (i.e.
170004
+** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
170005
+** pointer is returned and *pnVal is set to the number of bytes in the
170006
+** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
170007
+** set to the number of bytes in the value at *paOne. If *paOne points
170008
+** to the "no value" placeholder, *pnVal is set to 1. In other words:
170009
+**
170010
+** if( *paTwo is valid ) return *paTwo;
170011
+** return *paOne;
170012
+**
170013
+*/
170014
+static u8 *sessionMergeValue(
170015
+ u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
170016
+ u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
170017
+ int *pnVal /* OUT: Bytes in returned value */
170018
+){
170019
+ u8 *a1 = *paOne;
170020
+ u8 *a2 = *paTwo;
170021
+ u8 *pRet = 0;
170022
+ int n1;
170023
+
170024
+ assert( a1 );
170025
+ if( a2 ){
170026
+ int n2 = sessionSerialLen(a2);
170027
+ if( *a2 ){
170028
+ *pnVal = n2;
170029
+ pRet = a2;
170030
+ }
170031
+ *paTwo = &a2[n2];
170032
+ }
170033
+
170034
+ n1 = sessionSerialLen(a1);
170035
+ if( pRet==0 ){
170036
+ *pnVal = n1;
170037
+ pRet = a1;
170038
+ }
170039
+ *paOne = &a1[n1];
170040
+
170041
+ return pRet;
170042
+}
170043
+
170044
+/*
170045
+** This function is used by changeset_concat() to merge two UPDATE changes
170046
+** on the same row.
170047
+*/
170048
+static int sessionMergeUpdate(
170049
+ u8 **paOut, /* IN/OUT: Pointer to output buffer */
170050
+ SessionTable *pTab, /* Table change pertains to */
170051
+ int bPatchset, /* True if records are patchset records */
170052
+ u8 *aOldRecord1, /* old.* record for first change */
170053
+ u8 *aOldRecord2, /* old.* record for second change */
170054
+ u8 *aNewRecord1, /* new.* record for first change */
170055
+ u8 *aNewRecord2 /* new.* record for second change */
170056
+){
170057
+ u8 *aOld1 = aOldRecord1;
170058
+ u8 *aOld2 = aOldRecord2;
170059
+ u8 *aNew1 = aNewRecord1;
170060
+ u8 *aNew2 = aNewRecord2;
170061
+
170062
+ u8 *aOut = *paOut;
170063
+ int i;
170064
+
170065
+ if( bPatchset==0 ){
170066
+ int bRequired = 0;
170067
+
170068
+ assert( aOldRecord1 && aNewRecord1 );
170069
+
170070
+ /* Write the old.* vector first. */
170071
+ for(i=0; i<pTab->nCol; i++){
170072
+ int nOld;
170073
+ u8 *aOld;
170074
+ int nNew;
170075
+ u8 *aNew;
170076
+
170077
+ aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170078
+ aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170079
+ if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
170080
+ if( pTab->abPK[i]==0 ) bRequired = 1;
170081
+ memcpy(aOut, aOld, nOld);
170082
+ aOut += nOld;
170083
+ }else{
170084
+ *(aOut++) = '\0';
170085
+ }
170086
+ }
170087
+
170088
+ if( !bRequired ) return 0;
170089
+ }
170090
+
170091
+ /* Write the new.* vector */
170092
+ aOld1 = aOldRecord1;
170093
+ aOld2 = aOldRecord2;
170094
+ aNew1 = aNewRecord1;
170095
+ aNew2 = aNewRecord2;
170096
+ for(i=0; i<pTab->nCol; i++){
170097
+ int nOld;
170098
+ u8 *aOld;
170099
+ int nNew;
170100
+ u8 *aNew;
170101
+
170102
+ aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170103
+ aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170104
+ if( bPatchset==0
170105
+ && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
170106
+ ){
170107
+ *(aOut++) = '\0';
170108
+ }else{
170109
+ memcpy(aOut, aNew, nNew);
170110
+ aOut += nNew;
170111
+ }
170112
+ }
170113
+
170114
+ *paOut = aOut;
170115
+ return 1;
170116
+}
170117
+
170118
+/*
170119
+** This function is only called from within a pre-update-hook callback.
170120
+** It determines if the current pre-update-hook change affects the same row
170121
+** as the change stored in argument pChange. If so, it returns true. Otherwise
170122
+** if the pre-update-hook does not affect the same row as pChange, it returns
170123
+** false.
170124
+*/
170125
+static int sessionPreupdateEqual(
170126
+ sqlite3_session *pSession, /* Session object that owns SessionTable */
170127
+ SessionTable *pTab, /* Table associated with change */
170128
+ SessionChange *pChange, /* Change to compare to */
170129
+ int op /* Current pre-update operation */
170130
+){
170131
+ int iCol; /* Used to iterate through columns */
170132
+ u8 *a = pChange->aRecord; /* Cursor used to scan change record */
170133
+
170134
+ assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
170135
+ for(iCol=0; iCol<pTab->nCol; iCol++){
170136
+ if( !pTab->abPK[iCol] ){
170137
+ a += sessionSerialLen(a);
170138
+ }else{
170139
+ sqlite3_value *pVal; /* Value returned by preupdate_new/old */
170140
+ int rc; /* Error code from preupdate_new/old */
170141
+ int eType = *a++; /* Type of value from change record */
170142
+
170143
+ /* The following calls to preupdate_new() and preupdate_old() can not
170144
+ ** fail. This is because they cache their return values, and by the
170145
+ ** time control flows to here they have already been called once from
170146
+ ** within sessionPreupdateHash(). The first two asserts below verify
170147
+ ** this (that the method has already been called). */
170148
+ if( op==SQLITE_INSERT ){
170149
+ /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
170150
+ rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
170151
+ }else{
170152
+ /* assert( db->pPreUpdate->pUnpacked ); */
170153
+ rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
170154
+ }
170155
+ assert( rc==SQLITE_OK );
170156
+ if( sqlite3_value_type(pVal)!=eType ) return 0;
170157
+
170158
+ /* A SessionChange object never has a NULL value in a PK column */
170159
+ assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
170160
+ || eType==SQLITE_BLOB || eType==SQLITE_TEXT
170161
+ );
170162
+
170163
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170164
+ i64 iVal = sessionGetI64(a);
170165
+ a += 8;
170166
+ if( eType==SQLITE_INTEGER ){
170167
+ if( sqlite3_value_int64(pVal)!=iVal ) return 0;
170168
+ }else{
170169
+ double rVal;
170170
+ assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170171
+ memcpy(&rVal, &iVal, 8);
170172
+ if( sqlite3_value_double(pVal)!=rVal ) return 0;
170173
+ }
170174
+ }else{
170175
+ int n;
170176
+ const u8 *z;
170177
+ a += sessionVarintGet(a, &n);
170178
+ if( sqlite3_value_bytes(pVal)!=n ) return 0;
170179
+ if( eType==SQLITE_TEXT ){
170180
+ z = sqlite3_value_text(pVal);
170181
+ }else{
170182
+ z = sqlite3_value_blob(pVal);
170183
+ }
170184
+ if( memcmp(a, z, n) ) return 0;
170185
+ a += n;
170186
+ break;
170187
+ }
170188
+ }
170189
+ }
170190
+
170191
+ return 1;
170192
+}
170193
+
170194
+/*
170195
+** If required, grow the hash table used to store changes on table pTab
170196
+** (part of the session pSession). If a fatal OOM error occurs, set the
170197
+** session object to failed and return SQLITE_ERROR. Otherwise, return
170198
+** SQLITE_OK.
170199
+**
170200
+** It is possible that a non-fatal OOM error occurs in this function. In
170201
+** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
170202
+** Growing the hash table in this case is a performance optimization only,
170203
+** it is not required for correct operation.
170204
+*/
170205
+static int sessionGrowHash(int bPatchset, SessionTable *pTab){
170206
+ if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
170207
+ int i;
170208
+ SessionChange **apNew;
170209
+ int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
170210
+
170211
+ apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
170212
+ if( apNew==0 ){
170213
+ if( pTab->nChange==0 ){
170214
+ return SQLITE_ERROR;
170215
+ }
170216
+ return SQLITE_OK;
170217
+ }
170218
+ memset(apNew, 0, sizeof(SessionChange *) * nNew);
170219
+
170220
+ for(i=0; i<pTab->nChange; i++){
170221
+ SessionChange *p;
170222
+ SessionChange *pNext;
170223
+ for(p=pTab->apChange[i]; p; p=pNext){
170224
+ int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
170225
+ int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
170226
+ pNext = p->pNext;
170227
+ p->pNext = apNew[iHash];
170228
+ apNew[iHash] = p;
170229
+ }
170230
+ }
170231
+
170232
+ sqlite3_free(pTab->apChange);
170233
+ pTab->nChange = nNew;
170234
+ pTab->apChange = apNew;
170235
+ }
170236
+
170237
+ return SQLITE_OK;
170238
+}
170239
+
170240
+/*
170241
+** This function queries the database for the names of the columns of table
170242
+** zThis, in schema zDb. It is expected that the table has nCol columns. If
170243
+** not, SQLITE_SCHEMA is returned and none of the output variables are
170244
+** populated.
170245
+**
170246
+** Otherwise, if they are not NULL, variable *pnCol is set to the number
170247
+** of columns in the database table and variable *pzTab is set to point to a
170248
+** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
170249
+** point to an array of pointers to column names. And *pabPK (again, if not
170250
+** NULL) is set to point to an array of booleans - true if the corresponding
170251
+** column is part of the primary key.
170252
+**
170253
+** For example, if the table is declared as:
170254
+**
170255
+** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
170256
+**
170257
+** Then the four output variables are populated as follows:
170258
+**
170259
+** *pnCol = 4
170260
+** *pzTab = "tbl1"
170261
+** *pazCol = {"w", "x", "y", "z"}
170262
+** *pabPK = {1, 0, 0, 1}
170263
+**
170264
+** All returned buffers are part of the same single allocation, which must
170265
+** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
170266
+** pointer *pazCol should be freed to release all memory. Otherwise, pointer
170267
+** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
170268
+*/
170269
+static int sessionTableInfo(
170270
+ sqlite3 *db, /* Database connection */
170271
+ const char *zDb, /* Name of attached database (e.g. "main") */
170272
+ const char *zThis, /* Table name */
170273
+ int *pnCol, /* OUT: number of columns */
170274
+ const char **pzTab, /* OUT: Copy of zThis */
170275
+ const char ***pazCol, /* OUT: Array of column names for table */
170276
+ u8 **pabPK /* OUT: Array of booleans - true for PK col */
170277
+){
170278
+ char *zPragma;
170279
+ sqlite3_stmt *pStmt;
170280
+ int rc;
170281
+ int nByte;
170282
+ int nDbCol = 0;
170283
+ int nThis;
170284
+ int i;
170285
+ u8 *pAlloc = 0;
170286
+ char **azCol = 0;
170287
+ u8 *abPK = 0;
170288
+
170289
+ assert( pazCol && pabPK );
170290
+
170291
+ nThis = sqlite3Strlen30(zThis);
170292
+ zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
170293
+ if( !zPragma ) return SQLITE_NOMEM;
170294
+
170295
+ rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
170296
+ sqlite3_free(zPragma);
170297
+ if( rc!=SQLITE_OK ) return rc;
170298
+
170299
+ nByte = nThis + 1;
170300
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
170301
+ nByte += sqlite3_column_bytes(pStmt, 1);
170302
+ nDbCol++;
170303
+ }
170304
+ rc = sqlite3_reset(pStmt);
170305
+
170306
+ if( rc==SQLITE_OK ){
170307
+ nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
170308
+ pAlloc = sqlite3_malloc(nByte);
170309
+ if( pAlloc==0 ){
170310
+ rc = SQLITE_NOMEM;
170311
+ }
170312
+ }
170313
+ if( rc==SQLITE_OK ){
170314
+ azCol = (char **)pAlloc;
170315
+ pAlloc = (u8 *)&azCol[nDbCol];
170316
+ abPK = (u8 *)pAlloc;
170317
+ pAlloc = &abPK[nDbCol];
170318
+ if( pzTab ){
170319
+ memcpy(pAlloc, zThis, nThis+1);
170320
+ *pzTab = (char *)pAlloc;
170321
+ pAlloc += nThis+1;
170322
+ }
170323
+
170324
+ i = 0;
170325
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
170326
+ int nName = sqlite3_column_bytes(pStmt, 1);
170327
+ const unsigned char *zName = sqlite3_column_text(pStmt, 1);
170328
+ if( zName==0 ) break;
170329
+ memcpy(pAlloc, zName, nName+1);
170330
+ azCol[i] = (char *)pAlloc;
170331
+ pAlloc += nName+1;
170332
+ abPK[i] = sqlite3_column_int(pStmt, 5);
170333
+ i++;
170334
+ }
170335
+ rc = sqlite3_reset(pStmt);
170336
+
170337
+ }
170338
+
170339
+ /* If successful, populate the output variables. Otherwise, zero them and
170340
+ ** free any allocation made. An error code will be returned in this case.
170341
+ */
170342
+ if( rc==SQLITE_OK ){
170343
+ *pazCol = (const char **)azCol;
170344
+ *pabPK = abPK;
170345
+ *pnCol = nDbCol;
170346
+ }else{
170347
+ *pazCol = 0;
170348
+ *pabPK = 0;
170349
+ *pnCol = 0;
170350
+ if( pzTab ) *pzTab = 0;
170351
+ sqlite3_free(azCol);
170352
+ }
170353
+ sqlite3_finalize(pStmt);
170354
+ return rc;
170355
+}
170356
+
170357
+/*
170358
+** This function is only called from within a pre-update handler for a
170359
+** write to table pTab, part of session pSession. If this is the first
170360
+** write to this table, initalize the SessionTable.nCol, azCol[] and
170361
+** abPK[] arrays accordingly.
170362
+**
170363
+** If an error occurs, an error code is stored in sqlite3_session.rc and
170364
+** non-zero returned. Or, if no error occurs but the table has no primary
170365
+** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
170366
+** indicate that updates on this table should be ignored. SessionTable.abPK
170367
+** is set to NULL in this case.
170368
+*/
170369
+static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
170370
+ if( pTab->nCol==0 ){
170371
+ u8 *abPK;
170372
+ assert( pTab->azCol==0 || pTab->abPK==0 );
170373
+ pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
170374
+ pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
170375
+ );
170376
+ if( pSession->rc==SQLITE_OK ){
170377
+ int i;
170378
+ for(i=0; i<pTab->nCol; i++){
170379
+ if( abPK[i] ){
170380
+ pTab->abPK = abPK;
170381
+ break;
170382
+ }
170383
+ }
170384
+ }
170385
+ }
170386
+ return (pSession->rc || pTab->abPK==0);
170387
+}
170388
+
170389
+/*
170390
+** This function is only called from with a pre-update-hook reporting a
170391
+** change on table pTab (attached to session pSession). The type of change
170392
+** (UPDATE, INSERT, DELETE) is specified by the first argument.
170393
+**
170394
+** Unless one is already present or an error occurs, an entry is added
170395
+** to the changed-rows hash table associated with table pTab.
170396
+*/
170397
+static void sessionPreupdateOneChange(
170398
+ int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
170399
+ sqlite3_session *pSession, /* Session object pTab is attached to */
170400
+ SessionTable *pTab /* Table that change applies to */
170401
+){
170402
+ int iHash;
170403
+ int bNull = 0;
170404
+ int rc = SQLITE_OK;
170405
+
170406
+ if( pSession->rc ) return;
170407
+
170408
+ /* Load table details if required */
170409
+ if( sessionInitTable(pSession, pTab) ) return;
170410
+
170411
+ /* Check the number of columns in this xPreUpdate call matches the
170412
+ ** number of columns in the table. */
170413
+ if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
170414
+ pSession->rc = SQLITE_SCHEMA;
170415
+ return;
170416
+ }
170417
+
170418
+ /* Grow the hash table if required */
170419
+ if( sessionGrowHash(0, pTab) ){
170420
+ pSession->rc = SQLITE_NOMEM;
170421
+ return;
170422
+ }
170423
+
170424
+ /* Calculate the hash-key for this change. If the primary key of the row
170425
+ ** includes a NULL value, exit early. Such changes are ignored by the
170426
+ ** session module. */
170427
+ rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
170428
+ if( rc!=SQLITE_OK ) goto error_out;
170429
+
170430
+ if( bNull==0 ){
170431
+ /* Search the hash table for an existing record for this row. */
170432
+ SessionChange *pC;
170433
+ for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
170434
+ if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
170435
+ }
170436
+
170437
+ if( pC==0 ){
170438
+ /* Create a new change object containing all the old values (if
170439
+ ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
170440
+ ** values (if this is an INSERT). */
170441
+ SessionChange *pChange; /* New change object */
170442
+ int nByte; /* Number of bytes to allocate */
170443
+ int i; /* Used to iterate through columns */
170444
+
170445
+ assert( rc==SQLITE_OK );
170446
+ pTab->nEntry++;
170447
+
170448
+ /* Figure out how large an allocation is required */
170449
+ nByte = sizeof(SessionChange);
170450
+ for(i=0; i<pTab->nCol; i++){
170451
+ sqlite3_value *p = 0;
170452
+ if( op!=SQLITE_INSERT ){
170453
+ TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170454
+ assert( trc==SQLITE_OK );
170455
+ }else if( pTab->abPK[i] ){
170456
+ TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170457
+ assert( trc==SQLITE_OK );
170458
+ }
170459
+
170460
+ /* This may fail if SQLite value p contains a utf-16 string that must
170461
+ ** be converted to utf-8 and an OOM error occurs while doing so. */
170462
+ rc = sessionSerializeValue(0, p, &nByte);
170463
+ if( rc!=SQLITE_OK ) goto error_out;
170464
+ }
170465
+
170466
+ /* Allocate the change object */
170467
+ pChange = (SessionChange *)sqlite3_malloc(nByte);
170468
+ if( !pChange ){
170469
+ rc = SQLITE_NOMEM;
170470
+ goto error_out;
170471
+ }else{
170472
+ memset(pChange, 0, sizeof(SessionChange));
170473
+ pChange->aRecord = (u8 *)&pChange[1];
170474
+ }
170475
+
170476
+ /* Populate the change object. None of the preupdate_old(),
170477
+ ** preupdate_new() or SerializeValue() calls below may fail as all
170478
+ ** required values and encodings have already been cached in memory.
170479
+ ** It is not possible for an OOM to occur in this block. */
170480
+ nByte = 0;
170481
+ for(i=0; i<pTab->nCol; i++){
170482
+ sqlite3_value *p = 0;
170483
+ if( op!=SQLITE_INSERT ){
170484
+ pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170485
+ }else if( pTab->abPK[i] ){
170486
+ pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170487
+ }
170488
+ sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
170489
+ }
170490
+
170491
+ /* Add the change to the hash-table */
170492
+ if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
170493
+ pChange->bIndirect = 1;
170494
+ }
170495
+ pChange->nRecord = nByte;
170496
+ pChange->op = op;
170497
+ pChange->pNext = pTab->apChange[iHash];
170498
+ pTab->apChange[iHash] = pChange;
170499
+
170500
+ }else if( pC->bIndirect ){
170501
+ /* If the existing change is considered "indirect", but this current
170502
+ ** change is "direct", mark the change object as direct. */
170503
+ if( pSession->hook.xDepth(pSession->hook.pCtx)==0
170504
+ && pSession->bIndirect==0
170505
+ ){
170506
+ pC->bIndirect = 0;
170507
+ }
170508
+ }
170509
+ }
170510
+
170511
+ /* If an error has occurred, mark the session object as failed. */
170512
+ error_out:
170513
+ if( rc!=SQLITE_OK ){
170514
+ pSession->rc = rc;
170515
+ }
170516
+}
170517
+
170518
+static int sessionFindTable(
170519
+ sqlite3_session *pSession,
170520
+ const char *zName,
170521
+ SessionTable **ppTab
170522
+){
170523
+ int rc = SQLITE_OK;
170524
+ int nName = sqlite3Strlen30(zName);
170525
+ SessionTable *pRet;
170526
+
170527
+ /* Search for an existing table */
170528
+ for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
170529
+ if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
170530
+ }
170531
+
170532
+ if( pRet==0 && pSession->bAutoAttach ){
170533
+ /* If there is a table-filter configured, invoke it. If it returns 0,
170534
+ ** do not automatically add the new table. */
170535
+ if( pSession->xTableFilter==0
170536
+ || pSession->xTableFilter(pSession->pFilterCtx, zName)
170537
+ ){
170538
+ rc = sqlite3session_attach(pSession, zName);
170539
+ if( rc==SQLITE_OK ){
170540
+ for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
170541
+ assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
170542
+ }
170543
+ }
170544
+ }
170545
+
170546
+ assert( rc==SQLITE_OK || pRet==0 );
170547
+ *ppTab = pRet;
170548
+ return rc;
170549
+}
170550
+
170551
+/*
170552
+** The 'pre-update' hook registered by this module with SQLite databases.
170553
+*/
170554
+static void xPreUpdate(
170555
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
170556
+ sqlite3 *db, /* Database handle */
170557
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
170558
+ char const *zDb, /* Database name */
170559
+ char const *zName, /* Table name */
170560
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
170561
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
170562
+){
170563
+ sqlite3_session *pSession;
170564
+ int nDb = sqlite3Strlen30(zDb);
170565
+
170566
+ assert( sqlite3_mutex_held(db->mutex) );
170567
+
170568
+ for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
170569
+ SessionTable *pTab;
170570
+
170571
+ /* If this session is attached to a different database ("main", "temp"
170572
+ ** etc.), or if it is not currently enabled, there is nothing to do. Skip
170573
+ ** to the next session object attached to this database. */
170574
+ if( pSession->bEnable==0 ) continue;
170575
+ if( pSession->rc ) continue;
170576
+ if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
170577
+
170578
+ pSession->rc = sessionFindTable(pSession, zName, &pTab);
170579
+ if( pTab ){
170580
+ assert( pSession->rc==SQLITE_OK );
170581
+ sessionPreupdateOneChange(op, pSession, pTab);
170582
+ if( op==SQLITE_UPDATE ){
170583
+ sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
170584
+ }
170585
+ }
170586
+ }
170587
+}
170588
+
170589
+/*
170590
+** The pre-update hook implementations.
170591
+*/
170592
+static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170593
+ return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
170594
+}
170595
+static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170596
+ return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
170597
+}
170598
+static int sessionPreupdateCount(void *pCtx){
170599
+ return sqlite3_preupdate_count((sqlite3*)pCtx);
170600
+}
170601
+static int sessionPreupdateDepth(void *pCtx){
170602
+ return sqlite3_preupdate_depth((sqlite3*)pCtx);
170603
+}
170604
+
170605
+/*
170606
+** Install the pre-update hooks on the session object passed as the only
170607
+** argument.
170608
+*/
170609
+static void sessionPreupdateHooks(
170610
+ sqlite3_session *pSession
170611
+){
170612
+ pSession->hook.pCtx = (void*)pSession->db;
170613
+ pSession->hook.xOld = sessionPreupdateOld;
170614
+ pSession->hook.xNew = sessionPreupdateNew;
170615
+ pSession->hook.xCount = sessionPreupdateCount;
170616
+ pSession->hook.xDepth = sessionPreupdateDepth;
170617
+}
170618
+
170619
+typedef struct SessionDiffCtx SessionDiffCtx;
170620
+struct SessionDiffCtx {
170621
+ sqlite3_stmt *pStmt;
170622
+ int nOldOff;
170623
+};
170624
+
170625
+/*
170626
+** The diff hook implementations.
170627
+*/
170628
+static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170629
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170630
+ *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
170631
+ return SQLITE_OK;
170632
+}
170633
+static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170634
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170635
+ *ppVal = sqlite3_column_value(p->pStmt, iVal);
170636
+ return SQLITE_OK;
170637
+}
170638
+static int sessionDiffCount(void *pCtx){
170639
+ SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170640
+ return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
170641
+}
170642
+static int sessionDiffDepth(void *pCtx){
170643
+ return 0;
170644
+}
170645
+
170646
+/*
170647
+** Install the diff hooks on the session object passed as the only
170648
+** argument.
170649
+*/
170650
+static void sessionDiffHooks(
170651
+ sqlite3_session *pSession,
170652
+ SessionDiffCtx *pDiffCtx
170653
+){
170654
+ pSession->hook.pCtx = (void*)pDiffCtx;
170655
+ pSession->hook.xOld = sessionDiffOld;
170656
+ pSession->hook.xNew = sessionDiffNew;
170657
+ pSession->hook.xCount = sessionDiffCount;
170658
+ pSession->hook.xDepth = sessionDiffDepth;
170659
+}
170660
+
170661
+static char *sessionExprComparePK(
170662
+ int nCol,
170663
+ const char *zDb1, const char *zDb2,
170664
+ const char *zTab,
170665
+ const char **azCol, u8 *abPK
170666
+){
170667
+ int i;
170668
+ const char *zSep = "";
170669
+ char *zRet = 0;
170670
+
170671
+ for(i=0; i<nCol; i++){
170672
+ if( abPK[i] ){
170673
+ zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
170674
+ zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170675
+ );
170676
+ zSep = " AND ";
170677
+ if( zRet==0 ) break;
170678
+ }
170679
+ }
170680
+
170681
+ return zRet;
170682
+}
170683
+
170684
+static char *sessionExprCompareOther(
170685
+ int nCol,
170686
+ const char *zDb1, const char *zDb2,
170687
+ const char *zTab,
170688
+ const char **azCol, u8 *abPK
170689
+){
170690
+ int i;
170691
+ const char *zSep = "";
170692
+ char *zRet = 0;
170693
+ int bHave = 0;
170694
+
170695
+ for(i=0; i<nCol; i++){
170696
+ if( abPK[i]==0 ){
170697
+ bHave = 1;
170698
+ zRet = sqlite3_mprintf(
170699
+ "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
170700
+ zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170701
+ );
170702
+ zSep = " OR ";
170703
+ if( zRet==0 ) break;
170704
+ }
170705
+ }
170706
+
170707
+ if( bHave==0 ){
170708
+ assert( zRet==0 );
170709
+ zRet = sqlite3_mprintf("0");
170710
+ }
170711
+
170712
+ return zRet;
170713
+}
170714
+
170715
+static char *sessionSelectFindNew(
170716
+ int nCol,
170717
+ const char *zDb1, /* Pick rows in this db only */
170718
+ const char *zDb2, /* But not in this one */
170719
+ const char *zTbl, /* Table name */
170720
+ const char *zExpr
170721
+){
170722
+ char *zRet = sqlite3_mprintf(
170723
+ "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
170724
+ " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
170725
+ ")",
170726
+ zDb1, zTbl, zDb2, zTbl, zExpr
170727
+ );
170728
+ return zRet;
170729
+}
170730
+
170731
+static int sessionDiffFindNew(
170732
+ int op,
170733
+ sqlite3_session *pSession,
170734
+ SessionTable *pTab,
170735
+ const char *zDb1,
170736
+ const char *zDb2,
170737
+ char *zExpr
170738
+){
170739
+ int rc = SQLITE_OK;
170740
+ char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
170741
+
170742
+ if( zStmt==0 ){
170743
+ rc = SQLITE_NOMEM;
170744
+ }else{
170745
+ sqlite3_stmt *pStmt;
170746
+ rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170747
+ if( rc==SQLITE_OK ){
170748
+ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170749
+ pDiffCtx->pStmt = pStmt;
170750
+ pDiffCtx->nOldOff = 0;
170751
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
170752
+ sessionPreupdateOneChange(op, pSession, pTab);
170753
+ }
170754
+ rc = sqlite3_finalize(pStmt);
170755
+ }
170756
+ sqlite3_free(zStmt);
170757
+ }
170758
+
170759
+ return rc;
170760
+}
170761
+
170762
+static int sessionDiffFindModified(
170763
+ sqlite3_session *pSession,
170764
+ SessionTable *pTab,
170765
+ const char *zFrom,
170766
+ const char *zExpr
170767
+){
170768
+ int rc = SQLITE_OK;
170769
+
170770
+ char *zExpr2 = sessionExprCompareOther(pTab->nCol,
170771
+ pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
170772
+ );
170773
+ if( zExpr2==0 ){
170774
+ rc = SQLITE_NOMEM;
170775
+ }else{
170776
+ char *zStmt = sqlite3_mprintf(
170777
+ "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
170778
+ pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
170779
+ );
170780
+ if( zStmt==0 ){
170781
+ rc = SQLITE_NOMEM;
170782
+ }else{
170783
+ sqlite3_stmt *pStmt;
170784
+ rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170785
+
170786
+ if( rc==SQLITE_OK ){
170787
+ SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170788
+ pDiffCtx->pStmt = pStmt;
170789
+ pDiffCtx->nOldOff = pTab->nCol;
170790
+ while( SQLITE_ROW==sqlite3_step(pStmt) ){
170791
+ sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
170792
+ }
170793
+ rc = sqlite3_finalize(pStmt);
170794
+ }
170795
+ sqlite3_free(zStmt);
170796
+ }
170797
+ }
170798
+
170799
+ return rc;
170800
+}
170801
+
170802
+SQLITE_API int SQLITE_STDCALL sqlite3session_diff(
170803
+ sqlite3_session *pSession,
170804
+ const char *zFrom,
170805
+ const char *zTbl,
170806
+ char **pzErrMsg
170807
+){
170808
+ const char *zDb = pSession->zDb;
170809
+ int rc = pSession->rc;
170810
+ SessionDiffCtx d;
170811
+
170812
+ memset(&d, 0, sizeof(d));
170813
+ sessionDiffHooks(pSession, &d);
170814
+
170815
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
170816
+ if( pzErrMsg ) *pzErrMsg = 0;
170817
+ if( rc==SQLITE_OK ){
170818
+ char *zExpr = 0;
170819
+ sqlite3 *db = pSession->db;
170820
+ SessionTable *pTo; /* Table zTbl */
170821
+
170822
+ /* Locate and if necessary initialize the target table object */
170823
+ rc = sessionFindTable(pSession, zTbl, &pTo);
170824
+ if( pTo==0 ) goto diff_out;
170825
+ if( sessionInitTable(pSession, pTo) ){
170826
+ rc = pSession->rc;
170827
+ goto diff_out;
170828
+ }
170829
+
170830
+ /* Check the table schemas match */
170831
+ if( rc==SQLITE_OK ){
170832
+ int bHasPk = 0;
170833
+ int bMismatch = 0;
170834
+ int nCol; /* Columns in zFrom.zTbl */
170835
+ u8 *abPK;
170836
+ const char **azCol = 0;
170837
+ rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
170838
+ if( rc==SQLITE_OK ){
170839
+ if( pTo->nCol!=nCol ){
170840
+ bMismatch = 1;
170841
+ }else{
170842
+ int i;
170843
+ for(i=0; i<nCol; i++){
170844
+ if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
170845
+ if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
170846
+ if( abPK[i] ) bHasPk = 1;
170847
+ }
170848
+ }
170849
+
170850
+ }
170851
+ sqlite3_free((char*)azCol);
170852
+ if( bMismatch ){
170853
+ *pzErrMsg = sqlite3_mprintf("table schemas do not match");
170854
+ rc = SQLITE_SCHEMA;
170855
+ }
170856
+ if( bHasPk==0 ){
170857
+ /* Ignore tables with no primary keys */
170858
+ goto diff_out;
170859
+ }
170860
+ }
170861
+
170862
+ if( rc==SQLITE_OK ){
170863
+ zExpr = sessionExprComparePK(pTo->nCol,
170864
+ zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
170865
+ );
170866
+ }
170867
+
170868
+ /* Find new rows */
170869
+ if( rc==SQLITE_OK ){
170870
+ rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
170871
+ }
170872
+
170873
+ /* Find old rows */
170874
+ if( rc==SQLITE_OK ){
170875
+ rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
170876
+ }
170877
+
170878
+ /* Find modified rows */
170879
+ if( rc==SQLITE_OK ){
170880
+ rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
170881
+ }
170882
+
170883
+ sqlite3_free(zExpr);
170884
+ }
170885
+
170886
+ diff_out:
170887
+ sessionPreupdateHooks(pSession);
170888
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
170889
+ return rc;
170890
+}
170891
+
170892
+/*
170893
+** Create a session object. This session object will record changes to
170894
+** database zDb attached to connection db.
170895
+*/
170896
+SQLITE_API int SQLITE_STDCALL sqlite3session_create(
170897
+ sqlite3 *db, /* Database handle */
170898
+ const char *zDb, /* Name of db (e.g. "main") */
170899
+ sqlite3_session **ppSession /* OUT: New session object */
170900
+){
170901
+ sqlite3_session *pNew; /* Newly allocated session object */
170902
+ sqlite3_session *pOld; /* Session object already attached to db */
170903
+ int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
170904
+
170905
+ /* Zero the output value in case an error occurs. */
170906
+ *ppSession = 0;
170907
+
170908
+ /* Allocate and populate the new session object. */
170909
+ pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
170910
+ if( !pNew ) return SQLITE_NOMEM;
170911
+ memset(pNew, 0, sizeof(sqlite3_session));
170912
+ pNew->db = db;
170913
+ pNew->zDb = (char *)&pNew[1];
170914
+ pNew->bEnable = 1;
170915
+ memcpy(pNew->zDb, zDb, nDb+1);
170916
+ sessionPreupdateHooks(pNew);
170917
+
170918
+ /* Add the new session object to the linked list of session objects
170919
+ ** attached to database handle $db. Do this under the cover of the db
170920
+ ** handle mutex. */
170921
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
170922
+ pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
170923
+ pNew->pNext = pOld;
170924
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
170925
+
170926
+ *ppSession = pNew;
170927
+ return SQLITE_OK;
170928
+}
170929
+
170930
+/*
170931
+** Free the list of table objects passed as the first argument. The contents
170932
+** of the changed-rows hash tables are also deleted.
170933
+*/
170934
+static void sessionDeleteTable(SessionTable *pList){
170935
+ SessionTable *pNext;
170936
+ SessionTable *pTab;
170937
+
170938
+ for(pTab=pList; pTab; pTab=pNext){
170939
+ int i;
170940
+ pNext = pTab->pNext;
170941
+ for(i=0; i<pTab->nChange; i++){
170942
+ SessionChange *p;
170943
+ SessionChange *pNextChange;
170944
+ for(p=pTab->apChange[i]; p; p=pNextChange){
170945
+ pNextChange = p->pNext;
170946
+ sqlite3_free(p);
170947
+ }
170948
+ }
170949
+ sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
170950
+ sqlite3_free(pTab->apChange);
170951
+ sqlite3_free(pTab);
170952
+ }
170953
+}
170954
+
170955
+/*
170956
+** Delete a session object previously allocated using sqlite3session_create().
170957
+*/
170958
+SQLITE_API void SQLITE_STDCALL sqlite3session_delete(sqlite3_session *pSession){
170959
+ sqlite3 *db = pSession->db;
170960
+ sqlite3_session *pHead;
170961
+ sqlite3_session **pp;
170962
+
170963
+ /* Unlink the session from the linked list of sessions attached to the
170964
+ ** database handle. Hold the db mutex while doing so. */
170965
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
170966
+ pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
170967
+ for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
170968
+ if( (*pp)==pSession ){
170969
+ *pp = (*pp)->pNext;
170970
+ if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
170971
+ break;
170972
+ }
170973
+ }
170974
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
170975
+
170976
+ /* Delete all attached table objects. And the contents of their
170977
+ ** associated hash-tables. */
170978
+ sessionDeleteTable(pSession->pTable);
170979
+
170980
+ /* Free the session object itself. */
170981
+ sqlite3_free(pSession);
170982
+}
170983
+
170984
+/*
170985
+** Set a table filter on a Session Object.
170986
+*/
170987
+SQLITE_API void SQLITE_STDCALL sqlite3session_table_filter(
170988
+ sqlite3_session *pSession,
170989
+ int(*xFilter)(void*, const char*),
170990
+ void *pCtx /* First argument passed to xFilter */
170991
+){
170992
+ pSession->bAutoAttach = 1;
170993
+ pSession->pFilterCtx = pCtx;
170994
+ pSession->xTableFilter = xFilter;
170995
+}
170996
+
170997
+/*
170998
+** Attach a table to a session. All subsequent changes made to the table
170999
+** while the session object is enabled will be recorded.
171000
+**
171001
+** Only tables that have a PRIMARY KEY defined may be attached. It does
171002
+** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
171003
+** or not.
171004
+*/
171005
+SQLITE_API int SQLITE_STDCALL sqlite3session_attach(
171006
+ sqlite3_session *pSession, /* Session object */
171007
+ const char *zName /* Table name */
171008
+){
171009
+ int rc = SQLITE_OK;
171010
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171011
+
171012
+ if( !zName ){
171013
+ pSession->bAutoAttach = 1;
171014
+ }else{
171015
+ SessionTable *pTab; /* New table object (if required) */
171016
+ int nName; /* Number of bytes in string zName */
171017
+
171018
+ /* First search for an existing entry. If one is found, this call is
171019
+ ** a no-op. Return early. */
171020
+ nName = sqlite3Strlen30(zName);
171021
+ for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
171022
+ if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
171023
+ }
171024
+
171025
+ if( !pTab ){
171026
+ /* Allocate new SessionTable object. */
171027
+ pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
171028
+ if( !pTab ){
171029
+ rc = SQLITE_NOMEM;
171030
+ }else{
171031
+ /* Populate the new SessionTable object and link it into the list.
171032
+ ** The new object must be linked onto the end of the list, not
171033
+ ** simply added to the start of it in order to ensure that tables
171034
+ ** appear in the correct order when a changeset or patchset is
171035
+ ** eventually generated. */
171036
+ SessionTable **ppTab;
171037
+ memset(pTab, 0, sizeof(SessionTable));
171038
+ pTab->zName = (char *)&pTab[1];
171039
+ memcpy(pTab->zName, zName, nName+1);
171040
+ for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
171041
+ *ppTab = pTab;
171042
+ }
171043
+ }
171044
+ }
171045
+
171046
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171047
+ return rc;
171048
+}
171049
+
171050
+/*
171051
+** Ensure that there is room in the buffer to append nByte bytes of data.
171052
+** If not, use sqlite3_realloc() to grow the buffer so that there is.
171053
+**
171054
+** If successful, return zero. Otherwise, if an OOM condition is encountered,
171055
+** set *pRc to SQLITE_NOMEM and return non-zero.
171056
+*/
171057
+static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
171058
+ if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
171059
+ u8 *aNew;
171060
+ int nNew = p->nAlloc ? p->nAlloc : 128;
171061
+ do {
171062
+ nNew = nNew*2;
171063
+ }while( nNew<(p->nBuf+nByte) );
171064
+
171065
+ aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
171066
+ if( 0==aNew ){
171067
+ *pRc = SQLITE_NOMEM;
171068
+ }else{
171069
+ p->aBuf = aNew;
171070
+ p->nAlloc = nNew;
171071
+ }
171072
+ }
171073
+ return (*pRc!=SQLITE_OK);
171074
+}
171075
+
171076
+/*
171077
+** Append the value passed as the second argument to the buffer passed
171078
+** as the first.
171079
+**
171080
+** This function is a no-op if *pRc is non-zero when it is called.
171081
+** Otherwise, if an error occurs, *pRc is set to an SQLite error code
171082
+** before returning.
171083
+*/
171084
+static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
171085
+ int rc = *pRc;
171086
+ if( rc==SQLITE_OK ){
171087
+ int nByte = 0;
171088
+ rc = sessionSerializeValue(0, pVal, &nByte);
171089
+ sessionBufferGrow(p, nByte, &rc);
171090
+ if( rc==SQLITE_OK ){
171091
+ rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
171092
+ p->nBuf += nByte;
171093
+ }else{
171094
+ *pRc = rc;
171095
+ }
171096
+ }
171097
+}
171098
+
171099
+/*
171100
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171101
+** called. Otherwise, append a single byte to the buffer.
171102
+**
171103
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171104
+** returning.
171105
+*/
171106
+static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
171107
+ if( 0==sessionBufferGrow(p, 1, pRc) ){
171108
+ p->aBuf[p->nBuf++] = v;
171109
+ }
171110
+}
171111
+
171112
+/*
171113
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171114
+** called. Otherwise, append a single varint to the buffer.
171115
+**
171116
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171117
+** returning.
171118
+*/
171119
+static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
171120
+ if( 0==sessionBufferGrow(p, 9, pRc) ){
171121
+ p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
171122
+ }
171123
+}
171124
+
171125
+/*
171126
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171127
+** called. Otherwise, append a blob of data to the buffer.
171128
+**
171129
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171130
+** returning.
171131
+*/
171132
+static void sessionAppendBlob(
171133
+ SessionBuffer *p,
171134
+ const u8 *aBlob,
171135
+ int nBlob,
171136
+ int *pRc
171137
+){
171138
+ if( 0==sessionBufferGrow(p, nBlob, pRc) ){
171139
+ memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
171140
+ p->nBuf += nBlob;
171141
+ }
171142
+}
171143
+
171144
+/*
171145
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171146
+** called. Otherwise, append a string to the buffer. All bytes in the string
171147
+** up to (but not including) the nul-terminator are written to the buffer.
171148
+**
171149
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171150
+** returning.
171151
+*/
171152
+static void sessionAppendStr(
171153
+ SessionBuffer *p,
171154
+ const char *zStr,
171155
+ int *pRc
171156
+){
171157
+ int nStr = sqlite3Strlen30(zStr);
171158
+ if( 0==sessionBufferGrow(p, nStr, pRc) ){
171159
+ memcpy(&p->aBuf[p->nBuf], zStr, nStr);
171160
+ p->nBuf += nStr;
171161
+ }
171162
+}
171163
+
171164
+/*
171165
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171166
+** called. Otherwise, append the string representation of integer iVal
171167
+** to the buffer. No nul-terminator is written.
171168
+**
171169
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171170
+** returning.
171171
+*/
171172
+static void sessionAppendInteger(
171173
+ SessionBuffer *p, /* Buffer to append to */
171174
+ int iVal, /* Value to write the string rep. of */
171175
+ int *pRc /* IN/OUT: Error code */
171176
+){
171177
+ char aBuf[24];
171178
+ sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
171179
+ sessionAppendStr(p, aBuf, pRc);
171180
+}
171181
+
171182
+/*
171183
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171184
+** called. Otherwise, append the string zStr enclosed in quotes (") and
171185
+** with any embedded quote characters escaped to the buffer. No
171186
+** nul-terminator byte is written.
171187
+**
171188
+** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171189
+** returning.
171190
+*/
171191
+static void sessionAppendIdent(
171192
+ SessionBuffer *p, /* Buffer to a append to */
171193
+ const char *zStr, /* String to quote, escape and append */
171194
+ int *pRc /* IN/OUT: Error code */
171195
+){
171196
+ int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
171197
+ if( 0==sessionBufferGrow(p, nStr, pRc) ){
171198
+ char *zOut = (char *)&p->aBuf[p->nBuf];
171199
+ const char *zIn = zStr;
171200
+ *zOut++ = '"';
171201
+ while( *zIn ){
171202
+ if( *zIn=='"' ) *zOut++ = '"';
171203
+ *zOut++ = *(zIn++);
171204
+ }
171205
+ *zOut++ = '"';
171206
+ p->nBuf = (int)((u8 *)zOut - p->aBuf);
171207
+ }
171208
+}
171209
+
171210
+/*
171211
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
171212
+** called. Otherwse, it appends the serialized version of the value stored
171213
+** in column iCol of the row that SQL statement pStmt currently points
171214
+** to to the buffer.
171215
+*/
171216
+static void sessionAppendCol(
171217
+ SessionBuffer *p, /* Buffer to append to */
171218
+ sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
171219
+ int iCol, /* Column to read value from */
171220
+ int *pRc /* IN/OUT: Error code */
171221
+){
171222
+ if( *pRc==SQLITE_OK ){
171223
+ int eType = sqlite3_column_type(pStmt, iCol);
171224
+ sessionAppendByte(p, (u8)eType, pRc);
171225
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171226
+ sqlite3_int64 i;
171227
+ u8 aBuf[8];
171228
+ if( eType==SQLITE_INTEGER ){
171229
+ i = sqlite3_column_int64(pStmt, iCol);
171230
+ }else{
171231
+ double r = sqlite3_column_double(pStmt, iCol);
171232
+ memcpy(&i, &r, 8);
171233
+ }
171234
+ sessionPutI64(aBuf, i);
171235
+ sessionAppendBlob(p, aBuf, 8, pRc);
171236
+ }
171237
+ if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
171238
+ u8 *z;
171239
+ int nByte;
171240
+ if( eType==SQLITE_BLOB ){
171241
+ z = (u8 *)sqlite3_column_blob(pStmt, iCol);
171242
+ }else{
171243
+ z = (u8 *)sqlite3_column_text(pStmt, iCol);
171244
+ }
171245
+ nByte = sqlite3_column_bytes(pStmt, iCol);
171246
+ if( z || (eType==SQLITE_BLOB && nByte==0) ){
171247
+ sessionAppendVarint(p, nByte, pRc);
171248
+ sessionAppendBlob(p, z, nByte, pRc);
171249
+ }else{
171250
+ *pRc = SQLITE_NOMEM;
171251
+ }
171252
+ }
171253
+ }
171254
+}
171255
+
171256
+/*
171257
+**
171258
+** This function appends an update change to the buffer (see the comments
171259
+** under "CHANGESET FORMAT" at the top of the file). An update change
171260
+** consists of:
171261
+**
171262
+** 1 byte: SQLITE_UPDATE (0x17)
171263
+** n bytes: old.* record (see RECORD FORMAT)
171264
+** m bytes: new.* record (see RECORD FORMAT)
171265
+**
171266
+** The SessionChange object passed as the third argument contains the
171267
+** values that were stored in the row when the session began (the old.*
171268
+** values). The statement handle passed as the second argument points
171269
+** at the current version of the row (the new.* values).
171270
+**
171271
+** If all of the old.* values are equal to their corresponding new.* value
171272
+** (i.e. nothing has changed), then no data at all is appended to the buffer.
171273
+**
171274
+** Otherwise, the old.* record contains all primary key values and the
171275
+** original values of any fields that have been modified. The new.* record
171276
+** contains the new values of only those fields that have been modified.
171277
+*/
171278
+static int sessionAppendUpdate(
171279
+ SessionBuffer *pBuf, /* Buffer to append to */
171280
+ int bPatchset, /* True for "patchset", 0 for "changeset" */
171281
+ sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
171282
+ SessionChange *p, /* Object containing old values */
171283
+ u8 *abPK /* Boolean array - true for PK columns */
171284
+){
171285
+ int rc = SQLITE_OK;
171286
+ SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
171287
+ int bNoop = 1; /* Set to zero if any values are modified */
171288
+ int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
171289
+ int i; /* Used to iterate through columns */
171290
+ u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
171291
+
171292
+ sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
171293
+ sessionAppendByte(pBuf, p->bIndirect, &rc);
171294
+ for(i=0; i<sqlite3_column_count(pStmt); i++){
171295
+ int bChanged = 0;
171296
+ int nAdvance;
171297
+ int eType = *pCsr;
171298
+ switch( eType ){
171299
+ case SQLITE_NULL:
171300
+ nAdvance = 1;
171301
+ if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
171302
+ bChanged = 1;
171303
+ }
171304
+ break;
171305
+
171306
+ case SQLITE_FLOAT:
171307
+ case SQLITE_INTEGER: {
171308
+ nAdvance = 9;
171309
+ if( eType==sqlite3_column_type(pStmt, i) ){
171310
+ sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
171311
+ if( eType==SQLITE_INTEGER ){
171312
+ if( iVal==sqlite3_column_int64(pStmt, i) ) break;
171313
+ }else{
171314
+ double dVal;
171315
+ memcpy(&dVal, &iVal, 8);
171316
+ if( dVal==sqlite3_column_double(pStmt, i) ) break;
171317
+ }
171318
+ }
171319
+ bChanged = 1;
171320
+ break;
171321
+ }
171322
+
171323
+ default: {
171324
+ int nByte;
171325
+ int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
171326
+ assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
171327
+ nAdvance = nHdr + nByte;
171328
+ if( eType==sqlite3_column_type(pStmt, i)
171329
+ && nByte==sqlite3_column_bytes(pStmt, i)
171330
+ && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
171331
+ ){
171332
+ break;
171333
+ }
171334
+ bChanged = 1;
171335
+ }
171336
+ }
171337
+
171338
+ /* If at least one field has been modified, this is not a no-op. */
171339
+ if( bChanged ) bNoop = 0;
171340
+
171341
+ /* Add a field to the old.* record. This is omitted if this modules is
171342
+ ** currently generating a patchset. */
171343
+ if( bPatchset==0 ){
171344
+ if( bChanged || abPK[i] ){
171345
+ sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
171346
+ }else{
171347
+ sessionAppendByte(pBuf, 0, &rc);
171348
+ }
171349
+ }
171350
+
171351
+ /* Add a field to the new.* record. Or the only record if currently
171352
+ ** generating a patchset. */
171353
+ if( bChanged || (bPatchset && abPK[i]) ){
171354
+ sessionAppendCol(&buf2, pStmt, i, &rc);
171355
+ }else{
171356
+ sessionAppendByte(&buf2, 0, &rc);
171357
+ }
171358
+
171359
+ pCsr += nAdvance;
171360
+ }
171361
+
171362
+ if( bNoop ){
171363
+ pBuf->nBuf = nRewind;
171364
+ }else{
171365
+ sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
171366
+ }
171367
+ sqlite3_free(buf2.aBuf);
171368
+
171369
+ return rc;
171370
+}
171371
+
171372
+/*
171373
+** Append a DELETE change to the buffer passed as the first argument. Use
171374
+** the changeset format if argument bPatchset is zero, or the patchset
171375
+** format otherwise.
171376
+*/
171377
+static int sessionAppendDelete(
171378
+ SessionBuffer *pBuf, /* Buffer to append to */
171379
+ int bPatchset, /* True for "patchset", 0 for "changeset" */
171380
+ SessionChange *p, /* Object containing old values */
171381
+ int nCol, /* Number of columns in table */
171382
+ u8 *abPK /* Boolean array - true for PK columns */
171383
+){
171384
+ int rc = SQLITE_OK;
171385
+
171386
+ sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
171387
+ sessionAppendByte(pBuf, p->bIndirect, &rc);
171388
+
171389
+ if( bPatchset==0 ){
171390
+ sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
171391
+ }else{
171392
+ int i;
171393
+ u8 *a = p->aRecord;
171394
+ for(i=0; i<nCol; i++){
171395
+ u8 *pStart = a;
171396
+ int eType = *a++;
171397
+
171398
+ switch( eType ){
171399
+ case 0:
171400
+ case SQLITE_NULL:
171401
+ assert( abPK[i]==0 );
171402
+ break;
171403
+
171404
+ case SQLITE_FLOAT:
171405
+ case SQLITE_INTEGER:
171406
+ a += 8;
171407
+ break;
171408
+
171409
+ default: {
171410
+ int n;
171411
+ a += sessionVarintGet(a, &n);
171412
+ a += n;
171413
+ break;
171414
+ }
171415
+ }
171416
+ if( abPK[i] ){
171417
+ sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
171418
+ }
171419
+ }
171420
+ assert( (a - p->aRecord)==p->nRecord );
171421
+ }
171422
+
171423
+ return rc;
171424
+}
171425
+
171426
+/*
171427
+** Formulate and prepare a SELECT statement to retrieve a row from table
171428
+** zTab in database zDb based on its primary key. i.e.
171429
+**
171430
+** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
171431
+*/
171432
+static int sessionSelectStmt(
171433
+ sqlite3 *db, /* Database handle */
171434
+ const char *zDb, /* Database name */
171435
+ const char *zTab, /* Table name */
171436
+ int nCol, /* Number of columns in table */
171437
+ const char **azCol, /* Names of table columns */
171438
+ u8 *abPK, /* PRIMARY KEY array */
171439
+ sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
171440
+){
171441
+ int rc = SQLITE_OK;
171442
+ int i;
171443
+ const char *zSep = "";
171444
+ SessionBuffer buf = {0, 0, 0};
171445
+
171446
+ sessionAppendStr(&buf, "SELECT * FROM ", &rc);
171447
+ sessionAppendIdent(&buf, zDb, &rc);
171448
+ sessionAppendStr(&buf, ".", &rc);
171449
+ sessionAppendIdent(&buf, zTab, &rc);
171450
+ sessionAppendStr(&buf, " WHERE ", &rc);
171451
+ for(i=0; i<nCol; i++){
171452
+ if( abPK[i] ){
171453
+ sessionAppendStr(&buf, zSep, &rc);
171454
+ sessionAppendIdent(&buf, azCol[i], &rc);
171455
+ sessionAppendStr(&buf, " = ?", &rc);
171456
+ sessionAppendInteger(&buf, i+1, &rc);
171457
+ zSep = " AND ";
171458
+ }
171459
+ }
171460
+ if( rc==SQLITE_OK ){
171461
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
171462
+ }
171463
+ sqlite3_free(buf.aBuf);
171464
+ return rc;
171465
+}
171466
+
171467
+/*
171468
+** Bind the PRIMARY KEY values from the change passed in argument pChange
171469
+** to the SELECT statement passed as the first argument. The SELECT statement
171470
+** is as prepared by function sessionSelectStmt().
171471
+**
171472
+** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
171473
+** error code (e.g. SQLITE_NOMEM) otherwise.
171474
+*/
171475
+static int sessionSelectBind(
171476
+ sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
171477
+ int nCol, /* Number of columns in table */
171478
+ u8 *abPK, /* PRIMARY KEY array */
171479
+ SessionChange *pChange /* Change structure */
171480
+){
171481
+ int i;
171482
+ int rc = SQLITE_OK;
171483
+ u8 *a = pChange->aRecord;
171484
+
171485
+ for(i=0; i<nCol && rc==SQLITE_OK; i++){
171486
+ int eType = *a++;
171487
+
171488
+ switch( eType ){
171489
+ case 0:
171490
+ case SQLITE_NULL:
171491
+ assert( abPK[i]==0 );
171492
+ break;
171493
+
171494
+ case SQLITE_INTEGER: {
171495
+ if( abPK[i] ){
171496
+ i64 iVal = sessionGetI64(a);
171497
+ rc = sqlite3_bind_int64(pSelect, i+1, iVal);
171498
+ }
171499
+ a += 8;
171500
+ break;
171501
+ }
171502
+
171503
+ case SQLITE_FLOAT: {
171504
+ if( abPK[i] ){
171505
+ double rVal;
171506
+ i64 iVal = sessionGetI64(a);
171507
+ memcpy(&rVal, &iVal, 8);
171508
+ rc = sqlite3_bind_double(pSelect, i+1, rVal);
171509
+ }
171510
+ a += 8;
171511
+ break;
171512
+ }
171513
+
171514
+ case SQLITE_TEXT: {
171515
+ int n;
171516
+ a += sessionVarintGet(a, &n);
171517
+ if( abPK[i] ){
171518
+ rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
171519
+ }
171520
+ a += n;
171521
+ break;
171522
+ }
171523
+
171524
+ default: {
171525
+ int n;
171526
+ assert( eType==SQLITE_BLOB );
171527
+ a += sessionVarintGet(a, &n);
171528
+ if( abPK[i] ){
171529
+ rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
171530
+ }
171531
+ a += n;
171532
+ break;
171533
+ }
171534
+ }
171535
+ }
171536
+
171537
+ return rc;
171538
+}
171539
+
171540
+/*
171541
+** This function is a no-op if *pRc is set to other than SQLITE_OK when it
171542
+** is called. Otherwise, append a serialized table header (part of the binary
171543
+** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
171544
+** SQLite error code before returning.
171545
+*/
171546
+static void sessionAppendTableHdr(
171547
+ SessionBuffer *pBuf, /* Append header to this buffer */
171548
+ int bPatchset, /* Use the patchset format if true */
171549
+ SessionTable *pTab, /* Table object to append header for */
171550
+ int *pRc /* IN/OUT: Error code */
171551
+){
171552
+ /* Write a table header */
171553
+ sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
171554
+ sessionAppendVarint(pBuf, pTab->nCol, pRc);
171555
+ sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
171556
+ sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
171557
+}
171558
+
171559
+/*
171560
+** Generate either a changeset (if argument bPatchset is zero) or a patchset
171561
+** (if it is non-zero) based on the current contents of the session object
171562
+** passed as the first argument.
171563
+**
171564
+** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
171565
+** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
171566
+** occurs, an SQLite error code is returned and both output variables set
171567
+** to 0.
171568
+*/
171569
+static int sessionGenerateChangeset(
171570
+ sqlite3_session *pSession, /* Session object */
171571
+ int bPatchset, /* True for patchset, false for changeset */
171572
+ int (*xOutput)(void *pOut, const void *pData, int nData),
171573
+ void *pOut, /* First argument for xOutput */
171574
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171575
+ void **ppChangeset /* OUT: Buffer containing changeset */
171576
+){
171577
+ sqlite3 *db = pSession->db; /* Source database handle */
171578
+ SessionTable *pTab; /* Used to iterate through attached tables */
171579
+ SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
171580
+ int rc; /* Return code */
171581
+
171582
+ assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
171583
+
171584
+ /* Zero the output variables in case an error occurs. If this session
171585
+ ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
171586
+ ** this call will be a no-op. */
171587
+ if( xOutput==0 ){
171588
+ *pnChangeset = 0;
171589
+ *ppChangeset = 0;
171590
+ }
171591
+
171592
+ if( pSession->rc ) return pSession->rc;
171593
+ rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
171594
+ if( rc!=SQLITE_OK ) return rc;
171595
+
171596
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
171597
+
171598
+ for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
171599
+ if( pTab->nEntry ){
171600
+ const char *zName = pTab->zName;
171601
+ int nCol; /* Number of columns in table */
171602
+ u8 *abPK; /* Primary key array */
171603
+ const char **azCol = 0; /* Table columns */
171604
+ int i; /* Used to iterate through hash buckets */
171605
+ sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
171606
+ int nRewind = buf.nBuf; /* Initial size of write buffer */
171607
+ int nNoop; /* Size of buffer after writing tbl header */
171608
+
171609
+ /* Check the table schema is still Ok. */
171610
+ rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
171611
+ if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
171612
+ rc = SQLITE_SCHEMA;
171613
+ }
171614
+
171615
+ /* Write a table header */
171616
+ sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
171617
+
171618
+ /* Build and compile a statement to execute: */
171619
+ if( rc==SQLITE_OK ){
171620
+ rc = sessionSelectStmt(
171621
+ db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
171622
+ }
171623
+
171624
+ nNoop = buf.nBuf;
171625
+ for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
171626
+ SessionChange *p; /* Used to iterate through changes */
171627
+
171628
+ for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
171629
+ rc = sessionSelectBind(pSel, nCol, abPK, p);
171630
+ if( rc!=SQLITE_OK ) continue;
171631
+ if( sqlite3_step(pSel)==SQLITE_ROW ){
171632
+ if( p->op==SQLITE_INSERT ){
171633
+ int iCol;
171634
+ sessionAppendByte(&buf, SQLITE_INSERT, &rc);
171635
+ sessionAppendByte(&buf, p->bIndirect, &rc);
171636
+ for(iCol=0; iCol<nCol; iCol++){
171637
+ sessionAppendCol(&buf, pSel, iCol, &rc);
171638
+ }
171639
+ }else{
171640
+ rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
171641
+ }
171642
+ }else if( p->op!=SQLITE_INSERT ){
171643
+ rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
171644
+ }
171645
+ if( rc==SQLITE_OK ){
171646
+ rc = sqlite3_reset(pSel);
171647
+ }
171648
+
171649
+ /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
171650
+ ** its contents to the xOutput() callback. */
171651
+ if( xOutput
171652
+ && rc==SQLITE_OK
171653
+ && buf.nBuf>nNoop
171654
+ && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
171655
+ ){
171656
+ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171657
+ nNoop = -1;
171658
+ buf.nBuf = 0;
171659
+ }
171660
+
171661
+ }
171662
+ }
171663
+
171664
+ sqlite3_finalize(pSel);
171665
+ if( buf.nBuf==nNoop ){
171666
+ buf.nBuf = nRewind;
171667
+ }
171668
+ sqlite3_free((char*)azCol); /* cast works around VC++ bug */
171669
+ }
171670
+ }
171671
+
171672
+ if( rc==SQLITE_OK ){
171673
+ if( xOutput==0 ){
171674
+ *pnChangeset = buf.nBuf;
171675
+ *ppChangeset = buf.aBuf;
171676
+ buf.aBuf = 0;
171677
+ }else if( buf.nBuf>0 ){
171678
+ rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171679
+ }
171680
+ }
171681
+
171682
+ sqlite3_free(buf.aBuf);
171683
+ sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
171684
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
171685
+ return rc;
171686
+}
171687
+
171688
+/*
171689
+** Obtain a changeset object containing all changes recorded by the
171690
+** session object passed as the first argument.
171691
+**
171692
+** It is the responsibility of the caller to eventually free the buffer
171693
+** using sqlite3_free().
171694
+*/
171695
+SQLITE_API int SQLITE_STDCALL sqlite3session_changeset(
171696
+ sqlite3_session *pSession, /* Session object */
171697
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171698
+ void **ppChangeset /* OUT: Buffer containing changeset */
171699
+){
171700
+ return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
171701
+}
171702
+
171703
+/*
171704
+** Streaming version of sqlite3session_changeset().
171705
+*/
171706
+SQLITE_API int SQLITE_STDCALL sqlite3session_changeset_strm(
171707
+ sqlite3_session *pSession,
171708
+ int (*xOutput)(void *pOut, const void *pData, int nData),
171709
+ void *pOut
171710
+){
171711
+ return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
171712
+}
171713
+
171714
+/*
171715
+** Streaming version of sqlite3session_patchset().
171716
+*/
171717
+SQLITE_API int SQLITE_STDCALL sqlite3session_patchset_strm(
171718
+ sqlite3_session *pSession,
171719
+ int (*xOutput)(void *pOut, const void *pData, int nData),
171720
+ void *pOut
171721
+){
171722
+ return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
171723
+}
171724
+
171725
+/*
171726
+** Obtain a patchset object containing all changes recorded by the
171727
+** session object passed as the first argument.
171728
+**
171729
+** It is the responsibility of the caller to eventually free the buffer
171730
+** using sqlite3_free().
171731
+*/
171732
+SQLITE_API int SQLITE_STDCALL sqlite3session_patchset(
171733
+ sqlite3_session *pSession, /* Session object */
171734
+ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
171735
+ void **ppPatchset /* OUT: Buffer containing changeset */
171736
+){
171737
+ return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
171738
+}
171739
+
171740
+/*
171741
+** Enable or disable the session object passed as the first argument.
171742
+*/
171743
+SQLITE_API int SQLITE_STDCALL sqlite3session_enable(sqlite3_session *pSession, int bEnable){
171744
+ int ret;
171745
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171746
+ if( bEnable>=0 ){
171747
+ pSession->bEnable = bEnable;
171748
+ }
171749
+ ret = pSession->bEnable;
171750
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171751
+ return ret;
171752
+}
171753
+
171754
+/*
171755
+** Enable or disable the session object passed as the first argument.
171756
+*/
171757
+SQLITE_API int SQLITE_STDCALL sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
171758
+ int ret;
171759
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171760
+ if( bIndirect>=0 ){
171761
+ pSession->bIndirect = bIndirect;
171762
+ }
171763
+ ret = pSession->bIndirect;
171764
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171765
+ return ret;
171766
+}
171767
+
171768
+/*
171769
+** Return true if there have been no changes to monitored tables recorded
171770
+** by the session object passed as the only argument.
171771
+*/
171772
+SQLITE_API int SQLITE_STDCALL sqlite3session_isempty(sqlite3_session *pSession){
171773
+ int ret = 0;
171774
+ SessionTable *pTab;
171775
+
171776
+ sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171777
+ for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
171778
+ ret = (pTab->nEntry>0);
171779
+ }
171780
+ sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171781
+
171782
+ return (ret==0);
171783
+}
171784
+
171785
+/*
171786
+** Do the work for either sqlite3changeset_start() or start_strm().
171787
+*/
171788
+static int sessionChangesetStart(
171789
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171790
+ int (*xInput)(void *pIn, void *pData, int *pnData),
171791
+ void *pIn,
171792
+ int nChangeset, /* Size of buffer pChangeset in bytes */
171793
+ void *pChangeset /* Pointer to buffer containing changeset */
171794
+){
171795
+ sqlite3_changeset_iter *pRet; /* Iterator to return */
171796
+ int nByte; /* Number of bytes to allocate for iterator */
171797
+
171798
+ assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
171799
+
171800
+ /* Zero the output variable in case an error occurs. */
171801
+ *pp = 0;
171802
+
171803
+ /* Allocate and initialize the iterator structure. */
171804
+ nByte = sizeof(sqlite3_changeset_iter);
171805
+ pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
171806
+ if( !pRet ) return SQLITE_NOMEM;
171807
+ memset(pRet, 0, sizeof(sqlite3_changeset_iter));
171808
+ pRet->in.aData = (u8 *)pChangeset;
171809
+ pRet->in.nData = nChangeset;
171810
+ pRet->in.xInput = xInput;
171811
+ pRet->in.pIn = pIn;
171812
+ pRet->in.bEof = (xInput ? 0 : 1);
171813
+
171814
+ /* Populate the output variable and return success. */
171815
+ *pp = pRet;
171816
+ return SQLITE_OK;
171817
+}
171818
+
171819
+/*
171820
+** Create an iterator used to iterate through the contents of a changeset.
171821
+*/
171822
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_start(
171823
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171824
+ int nChangeset, /* Size of buffer pChangeset in bytes */
171825
+ void *pChangeset /* Pointer to buffer containing changeset */
171826
+){
171827
+ return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
171828
+}
171829
+
171830
+/*
171831
+** Streaming version of sqlite3changeset_start().
171832
+*/
171833
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_start_strm(
171834
+ sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171835
+ int (*xInput)(void *pIn, void *pData, int *pnData),
171836
+ void *pIn
171837
+){
171838
+ return sessionChangesetStart(pp, xInput, pIn, 0, 0);
171839
+}
171840
+
171841
+/*
171842
+** If the SessionInput object passed as the only argument is a streaming
171843
+** object and the buffer is full, discard some data to free up space.
171844
+*/
171845
+static void sessionDiscardData(SessionInput *pIn){
171846
+ if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
171847
+ int nMove = pIn->buf.nBuf - pIn->iNext;
171848
+ assert( nMove>=0 );
171849
+ if( nMove>0 ){
171850
+ memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
171851
+ }
171852
+ pIn->buf.nBuf -= pIn->iNext;
171853
+ pIn->iNext = 0;
171854
+ pIn->nData = pIn->buf.nBuf;
171855
+ }
171856
+}
171857
+
171858
+/*
171859
+** Ensure that there are at least nByte bytes available in the buffer. Or,
171860
+** if there are not nByte bytes remaining in the input, that all available
171861
+** data is in the buffer.
171862
+**
171863
+** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
171864
+*/
171865
+static int sessionInputBuffer(SessionInput *pIn, int nByte){
171866
+ int rc = SQLITE_OK;
171867
+ if( pIn->xInput ){
171868
+ while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
171869
+ int nNew = SESSIONS_STRM_CHUNK_SIZE;
171870
+
171871
+ if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
171872
+ if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
171873
+ rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
171874
+ if( nNew==0 ){
171875
+ pIn->bEof = 1;
171876
+ }else{
171877
+ pIn->buf.nBuf += nNew;
171878
+ }
171879
+ }
171880
+
171881
+ pIn->aData = pIn->buf.aBuf;
171882
+ pIn->nData = pIn->buf.nBuf;
171883
+ }
171884
+ }
171885
+ return rc;
171886
+}
171887
+
171888
+/*
171889
+** When this function is called, *ppRec points to the start of a record
171890
+** that contains nCol values. This function advances the pointer *ppRec
171891
+** until it points to the byte immediately following that record.
171892
+*/
171893
+static void sessionSkipRecord(
171894
+ u8 **ppRec, /* IN/OUT: Record pointer */
171895
+ int nCol /* Number of values in record */
171896
+){
171897
+ u8 *aRec = *ppRec;
171898
+ int i;
171899
+ for(i=0; i<nCol; i++){
171900
+ int eType = *aRec++;
171901
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171902
+ int nByte;
171903
+ aRec += sessionVarintGet((u8*)aRec, &nByte);
171904
+ aRec += nByte;
171905
+ }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171906
+ aRec += 8;
171907
+ }
171908
+ }
171909
+
171910
+ *ppRec = aRec;
171911
+}
171912
+
171913
+/*
171914
+** This function sets the value of the sqlite3_value object passed as the
171915
+** first argument to a copy of the string or blob held in the aData[]
171916
+** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
171917
+** error occurs.
171918
+*/
171919
+static int sessionValueSetStr(
171920
+ sqlite3_value *pVal, /* Set the value of this object */
171921
+ u8 *aData, /* Buffer containing string or blob data */
171922
+ int nData, /* Size of buffer aData[] in bytes */
171923
+ u8 enc /* String encoding (0 for blobs) */
171924
+){
171925
+ /* In theory this code could just pass SQLITE_TRANSIENT as the final
171926
+ ** argument to sqlite3ValueSetStr() and have the copy created
171927
+ ** automatically. But doing so makes it difficult to detect any OOM
171928
+ ** error. Hence the code to create the copy externally. */
171929
+ u8 *aCopy = sqlite3_malloc(nData+1);
171930
+ if( aCopy==0 ) return SQLITE_NOMEM;
171931
+ memcpy(aCopy, aData, nData);
171932
+ sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
171933
+ return SQLITE_OK;
171934
+}
171935
+
171936
+/*
171937
+** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
171938
+** for details.
171939
+**
171940
+** When this function is called, *paChange points to the start of the record
171941
+** to deserialize. Assuming no error occurs, *paChange is set to point to
171942
+** one byte after the end of the same record before this function returns.
171943
+** If the argument abPK is NULL, then the record contains nCol values. Or,
171944
+** if abPK is other than NULL, then the record contains only the PK fields
171945
+** (in other words, it is a patchset DELETE record).
171946
+**
171947
+** If successful, each element of the apOut[] array (allocated by the caller)
171948
+** is set to point to an sqlite3_value object containing the value read
171949
+** from the corresponding position in the record. If that value is not
171950
+** included in the record (i.e. because the record is part of an UPDATE change
171951
+** and the field was not modified), the corresponding element of apOut[] is
171952
+** set to NULL.
171953
+**
171954
+** It is the responsibility of the caller to free all sqlite_value structures
171955
+** using sqlite3_free().
171956
+**
171957
+** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
171958
+** The apOut[] array may have been partially populated in this case.
171959
+*/
171960
+static int sessionReadRecord(
171961
+ SessionInput *pIn, /* Input data */
171962
+ int nCol, /* Number of values in record */
171963
+ u8 *abPK, /* Array of primary key flags, or NULL */
171964
+ sqlite3_value **apOut /* Write values to this array */
171965
+){
171966
+ int i; /* Used to iterate through columns */
171967
+ int rc = SQLITE_OK;
171968
+
171969
+ for(i=0; i<nCol && rc==SQLITE_OK; i++){
171970
+ int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
171971
+ if( abPK && abPK[i]==0 ) continue;
171972
+ rc = sessionInputBuffer(pIn, 9);
171973
+ if( rc==SQLITE_OK ){
171974
+ eType = pIn->aData[pIn->iNext++];
171975
+ }
171976
+
171977
+ assert( apOut[i]==0 );
171978
+ if( eType ){
171979
+ apOut[i] = sqlite3ValueNew(0);
171980
+ if( !apOut[i] ) rc = SQLITE_NOMEM;
171981
+ }
171982
+
171983
+ if( rc==SQLITE_OK ){
171984
+ u8 *aVal = &pIn->aData[pIn->iNext];
171985
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171986
+ int nByte;
171987
+ pIn->iNext += sessionVarintGet(aVal, &nByte);
171988
+ rc = sessionInputBuffer(pIn, nByte);
171989
+ if( rc==SQLITE_OK ){
171990
+ u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
171991
+ rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
171992
+ }
171993
+ pIn->iNext += nByte;
171994
+ }
171995
+ if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171996
+ sqlite3_int64 v = sessionGetI64(aVal);
171997
+ if( eType==SQLITE_INTEGER ){
171998
+ sqlite3VdbeMemSetInt64(apOut[i], v);
171999
+ }else{
172000
+ double d;
172001
+ memcpy(&d, &v, 8);
172002
+ sqlite3VdbeMemSetDouble(apOut[i], d);
172003
+ }
172004
+ pIn->iNext += 8;
172005
+ }
172006
+ }
172007
+ }
172008
+
172009
+ return rc;
172010
+}
172011
+
172012
+/*
172013
+** The input pointer currently points to the second byte of a table-header.
172014
+** Specifically, to the following:
172015
+**
172016
+** + number of columns in table (varint)
172017
+** + array of PK flags (1 byte per column),
172018
+** + table name (nul terminated).
172019
+**
172020
+** This function ensures that all of the above is present in the input
172021
+** buffer (i.e. that it can be accessed without any calls to xInput()).
172022
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
172023
+** The input pointer is not moved.
172024
+*/
172025
+static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
172026
+ int rc = SQLITE_OK;
172027
+ int nCol = 0;
172028
+ int nRead = 0;
172029
+
172030
+ rc = sessionInputBuffer(pIn, 9);
172031
+ if( rc==SQLITE_OK ){
172032
+ nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
172033
+ rc = sessionInputBuffer(pIn, nRead+nCol+100);
172034
+ nRead += nCol;
172035
+ }
172036
+
172037
+ while( rc==SQLITE_OK ){
172038
+ while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
172039
+ nRead++;
172040
+ }
172041
+ if( (pIn->iNext + nRead)<pIn->nData ) break;
172042
+ rc = sessionInputBuffer(pIn, nRead + 100);
172043
+ }
172044
+ *pnByte = nRead+1;
172045
+ return rc;
172046
+}
172047
+
172048
+/*
172049
+** The input pointer currently points to the first byte of the first field
172050
+** of a record consisting of nCol columns. This function ensures the entire
172051
+** record is buffered. It does not move the input pointer.
172052
+**
172053
+** If successful, SQLITE_OK is returned and *pnByte is set to the size of
172054
+** the record in bytes. Otherwise, an SQLite error code is returned. The
172055
+** final value of *pnByte is undefined in this case.
172056
+*/
172057
+static int sessionChangesetBufferRecord(
172058
+ SessionInput *pIn, /* Input data */
172059
+ int nCol, /* Number of columns in record */
172060
+ int *pnByte /* OUT: Size of record in bytes */
172061
+){
172062
+ int rc = SQLITE_OK;
172063
+ int nByte = 0;
172064
+ int i;
172065
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
172066
+ int eType;
172067
+ rc = sessionInputBuffer(pIn, nByte + 10);
172068
+ if( rc==SQLITE_OK ){
172069
+ eType = pIn->aData[pIn->iNext + nByte++];
172070
+ if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172071
+ int n;
172072
+ nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
172073
+ nByte += n;
172074
+ rc = sessionInputBuffer(pIn, nByte);
172075
+ }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172076
+ nByte += 8;
172077
+ }
172078
+ }
172079
+ }
172080
+ *pnByte = nByte;
172081
+ return rc;
172082
+}
172083
+
172084
+/*
172085
+** The input pointer currently points to the second byte of a table-header.
172086
+** Specifically, to the following:
172087
+**
172088
+** + number of columns in table (varint)
172089
+** + array of PK flags (1 byte per column),
172090
+** + table name (nul terminated).
172091
+**
172092
+** This function decodes the table-header and populates the p->nCol,
172093
+** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
172094
+** also allocated or resized according to the new value of p->nCol. The
172095
+** input pointer is left pointing to the byte following the table header.
172096
+**
172097
+** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
172098
+** is returned and the final values of the various fields enumerated above
172099
+** are undefined.
172100
+*/
172101
+static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
172102
+ int rc;
172103
+ int nCopy;
172104
+ assert( p->rc==SQLITE_OK );
172105
+
172106
+ rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
172107
+ if( rc==SQLITE_OK ){
172108
+ int nByte;
172109
+ int nVarint;
172110
+ nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
172111
+ nCopy -= nVarint;
172112
+ p->in.iNext += nVarint;
172113
+ nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
172114
+ p->tblhdr.nBuf = 0;
172115
+ sessionBufferGrow(&p->tblhdr, nByte, &rc);
172116
+ }
172117
+
172118
+ if( rc==SQLITE_OK ){
172119
+ int iPK = sizeof(sqlite3_value*)*p->nCol*2;
172120
+ memset(p->tblhdr.aBuf, 0, iPK);
172121
+ memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
172122
+ p->in.iNext += nCopy;
172123
+ }
172124
+
172125
+ p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
172126
+ p->abPK = (u8*)&p->apValue[p->nCol*2];
172127
+ p->zTab = (char*)&p->abPK[p->nCol];
172128
+ return (p->rc = rc);
172129
+}
172130
+
172131
+/*
172132
+** Advance the changeset iterator to the next change.
172133
+**
172134
+** If both paRec and pnRec are NULL, then this function works like the public
172135
+** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
172136
+** sqlite3changeset_new() and old() APIs may be used to query for values.
172137
+**
172138
+** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
172139
+** record is written to *paRec before returning and the number of bytes in
172140
+** the record to *pnRec.
172141
+**
172142
+** Either way, this function returns SQLITE_ROW if the iterator is
172143
+** successfully advanced to the next change in the changeset, an SQLite
172144
+** error code if an error occurs, or SQLITE_DONE if there are no further
172145
+** changes in the changeset.
172146
+*/
172147
+static int sessionChangesetNext(
172148
+ sqlite3_changeset_iter *p, /* Changeset iterator */
172149
+ u8 **paRec, /* If non-NULL, store record pointer here */
172150
+ int *pnRec /* If non-NULL, store size of record here */
172151
+){
172152
+ int i;
172153
+ u8 op;
172154
+
172155
+ assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
172156
+
172157
+ /* If the iterator is in the error-state, return immediately. */
172158
+ if( p->rc!=SQLITE_OK ) return p->rc;
172159
+
172160
+ /* Free the current contents of p->apValue[], if any. */
172161
+ if( p->apValue ){
172162
+ for(i=0; i<p->nCol*2; i++){
172163
+ sqlite3ValueFree(p->apValue[i]);
172164
+ }
172165
+ memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
172166
+ }
172167
+
172168
+ /* Make sure the buffer contains at least 10 bytes of input data, or all
172169
+ ** remaining data if there are less than 10 bytes available. This is
172170
+ ** sufficient either for the 'T' or 'P' byte and the varint that follows
172171
+ ** it, or for the two single byte values otherwise. */
172172
+ p->rc = sessionInputBuffer(&p->in, 2);
172173
+ if( p->rc!=SQLITE_OK ) return p->rc;
172174
+
172175
+ /* If the iterator is already at the end of the changeset, return DONE. */
172176
+ if( p->in.iNext>=p->in.nData ){
172177
+ return SQLITE_DONE;
172178
+ }
172179
+
172180
+ sessionDiscardData(&p->in);
172181
+ p->in.iCurrent = p->in.iNext;
172182
+
172183
+ op = p->in.aData[p->in.iNext++];
172184
+ if( op=='T' || op=='P' ){
172185
+ p->bPatchset = (op=='P');
172186
+ if( sessionChangesetReadTblhdr(p) ) return p->rc;
172187
+ if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
172188
+ p->in.iCurrent = p->in.iNext;
172189
+ op = p->in.aData[p->in.iNext++];
172190
+ }
172191
+
172192
+ p->op = op;
172193
+ p->bIndirect = p->in.aData[p->in.iNext++];
172194
+ if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
172195
+ return (p->rc = SQLITE_CORRUPT_BKPT);
172196
+ }
172197
+
172198
+ if( paRec ){
172199
+ int nVal; /* Number of values to buffer */
172200
+ if( p->bPatchset==0 && op==SQLITE_UPDATE ){
172201
+ nVal = p->nCol * 2;
172202
+ }else if( p->bPatchset && op==SQLITE_DELETE ){
172203
+ nVal = 0;
172204
+ for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
172205
+ }else{
172206
+ nVal = p->nCol;
172207
+ }
172208
+ p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
172209
+ if( p->rc!=SQLITE_OK ) return p->rc;
172210
+ *paRec = &p->in.aData[p->in.iNext];
172211
+ p->in.iNext += *pnRec;
172212
+ }else{
172213
+
172214
+ /* If this is an UPDATE or DELETE, read the old.* record. */
172215
+ if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
172216
+ u8 *abPK = p->bPatchset ? p->abPK : 0;
172217
+ p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
172218
+ if( p->rc!=SQLITE_OK ) return p->rc;
172219
+ }
172220
+
172221
+ /* If this is an INSERT or UPDATE, read the new.* record. */
172222
+ if( p->op!=SQLITE_DELETE ){
172223
+ p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
172224
+ if( p->rc!=SQLITE_OK ) return p->rc;
172225
+ }
172226
+
172227
+ if( p->bPatchset && p->op==SQLITE_UPDATE ){
172228
+ /* If this is an UPDATE that is part of a patchset, then all PK and
172229
+ ** modified fields are present in the new.* record. The old.* record
172230
+ ** is currently completely empty. This block shifts the PK fields from
172231
+ ** new.* to old.*, to accommodate the code that reads these arrays. */
172232
+ for(i=0; i<p->nCol; i++){
172233
+ assert( p->apValue[i]==0 );
172234
+ assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
172235
+ if( p->abPK[i] ){
172236
+ p->apValue[i] = p->apValue[i+p->nCol];
172237
+ p->apValue[i+p->nCol] = 0;
172238
+ }
172239
+ }
172240
+ }
172241
+ }
172242
+
172243
+ return SQLITE_ROW;
172244
+}
172245
+
172246
+/*
172247
+** Advance an iterator created by sqlite3changeset_start() to the next
172248
+** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
172249
+** or SQLITE_CORRUPT.
172250
+**
172251
+** This function may not be called on iterators passed to a conflict handler
172252
+** callback by changeset_apply().
172253
+*/
172254
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_next(sqlite3_changeset_iter *p){
172255
+ return sessionChangesetNext(p, 0, 0);
172256
+}
172257
+
172258
+/*
172259
+** The following function extracts information on the current change
172260
+** from a changeset iterator. It may only be called after changeset_next()
172261
+** has returned SQLITE_ROW.
172262
+*/
172263
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_op(
172264
+ sqlite3_changeset_iter *pIter, /* Iterator handle */
172265
+ const char **pzTab, /* OUT: Pointer to table name */
172266
+ int *pnCol, /* OUT: Number of columns in table */
172267
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
172268
+ int *pbIndirect /* OUT: True if change is indirect */
172269
+){
172270
+ *pOp = pIter->op;
172271
+ *pnCol = pIter->nCol;
172272
+ *pzTab = pIter->zTab;
172273
+ if( pbIndirect ) *pbIndirect = pIter->bIndirect;
172274
+ return SQLITE_OK;
172275
+}
172276
+
172277
+/*
172278
+** Return information regarding the PRIMARY KEY and number of columns in
172279
+** the database table affected by the change that pIter currently points
172280
+** to. This function may only be called after changeset_next() returns
172281
+** SQLITE_ROW.
172282
+*/
172283
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_pk(
172284
+ sqlite3_changeset_iter *pIter, /* Iterator object */
172285
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
172286
+ int *pnCol /* OUT: Number of entries in output array */
172287
+){
172288
+ *pabPK = pIter->abPK;
172289
+ if( pnCol ) *pnCol = pIter->nCol;
172290
+ return SQLITE_OK;
172291
+}
172292
+
172293
+/*
172294
+** This function may only be called while the iterator is pointing to an
172295
+** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
172296
+** Otherwise, SQLITE_MISUSE is returned.
172297
+**
172298
+** It sets *ppValue to point to an sqlite3_value structure containing the
172299
+** iVal'th value in the old.* record. Or, if that particular value is not
172300
+** included in the record (because the change is an UPDATE and the field
172301
+** was not modified and is not a PK column), set *ppValue to NULL.
172302
+**
172303
+** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172304
+** not modified. Otherwise, SQLITE_OK.
172305
+*/
172306
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_old(
172307
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
172308
+ int iVal, /* Index of old.* value to retrieve */
172309
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
172310
+){
172311
+ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
172312
+ return SQLITE_MISUSE;
172313
+ }
172314
+ if( iVal<0 || iVal>=pIter->nCol ){
172315
+ return SQLITE_RANGE;
172316
+ }
172317
+ *ppValue = pIter->apValue[iVal];
172318
+ return SQLITE_OK;
172319
+}
172320
+
172321
+/*
172322
+** This function may only be called while the iterator is pointing to an
172323
+** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
172324
+** Otherwise, SQLITE_MISUSE is returned.
172325
+**
172326
+** It sets *ppValue to point to an sqlite3_value structure containing the
172327
+** iVal'th value in the new.* record. Or, if that particular value is not
172328
+** included in the record (because the change is an UPDATE and the field
172329
+** was not modified), set *ppValue to NULL.
172330
+**
172331
+** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172332
+** not modified. Otherwise, SQLITE_OK.
172333
+*/
172334
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_new(
172335
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
172336
+ int iVal, /* Index of new.* value to retrieve */
172337
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
172338
+){
172339
+ if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
172340
+ return SQLITE_MISUSE;
172341
+ }
172342
+ if( iVal<0 || iVal>=pIter->nCol ){
172343
+ return SQLITE_RANGE;
172344
+ }
172345
+ *ppValue = pIter->apValue[pIter->nCol+iVal];
172346
+ return SQLITE_OK;
172347
+}
172348
+
172349
+/*
172350
+** The following two macros are used internally. They are similar to the
172351
+** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
172352
+** they omit all error checking and return a pointer to the requested value.
172353
+*/
172354
+#define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
172355
+#define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
172356
+
172357
+/*
172358
+** This function may only be called with a changeset iterator that has been
172359
+** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
172360
+** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
172361
+**
172362
+** If successful, *ppValue is set to point to an sqlite3_value structure
172363
+** containing the iVal'th value of the conflicting record.
172364
+**
172365
+** If value iVal is out-of-range or some other error occurs, an SQLite error
172366
+** code is returned. Otherwise, SQLITE_OK.
172367
+*/
172368
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_conflict(
172369
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
172370
+ int iVal, /* Index of conflict record value to fetch */
172371
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
172372
+){
172373
+ if( !pIter->pConflict ){
172374
+ return SQLITE_MISUSE;
172375
+ }
172376
+ if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
172377
+ return SQLITE_RANGE;
172378
+ }
172379
+ *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
172380
+ return SQLITE_OK;
172381
+}
172382
+
172383
+/*
172384
+** This function may only be called with an iterator passed to an
172385
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
172386
+** it sets the output variable to the total number of known foreign key
172387
+** violations in the destination database and returns SQLITE_OK.
172388
+**
172389
+** In all other cases this function returns SQLITE_MISUSE.
172390
+*/
172391
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_fk_conflicts(
172392
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
172393
+ int *pnOut /* OUT: Number of FK violations */
172394
+){
172395
+ if( pIter->pConflict || pIter->apValue ){
172396
+ return SQLITE_MISUSE;
172397
+ }
172398
+ *pnOut = pIter->nCol;
172399
+ return SQLITE_OK;
172400
+}
172401
+
172402
+
172403
+/*
172404
+** Finalize an iterator allocated with sqlite3changeset_start().
172405
+**
172406
+** This function may not be called on iterators passed to a conflict handler
172407
+** callback by changeset_apply().
172408
+*/
172409
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_finalize(sqlite3_changeset_iter *p){
172410
+ int rc = SQLITE_OK;
172411
+ if( p ){
172412
+ int i; /* Used to iterate through p->apValue[] */
172413
+ rc = p->rc;
172414
+ if( p->apValue ){
172415
+ for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
172416
+ }
172417
+ sqlite3_free(p->tblhdr.aBuf);
172418
+ sqlite3_free(p->in.buf.aBuf);
172419
+ sqlite3_free(p);
172420
+ }
172421
+ return rc;
172422
+}
172423
+
172424
+static int sessionChangesetInvert(
172425
+ SessionInput *pInput, /* Input changeset */
172426
+ int (*xOutput)(void *pOut, const void *pData, int nData),
172427
+ void *pOut,
172428
+ int *pnInverted, /* OUT: Number of bytes in output changeset */
172429
+ void **ppInverted /* OUT: Inverse of pChangeset */
172430
+){
172431
+ int rc = SQLITE_OK; /* Return value */
172432
+ SessionBuffer sOut; /* Output buffer */
172433
+ int nCol = 0; /* Number of cols in current table */
172434
+ u8 *abPK = 0; /* PK array for current table */
172435
+ sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
172436
+ SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
172437
+
172438
+ /* Initialize the output buffer */
172439
+ memset(&sOut, 0, sizeof(SessionBuffer));
172440
+
172441
+ /* Zero the output variables in case an error occurs. */
172442
+ if( ppInverted ){
172443
+ *ppInverted = 0;
172444
+ *pnInverted = 0;
172445
+ }
172446
+
172447
+ while( 1 ){
172448
+ u8 eType;
172449
+
172450
+ /* Test for EOF. */
172451
+ if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
172452
+ if( pInput->iNext>=pInput->nData ) break;
172453
+ eType = pInput->aData[pInput->iNext];
172454
+
172455
+ switch( eType ){
172456
+ case 'T': {
172457
+ /* A 'table' record consists of:
172458
+ **
172459
+ ** * A constant 'T' character,
172460
+ ** * Number of columns in said table (a varint),
172461
+ ** * An array of nCol bytes (sPK),
172462
+ ** * A nul-terminated table name.
172463
+ */
172464
+ int nByte;
172465
+ int nVar;
172466
+ pInput->iNext++;
172467
+ if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
172468
+ goto finished_invert;
172469
+ }
172470
+ nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
172471
+ sPK.nBuf = 0;
172472
+ sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
172473
+ sessionAppendByte(&sOut, eType, &rc);
172474
+ sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172475
+ if( rc ) goto finished_invert;
172476
+
172477
+ pInput->iNext += nByte;
172478
+ sqlite3_free(apVal);
172479
+ apVal = 0;
172480
+ abPK = sPK.aBuf;
172481
+ break;
172482
+ }
172483
+
172484
+ case SQLITE_INSERT:
172485
+ case SQLITE_DELETE: {
172486
+ int nByte;
172487
+ int bIndirect = pInput->aData[pInput->iNext+1];
172488
+ int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
172489
+ pInput->iNext += 2;
172490
+ assert( rc==SQLITE_OK );
172491
+ rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
172492
+ sessionAppendByte(&sOut, eType2, &rc);
172493
+ sessionAppendByte(&sOut, bIndirect, &rc);
172494
+ sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172495
+ pInput->iNext += nByte;
172496
+ if( rc ) goto finished_invert;
172497
+ break;
172498
+ }
172499
+
172500
+ case SQLITE_UPDATE: {
172501
+ int iCol;
172502
+
172503
+ if( 0==apVal ){
172504
+ apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
172505
+ if( 0==apVal ){
172506
+ rc = SQLITE_NOMEM;
172507
+ goto finished_invert;
172508
+ }
172509
+ memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172510
+ }
172511
+
172512
+ /* Write the header for the new UPDATE change. Same as the original. */
172513
+ sessionAppendByte(&sOut, eType, &rc);
172514
+ sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
172515
+
172516
+ /* Read the old.* and new.* records for the update change. */
172517
+ pInput->iNext += 2;
172518
+ rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
172519
+ if( rc==SQLITE_OK ){
172520
+ rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
172521
+ }
172522
+
172523
+ /* Write the new old.* record. Consists of the PK columns from the
172524
+ ** original old.* record, and the other values from the original
172525
+ ** new.* record. */
172526
+ for(iCol=0; iCol<nCol; iCol++){
172527
+ sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
172528
+ sessionAppendValue(&sOut, pVal, &rc);
172529
+ }
172530
+
172531
+ /* Write the new new.* record. Consists of a copy of all values
172532
+ ** from the original old.* record, except for the PK columns, which
172533
+ ** are set to "undefined". */
172534
+ for(iCol=0; iCol<nCol; iCol++){
172535
+ sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
172536
+ sessionAppendValue(&sOut, pVal, &rc);
172537
+ }
172538
+
172539
+ for(iCol=0; iCol<nCol*2; iCol++){
172540
+ sqlite3ValueFree(apVal[iCol]);
172541
+ }
172542
+ memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172543
+ if( rc!=SQLITE_OK ){
172544
+ goto finished_invert;
172545
+ }
172546
+
172547
+ break;
172548
+ }
172549
+
172550
+ default:
172551
+ rc = SQLITE_CORRUPT_BKPT;
172552
+ goto finished_invert;
172553
+ }
172554
+
172555
+ assert( rc==SQLITE_OK );
172556
+ if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
172557
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172558
+ sOut.nBuf = 0;
172559
+ if( rc!=SQLITE_OK ) goto finished_invert;
172560
+ }
172561
+ }
172562
+
172563
+ assert( rc==SQLITE_OK );
172564
+ if( pnInverted ){
172565
+ *pnInverted = sOut.nBuf;
172566
+ *ppInverted = sOut.aBuf;
172567
+ sOut.aBuf = 0;
172568
+ }else if( sOut.nBuf>0 ){
172569
+ rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172570
+ }
172571
+
172572
+ finished_invert:
172573
+ sqlite3_free(sOut.aBuf);
172574
+ sqlite3_free(apVal);
172575
+ sqlite3_free(sPK.aBuf);
172576
+ return rc;
172577
+}
172578
+
172579
+
172580
+/*
172581
+** Invert a changeset object.
172582
+*/
172583
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert(
172584
+ int nChangeset, /* Number of bytes in input */
172585
+ const void *pChangeset, /* Input changeset */
172586
+ int *pnInverted, /* OUT: Number of bytes in output changeset */
172587
+ void **ppInverted /* OUT: Inverse of pChangeset */
172588
+){
172589
+ SessionInput sInput;
172590
+
172591
+ /* Set up the input stream */
172592
+ memset(&sInput, 0, sizeof(SessionInput));
172593
+ sInput.nData = nChangeset;
172594
+ sInput.aData = (u8*)pChangeset;
172595
+
172596
+ return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
172597
+}
172598
+
172599
+/*
172600
+** Streaming version of sqlite3changeset_invert().
172601
+*/
172602
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert_strm(
172603
+ int (*xInput)(void *pIn, void *pData, int *pnData),
172604
+ void *pIn,
172605
+ int (*xOutput)(void *pOut, const void *pData, int nData),
172606
+ void *pOut
172607
+){
172608
+ SessionInput sInput;
172609
+ int rc;
172610
+
172611
+ /* Set up the input stream */
172612
+ memset(&sInput, 0, sizeof(SessionInput));
172613
+ sInput.xInput = xInput;
172614
+ sInput.pIn = pIn;
172615
+
172616
+ rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
172617
+ sqlite3_free(sInput.buf.aBuf);
172618
+ return rc;
172619
+}
172620
+
172621
+typedef struct SessionApplyCtx SessionApplyCtx;
172622
+struct SessionApplyCtx {
172623
+ sqlite3 *db;
172624
+ sqlite3_stmt *pDelete; /* DELETE statement */
172625
+ sqlite3_stmt *pUpdate; /* UPDATE statement */
172626
+ sqlite3_stmt *pInsert; /* INSERT statement */
172627
+ sqlite3_stmt *pSelect; /* SELECT statement */
172628
+ int nCol; /* Size of azCol[] and abPK[] arrays */
172629
+ const char **azCol; /* Array of column names */
172630
+ u8 *abPK; /* Boolean array - true if column is in PK */
172631
+
172632
+ int bDeferConstraints; /* True to defer constraints */
172633
+ SessionBuffer constraints; /* Deferred constraints are stored here */
172634
+};
172635
+
172636
+/*
172637
+** Formulate a statement to DELETE a row from database db. Assuming a table
172638
+** structure like this:
172639
+**
172640
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172641
+**
172642
+** The DELETE statement looks like this:
172643
+**
172644
+** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
172645
+**
172646
+** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
172647
+** matching b and d values, or 1 otherwise. The second case comes up if the
172648
+** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
172649
+**
172650
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
172651
+** pointing to the prepared version of the SQL statement.
172652
+*/
172653
+static int sessionDeleteRow(
172654
+ sqlite3 *db, /* Database handle */
172655
+ const char *zTab, /* Table name */
172656
+ SessionApplyCtx *p /* Session changeset-apply context */
172657
+){
172658
+ int i;
172659
+ const char *zSep = "";
172660
+ int rc = SQLITE_OK;
172661
+ SessionBuffer buf = {0, 0, 0};
172662
+ int nPk = 0;
172663
+
172664
+ sessionAppendStr(&buf, "DELETE FROM ", &rc);
172665
+ sessionAppendIdent(&buf, zTab, &rc);
172666
+ sessionAppendStr(&buf, " WHERE ", &rc);
172667
+
172668
+ for(i=0; i<p->nCol; i++){
172669
+ if( p->abPK[i] ){
172670
+ nPk++;
172671
+ sessionAppendStr(&buf, zSep, &rc);
172672
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172673
+ sessionAppendStr(&buf, " = ?", &rc);
172674
+ sessionAppendInteger(&buf, i+1, &rc);
172675
+ zSep = " AND ";
172676
+ }
172677
+ }
172678
+
172679
+ if( nPk<p->nCol ){
172680
+ sessionAppendStr(&buf, " AND (?", &rc);
172681
+ sessionAppendInteger(&buf, p->nCol+1, &rc);
172682
+ sessionAppendStr(&buf, " OR ", &rc);
172683
+
172684
+ zSep = "";
172685
+ for(i=0; i<p->nCol; i++){
172686
+ if( !p->abPK[i] ){
172687
+ sessionAppendStr(&buf, zSep, &rc);
172688
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172689
+ sessionAppendStr(&buf, " IS ?", &rc);
172690
+ sessionAppendInteger(&buf, i+1, &rc);
172691
+ zSep = "AND ";
172692
+ }
172693
+ }
172694
+ sessionAppendStr(&buf, ")", &rc);
172695
+ }
172696
+
172697
+ if( rc==SQLITE_OK ){
172698
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
172699
+ }
172700
+ sqlite3_free(buf.aBuf);
172701
+
172702
+ return rc;
172703
+}
172704
+
172705
+/*
172706
+** Formulate and prepare a statement to UPDATE a row from database db.
172707
+** Assuming a table structure like this:
172708
+**
172709
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172710
+**
172711
+** The UPDATE statement looks like this:
172712
+**
172713
+** UPDATE x SET
172714
+** a = CASE WHEN ?2 THEN ?3 ELSE a END,
172715
+** b = CASE WHEN ?5 THEN ?6 ELSE b END,
172716
+** c = CASE WHEN ?8 THEN ?9 ELSE c END,
172717
+** d = CASE WHEN ?11 THEN ?12 ELSE d END
172718
+** WHERE a = ?1 AND c = ?7 AND (?13 OR
172719
+** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
172720
+** )
172721
+**
172722
+** For each column in the table, there are three variables to bind:
172723
+**
172724
+** ?(i*3+1) The old.* value of the column, if any.
172725
+** ?(i*3+2) A boolean flag indicating that the value is being modified.
172726
+** ?(i*3+3) The new.* value of the column, if any.
172727
+**
172728
+** Also, a boolean flag that, if set to true, causes the statement to update
172729
+** a row even if the non-PK values do not match. This is required if the
172730
+** conflict-handler is invoked with CHANGESET_DATA and returns
172731
+** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
172732
+**
172733
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
172734
+** pointing to the prepared version of the SQL statement.
172735
+*/
172736
+static int sessionUpdateRow(
172737
+ sqlite3 *db, /* Database handle */
172738
+ const char *zTab, /* Table name */
172739
+ SessionApplyCtx *p /* Session changeset-apply context */
172740
+){
172741
+ int rc = SQLITE_OK;
172742
+ int i;
172743
+ const char *zSep = "";
172744
+ SessionBuffer buf = {0, 0, 0};
172745
+
172746
+ /* Append "UPDATE tbl SET " */
172747
+ sessionAppendStr(&buf, "UPDATE ", &rc);
172748
+ sessionAppendIdent(&buf, zTab, &rc);
172749
+ sessionAppendStr(&buf, " SET ", &rc);
172750
+
172751
+ /* Append the assignments */
172752
+ for(i=0; i<p->nCol; i++){
172753
+ sessionAppendStr(&buf, zSep, &rc);
172754
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172755
+ sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
172756
+ sessionAppendInteger(&buf, i*3+2, &rc);
172757
+ sessionAppendStr(&buf, " THEN ?", &rc);
172758
+ sessionAppendInteger(&buf, i*3+3, &rc);
172759
+ sessionAppendStr(&buf, " ELSE ", &rc);
172760
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172761
+ sessionAppendStr(&buf, " END", &rc);
172762
+ zSep = ", ";
172763
+ }
172764
+
172765
+ /* Append the PK part of the WHERE clause */
172766
+ sessionAppendStr(&buf, " WHERE ", &rc);
172767
+ for(i=0; i<p->nCol; i++){
172768
+ if( p->abPK[i] ){
172769
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172770
+ sessionAppendStr(&buf, " = ?", &rc);
172771
+ sessionAppendInteger(&buf, i*3+1, &rc);
172772
+ sessionAppendStr(&buf, " AND ", &rc);
172773
+ }
172774
+ }
172775
+
172776
+ /* Append the non-PK part of the WHERE clause */
172777
+ sessionAppendStr(&buf, " (?", &rc);
172778
+ sessionAppendInteger(&buf, p->nCol*3+1, &rc);
172779
+ sessionAppendStr(&buf, " OR 1", &rc);
172780
+ for(i=0; i<p->nCol; i++){
172781
+ if( !p->abPK[i] ){
172782
+ sessionAppendStr(&buf, " AND (?", &rc);
172783
+ sessionAppendInteger(&buf, i*3+2, &rc);
172784
+ sessionAppendStr(&buf, "=0 OR ", &rc);
172785
+ sessionAppendIdent(&buf, p->azCol[i], &rc);
172786
+ sessionAppendStr(&buf, " IS ?", &rc);
172787
+ sessionAppendInteger(&buf, i*3+1, &rc);
172788
+ sessionAppendStr(&buf, ")", &rc);
172789
+ }
172790
+ }
172791
+ sessionAppendStr(&buf, ")", &rc);
172792
+
172793
+ if( rc==SQLITE_OK ){
172794
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
172795
+ }
172796
+ sqlite3_free(buf.aBuf);
172797
+
172798
+ return rc;
172799
+}
172800
+
172801
+/*
172802
+** Formulate and prepare an SQL statement to query table zTab by primary
172803
+** key. Assuming the following table structure:
172804
+**
172805
+** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172806
+**
172807
+** The SELECT statement looks like this:
172808
+**
172809
+** SELECT * FROM x WHERE a = ?1 AND c = ?3
172810
+**
172811
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
172812
+** pointing to the prepared version of the SQL statement.
172813
+*/
172814
+static int sessionSelectRow(
172815
+ sqlite3 *db, /* Database handle */
172816
+ const char *zTab, /* Table name */
172817
+ SessionApplyCtx *p /* Session changeset-apply context */
172818
+){
172819
+ return sessionSelectStmt(
172820
+ db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
172821
+}
172822
+
172823
+/*
172824
+** Formulate and prepare an INSERT statement to add a record to table zTab.
172825
+** For example:
172826
+**
172827
+** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
172828
+**
172829
+** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
172830
+** pointing to the prepared version of the SQL statement.
172831
+*/
172832
+static int sessionInsertRow(
172833
+ sqlite3 *db, /* Database handle */
172834
+ const char *zTab, /* Table name */
172835
+ SessionApplyCtx *p /* Session changeset-apply context */
172836
+){
172837
+ int rc = SQLITE_OK;
172838
+ int i;
172839
+ SessionBuffer buf = {0, 0, 0};
172840
+
172841
+ sessionAppendStr(&buf, "INSERT INTO main.", &rc);
172842
+ sessionAppendIdent(&buf, zTab, &rc);
172843
+ sessionAppendStr(&buf, " VALUES(?", &rc);
172844
+ for(i=1; i<p->nCol; i++){
172845
+ sessionAppendStr(&buf, ", ?", &rc);
172846
+ }
172847
+ sessionAppendStr(&buf, ")", &rc);
172848
+
172849
+ if( rc==SQLITE_OK ){
172850
+ rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
172851
+ }
172852
+ sqlite3_free(buf.aBuf);
172853
+ return rc;
172854
+}
172855
+
172856
+/*
172857
+** A wrapper around sqlite3_bind_value() that detects an extra problem.
172858
+** See comments in the body of this function for details.
172859
+*/
172860
+static int sessionBindValue(
172861
+ sqlite3_stmt *pStmt, /* Statement to bind value to */
172862
+ int i, /* Parameter number to bind to */
172863
+ sqlite3_value *pVal /* Value to bind */
172864
+){
172865
+ int eType = sqlite3_value_type(pVal);
172866
+ /* COVERAGE: The (pVal->z==0) branch is never true using current versions
172867
+ ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
172868
+ ** the (pVal->z) variable remains as it was or the type of the value is
172869
+ ** set to SQLITE_NULL. */
172870
+ if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
172871
+ /* This condition occurs when an earlier OOM in a call to
172872
+ ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
172873
+ ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
172874
+ return SQLITE_NOMEM;
172875
+ }
172876
+ return sqlite3_bind_value(pStmt, i, pVal);
172877
+}
172878
+
172879
+/*
172880
+** Iterator pIter must point to an SQLITE_INSERT entry. This function
172881
+** transfers new.* values from the current iterator entry to statement
172882
+** pStmt. The table being inserted into has nCol columns.
172883
+**
172884
+** New.* value $i from the iterator is bound to variable ($i+1) of
172885
+** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
172886
+** are transfered to the statement. Otherwise, if abPK is not NULL, it points
172887
+** to an array nCol elements in size. In this case only those values for
172888
+** which abPK[$i] is true are read from the iterator and bound to the
172889
+** statement.
172890
+**
172891
+** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
172892
+*/
172893
+static int sessionBindRow(
172894
+ sqlite3_changeset_iter *pIter, /* Iterator to read values from */
172895
+ int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
172896
+ int nCol, /* Number of columns */
172897
+ u8 *abPK, /* If not NULL, bind only if true */
172898
+ sqlite3_stmt *pStmt /* Bind values to this statement */
172899
+){
172900
+ int i;
172901
+ int rc = SQLITE_OK;
172902
+
172903
+ /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
172904
+ ** argument iterator points to a suitable entry. Make sure that xValue
172905
+ ** is one of these to guarantee that it is safe to ignore the return
172906
+ ** in the code below. */
172907
+ assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
172908
+
172909
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
172910
+ if( !abPK || abPK[i] ){
172911
+ sqlite3_value *pVal;
172912
+ (void)xValue(pIter, i, &pVal);
172913
+ rc = sessionBindValue(pStmt, i+1, pVal);
172914
+ }
172915
+ }
172916
+ return rc;
172917
+}
172918
+
172919
+/*
172920
+** SQL statement pSelect is as generated by the sessionSelectRow() function.
172921
+** This function binds the primary key values from the change that changeset
172922
+** iterator pIter points to to the SELECT and attempts to seek to the table
172923
+** entry. If a row is found, the SELECT statement left pointing at the row
172924
+** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
172925
+** has occured, the statement is reset and SQLITE_OK is returned. If an
172926
+** error occurs, the statement is reset and an SQLite error code is returned.
172927
+**
172928
+** If this function returns SQLITE_ROW, the caller must eventually reset()
172929
+** statement pSelect. If any other value is returned, the statement does
172930
+** not require a reset().
172931
+**
172932
+** If the iterator currently points to an INSERT record, bind values from the
172933
+** new.* record to the SELECT statement. Or, if it points to a DELETE or
172934
+** UPDATE, bind values from the old.* record.
172935
+*/
172936
+static int sessionSeekToRow(
172937
+ sqlite3 *db, /* Database handle */
172938
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
172939
+ u8 *abPK, /* Primary key flags array */
172940
+ sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
172941
+){
172942
+ int rc; /* Return code */
172943
+ int nCol; /* Number of columns in table */
172944
+ int op; /* Changset operation (SQLITE_UPDATE etc.) */
172945
+ const char *zDummy; /* Unused */
172946
+
172947
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
172948
+ rc = sessionBindRow(pIter,
172949
+ op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
172950
+ nCol, abPK, pSelect
172951
+ );
172952
+
172953
+ if( rc==SQLITE_OK ){
172954
+ rc = sqlite3_step(pSelect);
172955
+ if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
172956
+ }
172957
+
172958
+ return rc;
172959
+}
172960
+
172961
+/*
172962
+** Invoke the conflict handler for the change that the changeset iterator
172963
+** currently points to.
172964
+**
172965
+** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
172966
+** If argument pbReplace is NULL, then the type of conflict handler invoked
172967
+** depends solely on eType, as follows:
172968
+**
172969
+** eType value Value passed to xConflict
172970
+** -------------------------------------------------
172971
+** CHANGESET_DATA CHANGESET_NOTFOUND
172972
+** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
172973
+**
172974
+** Or, if pbReplace is not NULL, then an attempt is made to find an existing
172975
+** record with the same primary key as the record about to be deleted, updated
172976
+** or inserted. If such a record can be found, it is available to the conflict
172977
+** handler as the "conflicting" record. In this case the type of conflict
172978
+** handler invoked is as follows:
172979
+**
172980
+** eType value PK Record found? Value passed to xConflict
172981
+** ----------------------------------------------------------------
172982
+** CHANGESET_DATA Yes CHANGESET_DATA
172983
+** CHANGESET_DATA No CHANGESET_NOTFOUND
172984
+** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
172985
+** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
172986
+**
172987
+** If pbReplace is not NULL, and a record with a matching PK is found, and
172988
+** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
172989
+** is set to non-zero before returning SQLITE_OK.
172990
+**
172991
+** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
172992
+** returned. Or, if the conflict handler returns an invalid value,
172993
+** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
172994
+** this function returns SQLITE_OK.
172995
+*/
172996
+static int sessionConflictHandler(
172997
+ int eType, /* Either CHANGESET_DATA or CONFLICT */
172998
+ SessionApplyCtx *p, /* changeset_apply() context */
172999
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
173000
+ int(*xConflict)(void *, int, sqlite3_changeset_iter*),
173001
+ void *pCtx, /* First argument for conflict handler */
173002
+ int *pbReplace /* OUT: Set to true if PK row is found */
173003
+){
173004
+ int res = 0; /* Value returned by conflict handler */
173005
+ int rc;
173006
+ int nCol;
173007
+ int op;
173008
+ const char *zDummy;
173009
+
173010
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173011
+
173012
+ assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
173013
+ assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
173014
+ assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
173015
+
173016
+ /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
173017
+ if( pbReplace ){
173018
+ rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
173019
+ }else{
173020
+ rc = SQLITE_OK;
173021
+ }
173022
+
173023
+ if( rc==SQLITE_ROW ){
173024
+ /* There exists another row with the new.* primary key. */
173025
+ pIter->pConflict = p->pSelect;
173026
+ res = xConflict(pCtx, eType, pIter);
173027
+ pIter->pConflict = 0;
173028
+ rc = sqlite3_reset(p->pSelect);
173029
+ }else if( rc==SQLITE_OK ){
173030
+ if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
173031
+ /* Instead of invoking the conflict handler, append the change blob
173032
+ ** to the SessionApplyCtx.constraints buffer. */
173033
+ u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
173034
+ int nBlob = pIter->in.iNext - pIter->in.iCurrent;
173035
+ sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
173036
+ res = SQLITE_CHANGESET_OMIT;
173037
+ }else{
173038
+ /* No other row with the new.* primary key. */
173039
+ res = xConflict(pCtx, eType+1, pIter);
173040
+ if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
173041
+ }
173042
+ }
173043
+
173044
+ if( rc==SQLITE_OK ){
173045
+ switch( res ){
173046
+ case SQLITE_CHANGESET_REPLACE:
173047
+ assert( pbReplace );
173048
+ *pbReplace = 1;
173049
+ break;
173050
+
173051
+ case SQLITE_CHANGESET_OMIT:
173052
+ break;
173053
+
173054
+ case SQLITE_CHANGESET_ABORT:
173055
+ rc = SQLITE_ABORT;
173056
+ break;
173057
+
173058
+ default:
173059
+ rc = SQLITE_MISUSE;
173060
+ break;
173061
+ }
173062
+ }
173063
+
173064
+ return rc;
173065
+}
173066
+
173067
+/*
173068
+** Attempt to apply the change that the iterator passed as the first argument
173069
+** currently points to to the database. If a conflict is encountered, invoke
173070
+** the conflict handler callback.
173071
+**
173072
+** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
173073
+** one is encountered, update or delete the row with the matching primary key
173074
+** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
173075
+** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
173076
+** to true before returning. In this case the caller will invoke this function
173077
+** again, this time with pbRetry set to NULL.
173078
+**
173079
+** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
173080
+** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
173081
+** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
173082
+** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
173083
+** before retrying. In this case the caller attempts to remove the conflicting
173084
+** row before invoking this function again, this time with pbReplace set
173085
+** to NULL.
173086
+**
173087
+** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
173088
+** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
173089
+** returned.
173090
+*/
173091
+static int sessionApplyOneOp(
173092
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
173093
+ SessionApplyCtx *p, /* changeset_apply() context */
173094
+ int(*xConflict)(void *, int, sqlite3_changeset_iter *),
173095
+ void *pCtx, /* First argument for the conflict handler */
173096
+ int *pbReplace, /* OUT: True to remove PK row and retry */
173097
+ int *pbRetry /* OUT: True to retry. */
173098
+){
173099
+ const char *zDummy;
173100
+ int op;
173101
+ int nCol;
173102
+ int rc = SQLITE_OK;
173103
+
173104
+ assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
173105
+ assert( p->azCol && p->abPK );
173106
+ assert( !pbReplace || *pbReplace==0 );
173107
+
173108
+ sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173109
+
173110
+ if( op==SQLITE_DELETE ){
173111
+
173112
+ /* Bind values to the DELETE statement. If conflict handling is required,
173113
+ ** bind values for all columns and set bound variable (nCol+1) to true.
173114
+ ** Or, if conflict handling is not required, bind just the PK column
173115
+ ** values and, if it exists, set (nCol+1) to false. Conflict handling
173116
+ ** is not required if:
173117
+ **
173118
+ ** * this is a patchset, or
173119
+ ** * (pbRetry==0), or
173120
+ ** * all columns of the table are PK columns (in this case there is
173121
+ ** no (nCol+1) variable to bind to).
173122
+ */
173123
+ u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
173124
+ rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
173125
+ if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
173126
+ rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
173127
+ }
173128
+ if( rc!=SQLITE_OK ) return rc;
173129
+
173130
+ sqlite3_step(p->pDelete);
173131
+ rc = sqlite3_reset(p->pDelete);
173132
+ if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173133
+ rc = sessionConflictHandler(
173134
+ SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173135
+ );
173136
+ }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173137
+ rc = sessionConflictHandler(
173138
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173139
+ );
173140
+ }
173141
+
173142
+ }else if( op==SQLITE_UPDATE ){
173143
+ int i;
173144
+
173145
+ /* Bind values to the UPDATE statement. */
173146
+ for(i=0; rc==SQLITE_OK && i<nCol; i++){
173147
+ sqlite3_value *pOld = sessionChangesetOld(pIter, i);
173148
+ sqlite3_value *pNew = sessionChangesetNew(pIter, i);
173149
+
173150
+ sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
173151
+ if( pOld ){
173152
+ rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
173153
+ }
173154
+ if( rc==SQLITE_OK && pNew ){
173155
+ rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
173156
+ }
173157
+ }
173158
+ if( rc==SQLITE_OK ){
173159
+ sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
173160
+ }
173161
+ if( rc!=SQLITE_OK ) return rc;
173162
+
173163
+ /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
173164
+ ** the result will be SQLITE_OK with 0 rows modified. */
173165
+ sqlite3_step(p->pUpdate);
173166
+ rc = sqlite3_reset(p->pUpdate);
173167
+
173168
+ if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173169
+ /* A NOTFOUND or DATA error. Search the table to see if it contains
173170
+ ** a row with a matching primary key. If so, this is a DATA conflict.
173171
+ ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
173172
+
173173
+ rc = sessionConflictHandler(
173174
+ SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173175
+ );
173176
+
173177
+ }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173178
+ /* This is always a CONSTRAINT conflict. */
173179
+ rc = sessionConflictHandler(
173180
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173181
+ );
173182
+ }
173183
+
173184
+ }else{
173185
+ assert( op==SQLITE_INSERT );
173186
+ rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
173187
+ if( rc!=SQLITE_OK ) return rc;
173188
+
173189
+ sqlite3_step(p->pInsert);
173190
+ rc = sqlite3_reset(p->pInsert);
173191
+ if( (rc&0xff)==SQLITE_CONSTRAINT ){
173192
+ rc = sessionConflictHandler(
173193
+ SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
173194
+ );
173195
+ }
173196
+ }
173197
+
173198
+ return rc;
173199
+}
173200
+
173201
+/*
173202
+** Attempt to apply the change that the iterator passed as the first argument
173203
+** currently points to to the database. If a conflict is encountered, invoke
173204
+** the conflict handler callback.
173205
+**
173206
+** The difference between this function and sessionApplyOne() is that this
173207
+** function handles the case where the conflict-handler is invoked and
173208
+** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
173209
+** retried in some manner.
173210
+*/
173211
+static int sessionApplyOneWithRetry(
173212
+ sqlite3 *db, /* Apply change to "main" db of this handle */
173213
+ sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
173214
+ SessionApplyCtx *pApply, /* Apply context */
173215
+ int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173216
+ void *pCtx /* First argument passed to xConflict */
173217
+){
173218
+ int bReplace = 0;
173219
+ int bRetry = 0;
173220
+ int rc;
173221
+
173222
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
173223
+ assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
173224
+
173225
+ /* If the bRetry flag is set, the change has not been applied due to an
173226
+ ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
173227
+ ** a row with the correct PK is present in the db, but one or more other
173228
+ ** fields do not contain the expected values) and the conflict handler
173229
+ ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
173230
+ ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
173231
+ ** the SQLITE_CHANGESET_DATA problem. */
173232
+ if( bRetry ){
173233
+ assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
173234
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173235
+ }
173236
+
173237
+ /* If the bReplace flag is set, the change is an INSERT that has not
173238
+ ** been performed because the database already contains a row with the
173239
+ ** specified primary key and the conflict handler returned
173240
+ ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
173241
+ ** before reattempting the INSERT. */
173242
+ else if( bReplace ){
173243
+ assert( pIter->op==SQLITE_INSERT );
173244
+ rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
173245
+ if( rc==SQLITE_OK ){
173246
+ rc = sessionBindRow(pIter,
173247
+ sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
173248
+ sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
173249
+ }
173250
+ if( rc==SQLITE_OK ){
173251
+ sqlite3_step(pApply->pDelete);
173252
+ rc = sqlite3_reset(pApply->pDelete);
173253
+ }
173254
+ if( rc==SQLITE_OK ){
173255
+ rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173256
+ }
173257
+ if( rc==SQLITE_OK ){
173258
+ rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
173259
+ }
173260
+ }
173261
+
173262
+ return rc;
173263
+}
173264
+
173265
+/*
173266
+** Retry the changes accumulated in the pApply->constraints buffer.
173267
+*/
173268
+static int sessionRetryConstraints(
173269
+ sqlite3 *db,
173270
+ int bPatchset,
173271
+ const char *zTab,
173272
+ SessionApplyCtx *pApply,
173273
+ int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173274
+ void *pCtx /* First argument passed to xConflict */
173275
+){
173276
+ int rc = SQLITE_OK;
173277
+
173278
+ while( pApply->constraints.nBuf ){
173279
+ sqlite3_changeset_iter *pIter2 = 0;
173280
+ SessionBuffer cons = pApply->constraints;
173281
+ memset(&pApply->constraints, 0, sizeof(SessionBuffer));
173282
+
173283
+ rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
173284
+ if( rc==SQLITE_OK ){
173285
+ int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
173286
+ int rc2;
173287
+ pIter2->bPatchset = bPatchset;
173288
+ pIter2->zTab = (char*)zTab;
173289
+ pIter2->nCol = pApply->nCol;
173290
+ pIter2->abPK = pApply->abPK;
173291
+ sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
173292
+ pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
173293
+ if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
173294
+
173295
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
173296
+ rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
173297
+ }
173298
+
173299
+ rc2 = sqlite3changeset_finalize(pIter2);
173300
+ if( rc==SQLITE_OK ) rc = rc2;
173301
+ }
173302
+ assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
173303
+
173304
+ sqlite3_free(cons.aBuf);
173305
+ if( rc!=SQLITE_OK ) break;
173306
+ if( pApply->constraints.nBuf>=cons.nBuf ){
173307
+ /* No progress was made on the last round. */
173308
+ pApply->bDeferConstraints = 0;
173309
+ }
173310
+ }
173311
+
173312
+ return rc;
173313
+}
173314
+
173315
+/*
173316
+** Argument pIter is a changeset iterator that has been initialized, but
173317
+** not yet passed to sqlite3changeset_next(). This function applies the
173318
+** changeset to the main database attached to handle "db". The supplied
173319
+** conflict handler callback is invoked to resolve any conflicts encountered
173320
+** while applying the change.
173321
+*/
173322
+static int sessionChangesetApply(
173323
+ sqlite3 *db, /* Apply change to "main" db of this handle */
173324
+ sqlite3_changeset_iter *pIter, /* Changeset to apply */
173325
+ int(*xFilter)(
173326
+ void *pCtx, /* Copy of sixth arg to _apply() */
173327
+ const char *zTab /* Table name */
173328
+ ),
173329
+ int(*xConflict)(
173330
+ void *pCtx, /* Copy of fifth arg to _apply() */
173331
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173332
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
173333
+ ),
173334
+ void *pCtx /* First argument passed to xConflict */
173335
+){
173336
+ int schemaMismatch = 0;
173337
+ int rc; /* Return code */
173338
+ const char *zTab = 0; /* Name of current table */
173339
+ int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
173340
+ SessionApplyCtx sApply; /* changeset_apply() context object */
173341
+ int bPatchset;
173342
+
173343
+ assert( xConflict!=0 );
173344
+
173345
+ pIter->in.bNoDiscard = 1;
173346
+ memset(&sApply, 0, sizeof(sApply));
173347
+ sqlite3_mutex_enter(sqlite3_db_mutex(db));
173348
+ rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
173349
+ if( rc==SQLITE_OK ){
173350
+ rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
173351
+ }
173352
+ while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
173353
+ int nCol;
173354
+ int op;
173355
+ const char *zNew;
173356
+
173357
+ sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
173358
+
173359
+ if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
173360
+ u8 *abPK;
173361
+
173362
+ rc = sessionRetryConstraints(
173363
+ db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
173364
+ );
173365
+ if( rc!=SQLITE_OK ) break;
173366
+
173367
+ sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173368
+ sqlite3_finalize(sApply.pDelete);
173369
+ sqlite3_finalize(sApply.pUpdate);
173370
+ sqlite3_finalize(sApply.pInsert);
173371
+ sqlite3_finalize(sApply.pSelect);
173372
+ memset(&sApply, 0, sizeof(sApply));
173373
+ sApply.db = db;
173374
+ sApply.bDeferConstraints = 1;
173375
+
173376
+ /* If an xFilter() callback was specified, invoke it now. If the
173377
+ ** xFilter callback returns zero, skip this table. If it returns
173378
+ ** non-zero, proceed. */
173379
+ schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
173380
+ if( schemaMismatch ){
173381
+ zTab = sqlite3_mprintf("%s", zNew);
173382
+ if( zTab==0 ){
173383
+ rc = SQLITE_NOMEM;
173384
+ break;
173385
+ }
173386
+ nTab = (int)strlen(zTab);
173387
+ sApply.azCol = (const char **)zTab;
173388
+ }else{
173389
+ sqlite3changeset_pk(pIter, &abPK, 0);
173390
+ rc = sessionTableInfo(
173391
+ db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
173392
+ );
173393
+ if( rc!=SQLITE_OK ) break;
173394
+
173395
+ if( sApply.nCol==0 ){
173396
+ schemaMismatch = 1;
173397
+ sqlite3_log(SQLITE_SCHEMA,
173398
+ "sqlite3changeset_apply(): no such table: %s", zTab
173399
+ );
173400
+ }
173401
+ else if( sApply.nCol!=nCol ){
173402
+ schemaMismatch = 1;
173403
+ sqlite3_log(SQLITE_SCHEMA,
173404
+ "sqlite3changeset_apply(): table %s has %d columns, expected %d",
173405
+ zTab, sApply.nCol, nCol
173406
+ );
173407
+ }
173408
+ else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
173409
+ schemaMismatch = 1;
173410
+ sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
173411
+ "primary key mismatch for table %s", zTab
173412
+ );
173413
+ }
173414
+ else if(
173415
+ (rc = sessionSelectRow(db, zTab, &sApply))
173416
+ || (rc = sessionUpdateRow(db, zTab, &sApply))
173417
+ || (rc = sessionDeleteRow(db, zTab, &sApply))
173418
+ || (rc = sessionInsertRow(db, zTab, &sApply))
173419
+ ){
173420
+ break;
173421
+ }
173422
+ nTab = sqlite3Strlen30(zTab);
173423
+ }
173424
+ }
173425
+
173426
+ /* If there is a schema mismatch on the current table, proceed to the
173427
+ ** next change. A log message has already been issued. */
173428
+ if( schemaMismatch ) continue;
173429
+
173430
+ rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
173431
+ }
173432
+
173433
+ bPatchset = pIter->bPatchset;
173434
+ if( rc==SQLITE_OK ){
173435
+ rc = sqlite3changeset_finalize(pIter);
173436
+ }else{
173437
+ sqlite3changeset_finalize(pIter);
173438
+ }
173439
+
173440
+ if( rc==SQLITE_OK ){
173441
+ rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
173442
+ }
173443
+
173444
+ if( rc==SQLITE_OK ){
173445
+ int nFk, notUsed;
173446
+ sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
173447
+ if( nFk!=0 ){
173448
+ int res = SQLITE_CHANGESET_ABORT;
173449
+ sqlite3_changeset_iter sIter;
173450
+ memset(&sIter, 0, sizeof(sIter));
173451
+ sIter.nCol = nFk;
173452
+ res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
173453
+ if( res!=SQLITE_CHANGESET_OMIT ){
173454
+ rc = SQLITE_CONSTRAINT;
173455
+ }
173456
+ }
173457
+ }
173458
+ sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
173459
+
173460
+ if( rc==SQLITE_OK ){
173461
+ rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173462
+ }else{
173463
+ sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
173464
+ sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173465
+ }
173466
+
173467
+ sqlite3_finalize(sApply.pInsert);
173468
+ sqlite3_finalize(sApply.pDelete);
173469
+ sqlite3_finalize(sApply.pUpdate);
173470
+ sqlite3_finalize(sApply.pSelect);
173471
+ sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173472
+ sqlite3_free((char*)sApply.constraints.aBuf);
173473
+ sqlite3_mutex_leave(sqlite3_db_mutex(db));
173474
+ return rc;
173475
+}
173476
+
173477
+/*
173478
+** Apply the changeset passed via pChangeset/nChangeset to the main database
173479
+** attached to handle "db". Invoke the supplied conflict handler callback
173480
+** to resolve any conflicts encountered while applying the change.
173481
+*/
173482
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply(
173483
+ sqlite3 *db, /* Apply change to "main" db of this handle */
173484
+ int nChangeset, /* Size of changeset in bytes */
173485
+ void *pChangeset, /* Changeset blob */
173486
+ int(*xFilter)(
173487
+ void *pCtx, /* Copy of sixth arg to _apply() */
173488
+ const char *zTab /* Table name */
173489
+ ),
173490
+ int(*xConflict)(
173491
+ void *pCtx, /* Copy of fifth arg to _apply() */
173492
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173493
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
173494
+ ),
173495
+ void *pCtx /* First argument passed to xConflict */
173496
+){
173497
+ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173498
+ int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
173499
+ if( rc==SQLITE_OK ){
173500
+ rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173501
+ }
173502
+ return rc;
173503
+}
173504
+
173505
+/*
173506
+** Apply the changeset passed via xInput/pIn to the main database
173507
+** attached to handle "db". Invoke the supplied conflict handler callback
173508
+** to resolve any conflicts encountered while applying the change.
173509
+*/
173510
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply_strm(
173511
+ sqlite3 *db, /* Apply change to "main" db of this handle */
173512
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
173513
+ void *pIn, /* First arg for xInput */
173514
+ int(*xFilter)(
173515
+ void *pCtx, /* Copy of sixth arg to _apply() */
173516
+ const char *zTab /* Table name */
173517
+ ),
173518
+ int(*xConflict)(
173519
+ void *pCtx, /* Copy of sixth arg to _apply() */
173520
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173521
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
173522
+ ),
173523
+ void *pCtx /* First argument passed to xConflict */
173524
+){
173525
+ sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173526
+ int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173527
+ if( rc==SQLITE_OK ){
173528
+ rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173529
+ }
173530
+ return rc;
173531
+}
173532
+
173533
+/*
173534
+** sqlite3_changegroup handle.
173535
+*/
173536
+struct sqlite3_changegroup {
173537
+ int rc; /* Error code */
173538
+ int bPatch; /* True to accumulate patchsets */
173539
+ SessionTable *pList; /* List of tables in current patch */
173540
+};
173541
+
173542
+/*
173543
+** This function is called to merge two changes to the same row together as
173544
+** part of an sqlite3changeset_concat() operation. A new change object is
173545
+** allocated and a pointer to it stored in *ppNew.
173546
+*/
173547
+static int sessionChangeMerge(
173548
+ SessionTable *pTab, /* Table structure */
173549
+ int bPatchset, /* True for patchsets */
173550
+ SessionChange *pExist, /* Existing change */
173551
+ int op2, /* Second change operation */
173552
+ int bIndirect, /* True if second change is indirect */
173553
+ u8 *aRec, /* Second change record */
173554
+ int nRec, /* Number of bytes in aRec */
173555
+ SessionChange **ppNew /* OUT: Merged change */
173556
+){
173557
+ SessionChange *pNew = 0;
173558
+
173559
+ if( !pExist ){
173560
+ pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
173561
+ if( !pNew ){
173562
+ return SQLITE_NOMEM;
173563
+ }
173564
+ memset(pNew, 0, sizeof(SessionChange));
173565
+ pNew->op = op2;
173566
+ pNew->bIndirect = bIndirect;
173567
+ pNew->nRecord = nRec;
173568
+ pNew->aRecord = (u8*)&pNew[1];
173569
+ memcpy(pNew->aRecord, aRec, nRec);
173570
+ }else{
173571
+ int op1 = pExist->op;
173572
+
173573
+ /*
173574
+ ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
173575
+ ** op1=INSERT, op2=UPDATE -> INSERT.
173576
+ ** op1=INSERT, op2=DELETE -> (none)
173577
+ **
173578
+ ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
173579
+ ** op1=UPDATE, op2=UPDATE -> UPDATE.
173580
+ ** op1=UPDATE, op2=DELETE -> DELETE.
173581
+ **
173582
+ ** op1=DELETE, op2=INSERT -> UPDATE.
173583
+ ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
173584
+ ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
173585
+ */
173586
+ if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
173587
+ || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
173588
+ || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
173589
+ || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
173590
+ ){
173591
+ pNew = pExist;
173592
+ }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
173593
+ sqlite3_free(pExist);
173594
+ assert( pNew==0 );
173595
+ }else{
173596
+ u8 *aExist = pExist->aRecord;
173597
+ int nByte;
173598
+ u8 *aCsr;
173599
+
173600
+ /* Allocate a new SessionChange object. Ensure that the aRecord[]
173601
+ ** buffer of the new object is large enough to hold any record that
173602
+ ** may be generated by combining the input records. */
173603
+ nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
173604
+ pNew = (SessionChange *)sqlite3_malloc(nByte);
173605
+ if( !pNew ){
173606
+ sqlite3_free(pExist);
173607
+ return SQLITE_NOMEM;
173608
+ }
173609
+ memset(pNew, 0, sizeof(SessionChange));
173610
+ pNew->bIndirect = (bIndirect && pExist->bIndirect);
173611
+ aCsr = pNew->aRecord = (u8 *)&pNew[1];
173612
+
173613
+ if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
173614
+ u8 *a1 = aRec;
173615
+ assert( op2==SQLITE_UPDATE );
173616
+ pNew->op = SQLITE_INSERT;
173617
+ if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
173618
+ sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
173619
+ }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
173620
+ assert( op2==SQLITE_INSERT );
173621
+ pNew->op = SQLITE_UPDATE;
173622
+ if( bPatchset ){
173623
+ memcpy(aCsr, aRec, nRec);
173624
+ aCsr += nRec;
173625
+ }else{
173626
+ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
173627
+ sqlite3_free(pNew);
173628
+ pNew = 0;
173629
+ }
173630
+ }
173631
+ }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
173632
+ u8 *a1 = aExist;
173633
+ u8 *a2 = aRec;
173634
+ assert( op1==SQLITE_UPDATE );
173635
+ if( bPatchset==0 ){
173636
+ sessionSkipRecord(&a1, pTab->nCol);
173637
+ sessionSkipRecord(&a2, pTab->nCol);
173638
+ }
173639
+ pNew->op = SQLITE_UPDATE;
173640
+ if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
173641
+ sqlite3_free(pNew);
173642
+ pNew = 0;
173643
+ }
173644
+ }else{ /* UPDATE + DELETE */
173645
+ assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
173646
+ pNew->op = SQLITE_DELETE;
173647
+ if( bPatchset ){
173648
+ memcpy(aCsr, aRec, nRec);
173649
+ aCsr += nRec;
173650
+ }else{
173651
+ sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
173652
+ }
173653
+ }
173654
+
173655
+ if( pNew ){
173656
+ pNew->nRecord = (int)(aCsr - pNew->aRecord);
173657
+ }
173658
+ sqlite3_free(pExist);
173659
+ }
173660
+ }
173661
+
173662
+ *ppNew = pNew;
173663
+ return SQLITE_OK;
173664
+}
173665
+
173666
+/*
173667
+** Add all changes in the changeset traversed by the iterator passed as
173668
+** the first argument to the changegroup hash tables.
173669
+*/
173670
+static int sessionChangesetToHash(
173671
+ sqlite3_changeset_iter *pIter, /* Iterator to read from */
173672
+ sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
173673
+){
173674
+ u8 *aRec;
173675
+ int nRec;
173676
+ int rc = SQLITE_OK;
173677
+ SessionTable *pTab = 0;
173678
+
173679
+
173680
+ while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
173681
+ const char *zNew;
173682
+ int nCol;
173683
+ int op;
173684
+ int iHash;
173685
+ int bIndirect;
173686
+ SessionChange *pChange;
173687
+ SessionChange *pExist = 0;
173688
+ SessionChange **pp;
173689
+
173690
+ if( pGrp->pList==0 ){
173691
+ pGrp->bPatch = pIter->bPatchset;
173692
+ }else if( pIter->bPatchset!=pGrp->bPatch ){
173693
+ rc = SQLITE_ERROR;
173694
+ break;
173695
+ }
173696
+
173697
+ sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
173698
+ if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
173699
+ /* Search the list for a matching table */
173700
+ int nNew = (int)strlen(zNew);
173701
+ u8 *abPK;
173702
+
173703
+ sqlite3changeset_pk(pIter, &abPK, 0);
173704
+ for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
173705
+ if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
173706
+ }
173707
+ if( !pTab ){
173708
+ SessionTable **ppTab;
173709
+
173710
+ pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
173711
+ if( !pTab ){
173712
+ rc = SQLITE_NOMEM;
173713
+ break;
173714
+ }
173715
+ memset(pTab, 0, sizeof(SessionTable));
173716
+ pTab->nCol = nCol;
173717
+ pTab->abPK = (u8*)&pTab[1];
173718
+ memcpy(pTab->abPK, abPK, nCol);
173719
+ pTab->zName = (char*)&pTab->abPK[nCol];
173720
+ memcpy(pTab->zName, zNew, nNew+1);
173721
+
173722
+ /* The new object must be linked on to the end of the list, not
173723
+ ** simply added to the start of it. This is to ensure that the
173724
+ ** tables within the output of sqlite3changegroup_output() are in
173725
+ ** the right order. */
173726
+ for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
173727
+ *ppTab = pTab;
173728
+ }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
173729
+ rc = SQLITE_SCHEMA;
173730
+ break;
173731
+ }
173732
+ }
173733
+
173734
+ if( sessionGrowHash(pIter->bPatchset, pTab) ){
173735
+ rc = SQLITE_NOMEM;
173736
+ break;
173737
+ }
173738
+ iHash = sessionChangeHash(
173739
+ pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
173740
+ );
173741
+
173742
+ /* Search for existing entry. If found, remove it from the hash table.
173743
+ ** Code below may link it back in.
173744
+ */
173745
+ for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
173746
+ int bPkOnly1 = 0;
173747
+ int bPkOnly2 = 0;
173748
+ if( pIter->bPatchset ){
173749
+ bPkOnly1 = (*pp)->op==SQLITE_DELETE;
173750
+ bPkOnly2 = op==SQLITE_DELETE;
173751
+ }
173752
+ if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
173753
+ pExist = *pp;
173754
+ *pp = (*pp)->pNext;
173755
+ pTab->nEntry--;
173756
+ break;
173757
+ }
173758
+ }
173759
+
173760
+ rc = sessionChangeMerge(pTab,
173761
+ pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
173762
+ );
173763
+ if( rc ) break;
173764
+ if( pChange ){
173765
+ pChange->pNext = pTab->apChange[iHash];
173766
+ pTab->apChange[iHash] = pChange;
173767
+ pTab->nEntry++;
173768
+ }
173769
+ }
173770
+
173771
+ if( rc==SQLITE_OK ) rc = pIter->rc;
173772
+ return rc;
173773
+}
173774
+
173775
+/*
173776
+** Serialize a changeset (or patchset) based on all changesets (or patchsets)
173777
+** added to the changegroup object passed as the first argument.
173778
+**
173779
+** If xOutput is not NULL, then the changeset/patchset is returned to the
173780
+** user via one or more calls to xOutput, as with the other streaming
173781
+** interfaces.
173782
+**
173783
+** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
173784
+** buffer containing the output changeset before this function returns. In
173785
+** this case (*pnOut) is set to the size of the output buffer in bytes. It
173786
+** is the responsibility of the caller to free the output buffer using
173787
+** sqlite3_free() when it is no longer required.
173788
+**
173789
+** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
173790
+** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
173791
+** are both set to 0 before returning.
173792
+*/
173793
+static int sessionChangegroupOutput(
173794
+ sqlite3_changegroup *pGrp,
173795
+ int (*xOutput)(void *pOut, const void *pData, int nData),
173796
+ void *pOut,
173797
+ int *pnOut,
173798
+ void **ppOut
173799
+){
173800
+ int rc = SQLITE_OK;
173801
+ SessionBuffer buf = {0, 0, 0};
173802
+ SessionTable *pTab;
173803
+ assert( xOutput==0 || (ppOut==0 && pnOut==0) );
173804
+
173805
+ /* Create the serialized output changeset based on the contents of the
173806
+ ** hash tables attached to the SessionTable objects in list p->pList.
173807
+ */
173808
+ for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
173809
+ int i;
173810
+ if( pTab->nEntry==0 ) continue;
173811
+
173812
+ sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
173813
+ for(i=0; i<pTab->nChange; i++){
173814
+ SessionChange *p;
173815
+ for(p=pTab->apChange[i]; p; p=p->pNext){
173816
+ sessionAppendByte(&buf, p->op, &rc);
173817
+ sessionAppendByte(&buf, p->bIndirect, &rc);
173818
+ sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
173819
+ }
173820
+ }
173821
+
173822
+ if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173823
+ rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173824
+ buf.nBuf = 0;
173825
+ }
173826
+ }
173827
+
173828
+ if( rc==SQLITE_OK ){
173829
+ if( xOutput ){
173830
+ if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173831
+ }else{
173832
+ *ppOut = buf.aBuf;
173833
+ *pnOut = buf.nBuf;
173834
+ buf.aBuf = 0;
173835
+ }
173836
+ }
173837
+ sqlite3_free(buf.aBuf);
173838
+
173839
+ return rc;
173840
+}
173841
+
173842
+/*
173843
+** Allocate a new, empty, sqlite3_changegroup.
173844
+*/
173845
+SQLITE_API int SQLITE_STDCALL sqlite3changegroup_new(sqlite3_changegroup **pp){
173846
+ int rc = SQLITE_OK; /* Return code */
173847
+ sqlite3_changegroup *p; /* New object */
173848
+ p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
173849
+ if( p==0 ){
173850
+ rc = SQLITE_NOMEM;
173851
+ }else{
173852
+ memset(p, 0, sizeof(sqlite3_changegroup));
173853
+ }
173854
+ *pp = p;
173855
+ return rc;
173856
+}
173857
+
173858
+/*
173859
+** Add the changeset currently stored in buffer pData, size nData bytes,
173860
+** to changeset-group p.
173861
+*/
173862
+SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
173863
+ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173864
+ int rc; /* Return code */
173865
+
173866
+ rc = sqlite3changeset_start(&pIter, nData, pData);
173867
+ if( rc==SQLITE_OK ){
173868
+ rc = sessionChangesetToHash(pIter, pGrp);
173869
+ }
173870
+ sqlite3changeset_finalize(pIter);
173871
+ return rc;
173872
+}
173873
+
173874
+/*
173875
+** Obtain a buffer containing a changeset representing the concatenation
173876
+** of all changesets added to the group so far.
173877
+*/
173878
+SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output(
173879
+ sqlite3_changegroup *pGrp,
173880
+ int *pnData,
173881
+ void **ppData
173882
+){
173883
+ return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
173884
+}
173885
+
173886
+/*
173887
+** Streaming versions of changegroup_add().
173888
+*/
173889
+SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add_strm(
173890
+ sqlite3_changegroup *pGrp,
173891
+ int (*xInput)(void *pIn, void *pData, int *pnData),
173892
+ void *pIn
173893
+){
173894
+ sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173895
+ int rc; /* Return code */
173896
+
173897
+ rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173898
+ if( rc==SQLITE_OK ){
173899
+ rc = sessionChangesetToHash(pIter, pGrp);
173900
+ }
173901
+ sqlite3changeset_finalize(pIter);
173902
+ return rc;
173903
+}
173904
+
173905
+/*
173906
+** Streaming versions of changegroup_output().
173907
+*/
173908
+SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output_strm(
173909
+ sqlite3_changegroup *pGrp,
173910
+ int (*xOutput)(void *pOut, const void *pData, int nData),
173911
+ void *pOut
173912
+){
173913
+ return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
173914
+}
173915
+
173916
+/*
173917
+** Delete a changegroup object.
173918
+*/
173919
+SQLITE_API void SQLITE_STDCALL sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
173920
+ if( pGrp ){
173921
+ sessionDeleteTable(pGrp->pList);
173922
+ sqlite3_free(pGrp);
173923
+ }
173924
+}
173925
+
173926
+/*
173927
+** Combine two changesets together.
173928
+*/
173929
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat(
173930
+ int nLeft, /* Number of bytes in lhs input */
173931
+ void *pLeft, /* Lhs input changeset */
173932
+ int nRight /* Number of bytes in rhs input */,
173933
+ void *pRight, /* Rhs input changeset */
173934
+ int *pnOut, /* OUT: Number of bytes in output changeset */
173935
+ void **ppOut /* OUT: changeset (left <concat> right) */
173936
+){
173937
+ sqlite3_changegroup *pGrp;
173938
+ int rc;
173939
+
173940
+ rc = sqlite3changegroup_new(&pGrp);
173941
+ if( rc==SQLITE_OK ){
173942
+ rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
173943
+ }
173944
+ if( rc==SQLITE_OK ){
173945
+ rc = sqlite3changegroup_add(pGrp, nRight, pRight);
173946
+ }
173947
+ if( rc==SQLITE_OK ){
173948
+ rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
173949
+ }
173950
+ sqlite3changegroup_delete(pGrp);
173951
+
173952
+ return rc;
173953
+}
173954
+
173955
+/*
173956
+** Streaming version of sqlite3changeset_concat().
173957
+*/
173958
+SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat_strm(
173959
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
173960
+ void *pInA,
173961
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
173962
+ void *pInB,
173963
+ int (*xOutput)(void *pOut, const void *pData, int nData),
173964
+ void *pOut
173965
+){
173966
+ sqlite3_changegroup *pGrp;
173967
+ int rc;
173968
+
173969
+ rc = sqlite3changegroup_new(&pGrp);
173970
+ if( rc==SQLITE_OK ){
173971
+ rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
173972
+ }
173973
+ if( rc==SQLITE_OK ){
173974
+ rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
173975
+ }
173976
+ if( rc==SQLITE_OK ){
173977
+ rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
173978
+ }
173979
+ sqlite3changegroup_delete(pGrp);
173980
+
173981
+ return rc;
173982
+}
173983
+
173984
+#endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
173985
+
173986
+/************** End of sqlite3session.c **************************************/
166462173987
/************** Begin file json1.c *******************************************/
166463173988
/*
166464173989
** 2015-08-12
166465173990
**
166466173991
** The author disclaims copyright to this source code. In place of
@@ -168809,15 +176334,17 @@
168809176334
** of the current query. Specifically, a query equivalent to:
168810176335
**
168811176336
** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
168812176337
**
168813176338
** with $p set to a phrase equivalent to the phrase iPhrase of the
168814
-** current query is executed. For each row visited, the callback function
168815
-** passed as the fourth argument is invoked. The context and API objects
168816
-** passed to the callback function may be used to access the properties of
168817
-** each matched row. Invoking Api.xUserData() returns a copy of the pointer
168818
-** passed as the third argument to pUserData.
176339
+** current query is executed. Any column filter that applies to
176340
+** phrase iPhrase of the current query is included in $p. For each
176341
+** row visited, the callback function passed as the fourth argument
176342
+** is invoked. The context and API objects passed to the callback
176343
+** function may be used to access the properties of each matched row.
176344
+** Invoking Api.xUserData() returns a copy of the pointer passed as
176345
+** the third argument to pUserData.
168819176346
**
168820176347
** If the callback function returns any value other than SQLITE_OK, the
168821176348
** query is abandoned and the xQueryPhrase function returns immediately.
168822176349
** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
168823176350
** Otherwise, the error code is propagated upwards.
@@ -174848,10 +182375,21 @@
174848182375
}
174849182376
if( rc==SQLITE_OK ){
174850182377
pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
174851182378
sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
174852182379
}
182380
+ if( rc==SQLITE_OK ){
182381
+ Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
182382
+ if( pColsetOrig ){
182383
+ int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
182384
+ Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
182385
+ if( pColset ){
182386
+ memcpy(pColset, pColsetOrig, nByte);
182387
+ }
182388
+ pNew->pRoot->pNear->pColset = pColset;
182389
+ }
182390
+ }
174853182391
174854182392
for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
174855182393
int tflags = 0;
174856182394
Fts5ExprTerm *p;
174857182395
for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
@@ -176196,15 +183734,15 @@
176196183734
assert( iCol>=p->iCol );
176197183735
if( iCol!=p->iCol ){
176198183736
if( pHash->eDetail==FTS5_DETAIL_FULL ){
176199183737
pPtr[p->nData++] = 0x01;
176200183738
p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
176201
- p->iCol = iCol;
183739
+ p->iCol = (i16)iCol;
176202183740
p->iPos = 0;
176203183741
}else{
176204183742
bNew = 1;
176205
- p->iCol = iPos = iCol;
183743
+ p->iCol = (i16)(iPos = iCol);
176206183744
}
176207183745
}
176208183746
176209183747
/* Append the new position offset, if necessary */
176210183748
if( bNew ){
@@ -179623,11 +187161,11 @@
179623187161
while( *aiCol<iPrev ){
179624187162
aiCol++;
179625187163
if( aiCol==aiColEnd ) goto setoutputs_col_out;
179626187164
}
179627187165
if( *aiCol==iPrev ){
179628
- *aOut++ = (iPrev - iPrevOut) + 2;
187166
+ *aOut++ = (u8)((iPrev - iPrevOut) + 2);
179629187167
iPrevOut = iPrev;
179630187168
}
179631187169
}
179632187170
179633187171
setoutputs_col_out:
@@ -185456,11 +192994,11 @@
185456192994
int nArg, /* Number of args */
185457192995
sqlite3_value **apUnused /* Function arguments */
185458192996
){
185459192997
assert( nArg==0 );
185460192998
UNUSED_PARAM2(nArg, apUnused);
185461
- sqlite3_result_text(pCtx, "fts5: 2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d", -1, SQLITE_TRANSIENT);
192999
+ sqlite3_result_text(pCtx, "fts5: 2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2", -1, SQLITE_TRANSIENT);
185462193000
}
185463193001
185464193002
static int fts5Init(sqlite3 *db){
185465193003
static const sqlite3_module fts5Mod = {
185466193004
/* iVersion */ 2,
185467193005
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -1,8 +1,8 @@
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.12.1. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
@@ -37,10 +37,37 @@
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef _SQLITEINT_H_
41 #define _SQLITEINT_H_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
43 /*
44 ** Make sure that rand_s() is available on Windows systems with MSVC 2005
45 ** or higher.
46 */
@@ -334,13 +361,13 @@
334 **
335 ** See also: [sqlite3_libversion()],
336 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
337 ** [sqlite_version()] and [sqlite_source_id()].
338 */
339 #define SQLITE_VERSION "3.12.1"
340 #define SQLITE_VERSION_NUMBER 3012001
341 #define SQLITE_SOURCE_ID "2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d"
342
343 /*
344 ** CAPI3REF: Run-Time Library Version Numbers
345 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
346 **
@@ -2155,16 +2182,34 @@
2155 ** The second parameter is a pointer to an integer into which
2156 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2157 ** following this call. The second parameter may be a NULL pointer, in
2158 ** which case the new setting is not reported back. </dd>
2159 **
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2160 ** </dl>
2161 */
2162 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2163 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2164 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2165 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
 
2166
2167
2168 /*
2169 ** CAPI3REF: Enable Or Disable Extended Result Codes
2170 ** METHOD: sqlite3
@@ -5410,11 +5455,11 @@
5410 ** METHOD: sqlite3
5411 **
5412 ** ^The sqlite3_update_hook() interface registers a callback function
5413 ** with the [database connection] identified by the first argument
5414 ** to be invoked whenever a row is updated, inserted or deleted in
5415 ** a rowid table.
5416 ** ^Any callback set by a previous call to this function
5417 ** for the same database connection is overridden.
5418 **
5419 ** ^The second argument is a pointer to the function to invoke when a
5420 ** row is updated, inserted or deleted in a rowid table.
@@ -5449,12 +5494,12 @@
5449 ** ^The sqlite3_update_hook(D,C,P) function
5450 ** returns the P argument from the previous call
5451 ** on the same [database connection] D, or NULL for
5452 ** the first call on D.
5453 **
5454 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5455 ** interfaces.
5456 */
5457 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5458 sqlite3*,
5459 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5460 void*
@@ -5697,12 +5742,21 @@
5697 ** fill *pzErrMsg with error message text stored in memory
5698 ** obtained from [sqlite3_malloc()]. The calling function
5699 ** should free this memory by calling [sqlite3_free()].
5700 **
5701 ** ^Extension loading must be enabled using
5702 ** [sqlite3_enable_load_extension()] prior to calling this API,
 
 
5703 ** otherwise an error will be returned.
 
 
 
 
 
 
 
5704 **
5705 ** See also the [load_extension() SQL function].
5706 */
5707 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5708 sqlite3 *db, /* Load the extension into this database connection */
@@ -5722,10 +5776,21 @@
5722 **
5723 ** ^Extension loading is off by default.
5724 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5725 ** to turn extension loading on and call it with onoff==0 to turn
5726 ** it back off again.
 
 
 
 
 
 
 
 
 
 
 
5727 */
5728 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5729
5730 /*
5731 ** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7360,11 +7425,11 @@
7360 ** and database name of the source database, respectively.
7361 ** ^The source and destination [database connections] (parameters S and D)
7362 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7363 ** an error.
7364 **
7365 ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7366 ** there is already a read or read-write transaction open on the
7367 ** destination database.
7368 **
7369 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7370 ** returned and an error code and error message are stored in the
@@ -8138,15 +8203,111 @@
8138 ** ^This function does not set the database handle error code or message
8139 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8140 */
8141 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
8142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8143 /*
8144 ** CAPI3REF: Low-level system error code
8145 **
8146 ** ^Attempt to return the underlying operating system error code or error
8147 ** number that caused the most reason I/O error or failure to open a file.
8148 ** The return value is OS-dependent. For example, on unix systems, after
8149 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8150 ** called to get back the underlying "errno" that caused the problem, such
8151 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8152 */
@@ -8208,24 +8369,33 @@
8208
8209 /*
8210 ** CAPI3REF: Start a read transaction on an historical snapshot
8211 ** EXPERIMENTAL
8212 **
8213 ** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
8214 ** read transaction that is currently open on schema S of
8215 ** [database connection] D so that it refers to historical [snapshot] P.
 
 
8216 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8217 ** or an appropriate [error code] if it fails.
8218 **
8219 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8220 ** the first operation, apart from other sqlite3_snapshot_open() calls,
8221 ** following the [BEGIN] that starts a new read transaction.
8222 ** ^A [snapshot] will fail to open if it has been overwritten by a
 
 
 
8223 ** [checkpoint].
8224 ** ^A [snapshot] will fail to open if the database connection D has not
8225 ** previously completed at least one read operation against the database
8226 ** file. (Hint: Run "[PRAGMA application_id]" against a newly opened
 
 
 
 
8227 ** database connection in order to make it ready to use snapshots.)
8228 **
8229 ** The [sqlite3_snapshot_open()] interface is only available when the
8230 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8231 */
@@ -8246,10 +8416,37 @@
8246 ** The [sqlite3_snapshot_free()] interface is only available when the
8247 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8248 */
8249 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8250
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8251 /*
8252 ** Undo the hack that converts floating point types to integer for
8253 ** builds on processors without floating point support.
8254 */
8255 #ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8259,10 +8456,11 @@
8259 #if 0
8260 } /* End of the 'extern "C"' block */
8261 #endif
8262 #endif /* _SQLITE3_H_ */
8263
 
8264 /*
8265 ** 2010 August 30
8266 **
8267 ** The author disclaims copyright to this source code. In place of
8268 ** a legal notice, here is a blessing:
@@ -8376,10 +8574,1291 @@
8376 } /* end of the 'extern "C"' block */
8377 #endif
8378
8379 #endif /* ifndef _SQLITE3RTREE_H_ */
8380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8381 /*
8382 ** 2014 May 31
8383 **
8384 ** The author disclaims copyright to this source code. In place of
8385 ** a legal notice, here is a blessing:
@@ -8520,15 +9999,17 @@
8520 ** of the current query. Specifically, a query equivalent to:
8521 **
8522 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
8523 **
8524 ** with $p set to a phrase equivalent to the phrase iPhrase of the
8525 ** current query is executed. For each row visited, the callback function
8526 ** passed as the fourth argument is invoked. The context and API objects
8527 ** passed to the callback function may be used to access the properties of
8528 ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
8529 ** passed as the third argument to pUserData.
 
 
8530 **
8531 ** If the callback function returns any value other than SQLITE_OK, the
8532 ** query is abandoned and the xQueryPhrase function returns immediately.
8533 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
8534 ** Otherwise, the error code is propagated upwards.
@@ -8954,10 +10435,11 @@
8954 #endif
8955
8956 #endif /* _FTS5_H */
8957
8958
 
8959
8960 /************** End of sqlite3.h *********************************************/
8961 /************** Continuing where we left off in sqliteInt.h ******************/
8962
8963 /*
@@ -9435,11 +10917,11 @@
9435 **
9436 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
9437 ** be true and false so that the unreachable code they specify will
9438 ** not be counted as untested code.
9439 */
9440 #if defined(SQLITE_COVERAGE_TEST)
9441 # define ALWAYS(X) (1)
9442 # define NEVER(X) (0)
9443 #elif !defined(NDEBUG)
9444 # define ALWAYS(X) ((X)?1:(assert(0),0))
9445 # define NEVER(X) ((X)?(assert(0),1):0)
@@ -9640,80 +11122,80 @@
9640 #define TK_LP 22
9641 #define TK_RP 23
9642 #define TK_AS 24
9643 #define TK_WITHOUT 25
9644 #define TK_COMMA 26
9645 #define TK_ID 27
9646 #define TK_INDEXED 28
9647 #define TK_ABORT 29
9648 #define TK_ACTION 30
9649 #define TK_AFTER 31
9650 #define TK_ANALYZE 32
9651 #define TK_ASC 33
9652 #define TK_ATTACH 34
9653 #define TK_BEFORE 35
9654 #define TK_BY 36
9655 #define TK_CASCADE 37
9656 #define TK_CAST 38
9657 #define TK_COLUMNKW 39
9658 #define TK_CONFLICT 40
9659 #define TK_DATABASE 41
9660 #define TK_DESC 42
9661 #define TK_DETACH 43
9662 #define TK_EACH 44
9663 #define TK_FAIL 45
9664 #define TK_FOR 46
9665 #define TK_IGNORE 47
9666 #define TK_INITIALLY 48
9667 #define TK_INSTEAD 49
9668 #define TK_LIKE_KW 50
9669 #define TK_MATCH 51
9670 #define TK_NO 52
9671 #define TK_KEY 53
9672 #define TK_OF 54
9673 #define TK_OFFSET 55
9674 #define TK_PRAGMA 56
9675 #define TK_RAISE 57
9676 #define TK_RECURSIVE 58
9677 #define TK_REPLACE 59
9678 #define TK_RESTRICT 60
9679 #define TK_ROW 61
9680 #define TK_TRIGGER 62
9681 #define TK_VACUUM 63
9682 #define TK_VIEW 64
9683 #define TK_VIRTUAL 65
9684 #define TK_WITH 66
9685 #define TK_REINDEX 67
9686 #define TK_RENAME 68
9687 #define TK_CTIME_KW 69
9688 #define TK_ANY 70
9689 #define TK_OR 71
9690 #define TK_AND 72
9691 #define TK_IS 73
9692 #define TK_BETWEEN 74
9693 #define TK_IN 75
9694 #define TK_ISNULL 76
9695 #define TK_NOTNULL 77
9696 #define TK_NE 78
9697 #define TK_EQ 79
9698 #define TK_GT 80
9699 #define TK_LE 81
9700 #define TK_LT 82
9701 #define TK_GE 83
9702 #define TK_ESCAPE 84
9703 #define TK_BITAND 85
9704 #define TK_BITOR 86
9705 #define TK_LSHIFT 87
9706 #define TK_RSHIFT 88
9707 #define TK_PLUS 89
9708 #define TK_MINUS 90
9709 #define TK_STAR 91
9710 #define TK_SLASH 92
9711 #define TK_REM 93
9712 #define TK_CONCAT 94
9713 #define TK_COLLATE 95
9714 #define TK_BITNOT 96
9715 #define TK_STRING 97
9716 #define TK_JOIN_KW 98
9717 #define TK_CONSTRAINT 99
9718 #define TK_DEFAULT 100
9719 #define TK_NULL 101
@@ -10311,10 +11793,11 @@
10311 typedef struct Lookaside Lookaside;
10312 typedef struct LookasideSlot LookasideSlot;
10313 typedef struct Module Module;
10314 typedef struct NameContext NameContext;
10315 typedef struct Parse Parse;
 
10316 typedef struct PrintfArguments PrintfArguments;
10317 typedef struct RowSet RowSet;
10318 typedef struct Savepoint Savepoint;
10319 typedef struct Select Select;
10320 typedef struct SQLiteThread SQLiteThread;
@@ -10723,11 +12206,11 @@
10723 ** as an instance of the following structure:
10724 */
10725 struct VdbeOp {
10726 u8 opcode; /* What operation to perform */
10727 signed char p4type; /* One of the P4_xxx constants for p4 */
10728 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
10729 u8 p5; /* Fifth parameter is an unsigned character */
10730 int p1; /* First operand */
10731 int p2; /* Second parameter (often the jump destination) */
10732 int p3; /* The third parameter */
10733 union p4union { /* fourth parameter */
@@ -10742,10 +12225,11 @@
10742 Mem *pMem; /* Used when p4type is P4_MEM */
10743 VTable *pVtab; /* Used when p4type is P4_VTAB */
10744 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
10745 int *ai; /* Used when p4type is P4_INTARRAY */
10746 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
 
10747 #ifdef SQLITE_ENABLE_CURSOR_HINTS
10748 Expr *pExpr; /* Used when p4type is P4_EXPR */
10749 #endif
10750 int (*xAdvance)(BtCursor *, int *);
10751 } p4;
@@ -10806,11 +12290,12 @@
10806 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
10807 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
10808 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
10809 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
10810 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
10811 #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
 
10812
10813 /* Error message codes for OP_Halt */
10814 #define P5_ConstraintNotNull 1
10815 #define P5_ConstraintUnique 2
10816 #define P5_ConstraintCheck 3
@@ -10864,157 +12349,156 @@
10864 #define OP_Vacuum 10
10865 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
10866 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
10867 #define OP_Goto 13
10868 #define OP_Gosub 14
10869 #define OP_Return 15
10870 #define OP_InitCoroutine 16
10871 #define OP_EndCoroutine 17
10872 #define OP_Yield 18
10873 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
10874 #define OP_HaltIfNull 20 /* synopsis: if r[P3]=null halt */
10875 #define OP_Halt 21
10876 #define OP_Integer 22 /* synopsis: r[P2]=P1 */
10877 #define OP_Int64 23 /* synopsis: r[P2]=P4 */
10878 #define OP_String 24 /* synopsis: r[P2]='P4' (len=P1) */
10879 #define OP_Null 25 /* synopsis: r[P2..P3]=NULL */
10880 #define OP_SoftNull 26 /* synopsis: r[P1]=NULL */
10881 #define OP_Blob 27 /* synopsis: r[P2]=P4 (len=P1) */
10882 #define OP_Variable 28 /* synopsis: r[P2]=parameter(P1,P4) */
10883 #define OP_Move 29 /* synopsis: r[P2@P3]=r[P1@P3] */
10884 #define OP_Copy 30 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
10885 #define OP_SCopy 31 /* synopsis: r[P2]=r[P1] */
10886 #define OP_IntCopy 32 /* synopsis: r[P2]=r[P1] */
10887 #define OP_ResultRow 33 /* synopsis: output=r[P1@P2] */
10888 #define OP_CollSeq 34
10889 #define OP_Function0 35 /* synopsis: r[P3]=func(r[P2@P5]) */
10890 #define OP_Function 36 /* synopsis: r[P3]=func(r[P2@P5]) */
10891 #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
10892 #define OP_MustBeInt 38
10893 #define OP_RealAffinity 39
10894 #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
10895 #define OP_Permutation 41
10896 #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
10897 #define OP_Jump 43
10898 #define OP_Once 44
10899 #define OP_If 45
10900 #define OP_IfNot 46
10901 #define OP_Column 47 /* synopsis: r[P3]=PX */
10902 #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
10903 #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
10904 #define OP_Count 50 /* synopsis: r[P2]=count() */
10905 #define OP_ReadCookie 51
10906 #define OP_SetCookie 52
10907 #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
10908 #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
10909 #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
10910 #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
10911 #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
10912 #define OP_SorterOpen 58
10913 #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
10914 #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
10915 #define OP_Close 61
10916 #define OP_ColumnsUsed 62
10917 #define OP_SeekLT 63 /* synopsis: key=r[P3@P4] */
10918 #define OP_SeekLE 64 /* synopsis: key=r[P3@P4] */
10919 #define OP_SeekGE 65 /* synopsis: key=r[P3@P4] */
10920 #define OP_SeekGT 66 /* synopsis: key=r[P3@P4] */
10921 #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
10922 #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
10923 #define OP_Found 69 /* synopsis: key=r[P3@P4] */
10924 #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
10925 #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
10926 #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
10927 #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
10928 #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
10929 #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
10930 #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
10931 #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
10932 #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
10933 #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
10934 #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
10935 #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
10936 #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
10937 #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
10938 #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
10939 #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
10940 #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
10941 #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
10942 #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
10943 #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
10944 #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
10945 #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
10946 #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
10947 #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
10948 #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
10949 #define OP_Delete 95
10950 #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
10951 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
10952 #define OP_ResetCount 98
10953 #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
10954 #define OP_SorterData 100 /* synopsis: r[P2]=data */
10955 #define OP_RowKey 101 /* synopsis: r[P2]=key */
10956 #define OP_RowData 102 /* synopsis: r[P2]=data */
10957 #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
10958 #define OP_NullRow 104
10959 #define OP_Last 105
10960 #define OP_SorterSort 106
10961 #define OP_Sort 107
10962 #define OP_Rewind 108
10963 #define OP_SorterInsert 109
10964 #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
10965 #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
10966 #define OP_Seek 112 /* synopsis: Move P3 to P1.rowid */
10967 #define OP_IdxRowid 113 /* synopsis: r[P2]=rowid */
10968 #define OP_IdxLE 114 /* synopsis: key=r[P3@P4] */
10969 #define OP_IdxGT 115 /* synopsis: key=r[P3@P4] */
10970 #define OP_IdxLT 116 /* synopsis: key=r[P3@P4] */
10971 #define OP_IdxGE 117 /* synopsis: key=r[P3@P4] */
10972 #define OP_Destroy 118
10973 #define OP_Clear 119
10974 #define OP_ResetSorter 120
10975 #define OP_CreateIndex 121 /* synopsis: r[P2]=root iDb=P1 */
10976 #define OP_CreateTable 122 /* synopsis: r[P2]=root iDb=P1 */
10977 #define OP_ParseSchema 123
10978 #define OP_LoadAnalysis 124
10979 #define OP_DropTable 125
10980 #define OP_DropIndex 126
10981 #define OP_DropTrigger 127
10982 #define OP_IntegrityCk 128
10983 #define OP_RowSetAdd 129 /* synopsis: rowset(P1)=r[P2] */
10984 #define OP_RowSetRead 130 /* synopsis: r[P3]=rowset(P1) */
10985 #define OP_RowSetTest 131 /* synopsis: if r[P3] in rowset(P1) goto P2 */
10986 #define OP_Program 132
10987 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
10988 #define OP_Param 134
10989 #define OP_FkCounter 135 /* synopsis: fkctr[P1]+=P2 */
10990 #define OP_FkIfZero 136 /* synopsis: if fkctr[P1]==0 goto P2 */
10991 #define OP_MemMax 137 /* synopsis: r[P1]=max(r[P1],r[P2]) */
10992 #define OP_IfPos 138 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
10993 #define OP_OffsetLimit 139 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
10994 #define OP_IfNotZero 140 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
10995 #define OP_DecrJumpZero 141 /* synopsis: if (--r[P1])==0 goto P2 */
10996 #define OP_JumpZeroIncr 142 /* synopsis: if (r[P1]++)==0 ) goto P2 */
10997 #define OP_AggStep0 143 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10998 #define OP_AggStep 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
10999 #define OP_AggFinal 145 /* synopsis: accum=r[P1] N=P2 */
11000 #define OP_IncrVacuum 146
11001 #define OP_Expire 147
11002 #define OP_TableLock 148 /* synopsis: iDb=P1 root=P2 write=P3 */
11003 #define OP_VBegin 149
11004 #define OP_VCreate 150
11005 #define OP_VDestroy 151
11006 #define OP_VOpen 152
11007 #define OP_VColumn 153 /* synopsis: r[P3]=vcolumn(P2) */
11008 #define OP_VNext 154
11009 #define OP_VRename 155
11010 #define OP_Pagecount 156
11011 #define OP_MaxPgcnt 157
11012 #define OP_Init 158 /* synopsis: Start at P2 */
11013 #define OP_CursorHint 159
11014 #define OP_Noop 160
11015 #define OP_Explain 161
11016
11017 /* Properties such as "out2" or "jump" that are specified in
11018 ** comments following the "case" for each opcode in the vdbe.c
11019 ** are encoded into bitvectors as follows:
11020 */
@@ -11024,30 +12508,38 @@
11024 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
11025 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
11026 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
11027 #define OPFLG_INITIALIZER {\
11028 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
11029 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x02,\
11030 /* 16 */ 0x01, 0x02, 0x03, 0x12, 0x08, 0x00, 0x10, 0x10,\
11031 /* 24 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
11032 /* 32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
11033 /* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
11034 /* 48 */ 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
11035 /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
11036 /* 64 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x26,\
11037 /* 72 */ 0x26, 0x10, 0x10, 0x00, 0x03, 0x03, 0x0b, 0x0b,\
11038 /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
11039 /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
11040 /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
11041 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x00,\
11042 /* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
11043 /* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
11044 /* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
11045 /* 136 */ 0x01, 0x04, 0x03, 0x1a, 0x03, 0x03, 0x03, 0x00,\
11046 /* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
11047 /* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
11048 /* 160 */ 0x00, 0x00,}
 
 
 
 
 
 
 
 
11049
11050 /************** End of opcodes.h *********************************************/
11051 /************** Continuing where we left off in vdbe.h ***********************/
11052
11053 /*
@@ -11266,11 +12758,15 @@
11266 #define PAGER_LOCKINGMODE_QUERY -1
11267 #define PAGER_LOCKINGMODE_NORMAL 0
11268 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
11269
11270 /*
11271 ** Numeric constants that encode the journalmode.
 
 
 
 
11272 */
11273 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
11274 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
11275 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
11276 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
@@ -11284,10 +12780,15 @@
11284 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
11285 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
11286
11287 /*
11288 ** Flags for sqlite3PagerSetFlags()
 
 
 
 
 
11289 */
11290 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
11291 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
11292 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
11293 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
@@ -11453,11 +12954,11 @@
11453 */
11454 struct PgHdr {
11455 sqlite3_pcache_page *pPage; /* Pcache object page handle */
11456 void *pData; /* Page data */
11457 void *pExtra; /* Extra content */
11458 PgHdr *pDirty; /* Transient list of dirty pages */
11459 Pager *pPager; /* The pager this page is part of */
11460 Pgno pgno; /* Page number for this page */
11461 #ifdef SQLITE_CHECK_PAGES
11462 u32 pageHash; /* Hash of page content */
11463 #endif
@@ -11478,15 +12979,14 @@
11478 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
11479 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
11480 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
11481 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
11482 ** writing this page to the database */
11483 #define PGHDR_NEED_READ 0x010 /* Content is unread */
11484 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
11485 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
11486
11487 #define PGHDR_WAL_APPEND 0x080 /* Appended to wal file */
11488
11489 /* Initialize and shutdown the page cache subsystem */
11490 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
11491 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
11492
@@ -11526,10 +13026,11 @@
11526
11527 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
11528 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
11529 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
11530 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
 
11531
11532 /* Change a page number. Used by incr-vacuum. */
11533 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
11534
11535 /* Remove all pages with pgno>x. Reset the cache if x==0 */
@@ -11563,10 +13064,15 @@
11563 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
11564 ** library is built.
11565 */
11566 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
11567 #endif
 
 
 
 
 
11568
11569 /* Set and get the suggested cache-size for the specified pager-cache.
11570 **
11571 ** If no global maximum is configured, then the system attempts to limit
11572 ** the total number of pages cached by purgeable pager-caches to the sum
@@ -11599,10 +13105,13 @@
11599 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
11600
11601 /* Return the header size */
11602 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
11603 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
 
 
 
11604
11605 #endif /* _PCACHE_H_ */
11606
11607 /************** End of pcache.h **********************************************/
11608 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -11829,11 +13338,11 @@
11829 SQLITE_PRIVATE int sqlite3OsInit(void);
11830
11831 /*
11832 ** Functions for accessing sqlite3_file methods
11833 */
11834 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
11835 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
11836 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
11837 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
11838 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
11839 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
@@ -11874,11 +13383,11 @@
11874 /*
11875 ** Convenience functions for opening and closing files using
11876 ** sqlite3_malloc() to obtain space for the file-handle structure.
11877 */
11878 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
11879 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
11880
11881 #endif /* _SQLITE_OS_H_ */
11882
11883 /************** End of os.h **************************************************/
11884 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -12206,10 +13715,17 @@
12206 int (*xCommitCallback)(void*); /* Invoked at every commit. */
12207 void *pRollbackArg; /* Argument to xRollbackCallback() */
12208 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
12209 void *pUpdateArg;
12210 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
 
 
 
 
 
 
 
12211 #ifndef SQLITE_OMIT_WAL
12212 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
12213 void *pWalArg;
12214 #endif
12215 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
@@ -12276,10 +13792,15 @@
12276 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
12277 #define ENC(db) ((db)->enc)
12278
12279 /*
12280 ** Possible values for the sqlite3.flags.
 
 
 
 
 
12281 */
12282 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
12283 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
12284 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
12285 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
@@ -12303,17 +13824,18 @@
12303 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
12304 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
12305 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
12306 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
12307 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
12308 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
12309 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
12310 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
12311 #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
12312 #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
12313 #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
12314 #define SQLITE_Fts3Tokenizer 0x20000000 /* Enable fts3_tokenizer(2) */
 
12315
12316
12317 /*
12318 ** Bits of the sqlite3.dbOptFlags field that are used by the
12319 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
@@ -12410,10 +13932,17 @@
12410 /*
12411 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
12412 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
12413 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
12414 ** are assert() statements in the code to verify this.
 
 
 
 
 
 
 
12415 */
12416 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
12417 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
12418 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
12419 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
@@ -13409,10 +14938,13 @@
13409
13410
13411 /*
13412 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
13413 ** and the WhereInfo.wctrlFlags member.
 
 
 
13414 */
13415 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
13416 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
13417 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
13418 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
@@ -13426,10 +14958,11 @@
13426 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
13427 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
13428 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
13429 #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
13430 #define WHERE_USE_LIMIT 0x4000 /* There is a constant LIMIT clause */
 
13431
13432 /* Allowed return values from sqlite3WhereIsDistinct()
13433 */
13434 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
13435 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
@@ -13469,20 +15002,22 @@
13469 };
13470
13471 /*
13472 ** Allowed values for the NameContext, ncFlags field.
13473 **
13474 ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
13475 ** SQLITE_FUNC_MINMAX.
 
13476 **
13477 */
13478 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
13479 #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
13480 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
13481 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
13482 #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
13483 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
 
13484 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
13485
13486 /*
13487 ** An instance of the following structure contains all information
13488 ** needed to generate code for a single SELECT statement.
@@ -13526,28 +15061,34 @@
13526 };
13527
13528 /*
13529 ** Allowed values for Select.selFlags. The "SF" prefix stands for
13530 ** "Select Flag".
 
 
 
 
 
13531 */
13532 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
13533 #define SF_All 0x00002 /* Includes the ALL keyword */
13534 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
13535 #define SF_Aggregate 0x00008 /* Contains aggregate functions */
13536 #define SF_UsesEphemeral 0x00010 /* Uses the OpenEphemeral opcode */
13537 #define SF_Expanded 0x00020 /* sqlite3SelectExpand() called on this */
13538 #define SF_HasTypeInfo 0x00040 /* FROM subqueries have Table metadata */
13539 #define SF_Compound 0x00080 /* Part of a compound query */
13540 #define SF_Values 0x00100 /* Synthesized from VALUES clause */
13541 #define SF_MultiValue 0x00200 /* Single VALUES term with multiple rows */
13542 #define SF_NestedFrom 0x00400 /* Part of a parenthesized FROM clause */
13543 #define SF_MaybeConvert 0x00800 /* Need convertCompoundSelectToSubquery() */
13544 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
13545 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
13546 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
13547 #define SF_Converted 0x08000 /* By convertCompoundSelectToSubquery() */
13548 #define SF_IncludeHidden 0x10000 /* Include hidden columns in output */
 
13549
13550
13551 /*
13552 ** The results of a SELECT can be distributed in several ways, as defined
13553 ** by one of the following macros. The "SRT" prefix means "SELECT Result
@@ -13740,10 +15281,11 @@
13740 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
13741 u8 mayAbort; /* True if statement may throw an ABORT exception */
13742 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
13743 u8 okConstFactor; /* OK to factor out constants */
13744 u8 disableLookaside; /* Number of times lookaside has been disabled */
 
13745 int aTempReg[8]; /* Holding area for temporary registers */
13746 int nRangeReg; /* Size of the temporary register block */
13747 int iRangeReg; /* First register in temporary register block */
13748 int nErr; /* Number of errors seen */
13749 int nTab; /* Number of previously allocated VDBE cursors */
@@ -13853,18 +15395,30 @@
13853 Parse *pParse; /* The Parse structure */
13854 };
13855
13856 /*
13857 ** Bitfield flags for P5 value in various opcodes.
 
 
 
 
 
 
 
 
 
13858 */
13859 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
13860 /* Also used in P2 (not P5) of OP_Delete */
13861 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
13862 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
13863 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
13864 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
13865 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
 
 
 
13866 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
13867 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
13868 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
13869 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
13870 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
@@ -14224,18 +15778,20 @@
14224 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
14225 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
14226 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
14227 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
14228 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
 
14229 #else
14230 # define sqlite3Toupper(x) toupper((unsigned char)(x))
14231 # define sqlite3Isspace(x) isspace((unsigned char)(x))
14232 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
14233 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
14234 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
14235 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
14236 # define sqlite3Tolower(x) tolower((unsigned char)(x))
 
14237 #endif
14238 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
14239 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
14240 #endif
14241
@@ -14355,11 +15911,11 @@
14355 #endif
14356
14357
14358 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
14359 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
14360 SQLITE_PRIVATE int sqlite3Dequote(char*);
14361 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
14362 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
14363 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
14364 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
14365 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
@@ -14372,10 +15928,11 @@
14372 #endif
14373 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
14374 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
14375 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
14376 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
 
14377 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
14378 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
14379 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
14380 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
14381 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
@@ -15167,10 +16724,11 @@
15167 ** isdigit() 0x04
15168 ** isalnum() 0x06
15169 ** isxdigit() 0x08
15170 ** toupper() 0x20
15171 ** SQLite identifier character 0x40
 
15172 **
15173 ** Bit 0x20 is set if the mapped character requires translation to upper
15174 ** case. i.e. if the character is a lower-case ASCII character.
15175 ** If x is a lower-case ASCII character, then its upper-case equivalent
15176 ** is (x - 0x20). Therefore toupper() can be implemented as:
@@ -15192,20 +16750,20 @@
15192 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
15193 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
15194 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
15195 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
15196 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
15197 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
15198 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
15199 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
15200 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
15201
15202 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
15203 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
15204 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
15205 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
15206 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
15207 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
15208 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
15209 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
15210
15211 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
@@ -16271,10 +17829,29 @@
16271 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
16272 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
16273 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
16274 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
16275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16276 /*
16277 ** Function prototypes
16278 */
16279 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
16280 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
@@ -16330,10 +17907,13 @@
16330 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
16331 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
16332 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
16333 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
16334 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
 
 
 
16335 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
16336
16337 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
16338 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
16339 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
@@ -16767,10 +18347,19 @@
16767 /* #include <assert.h> */
16768 #include <time.h>
16769
16770 #ifndef SQLITE_OMIT_DATETIME_FUNCS
16771
 
 
 
 
 
 
 
 
 
16772
16773 /*
16774 ** A structure for holding a single date and time.
16775 */
16776 typedef struct DateTime DateTime;
@@ -17135,10 +18724,11 @@
17135 p->validYMD = 0;
17136 p->validHMS = 0;
17137 p->validTZ = 0;
17138 }
17139
 
17140 /*
17141 ** On recent Windows platforms, the localtime_s() function is available
17142 ** as part of the "Secure CRT". It is essentially equivalent to
17143 ** localtime_r() available under most POSIX platforms, except that the
17144 ** order of the parameters is reversed.
@@ -17153,11 +18743,10 @@
17153 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
17154 #undef HAVE_LOCALTIME_S
17155 #define HAVE_LOCALTIME_S 1
17156 #endif
17157
17158 #ifndef SQLITE_OMIT_LOCALTIME
17159 /*
17160 ** The following routine implements the rough equivalent of localtime_r()
17161 ** using whatever operating-system specific localtime facility that
17162 ** is available. This routine returns 0 on success and
17163 ** non-zero on any kind of error.
@@ -17957,17 +19546,15 @@
17957 ** The following routines are convenience wrappers around methods
17958 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
17959 ** of this would be completely automatic if SQLite were coded using
17960 ** C++ instead of plain old C.
17961 */
17962 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
17963 int rc = SQLITE_OK;
17964 if( pId->pMethods ){
17965 rc = pId->pMethods->xClose(pId);
17966 pId->pMethods = 0;
17967 }
17968 return rc;
17969 }
17970 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
17971 DO_OS_MALLOC_TEST(id);
17972 return id->pMethods->xRead(id, pBuf, amt, offset);
17973 }
@@ -18181,16 +19768,14 @@
18181 }else{
18182 rc = SQLITE_NOMEM_BKPT;
18183 }
18184 return rc;
18185 }
18186 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
18187 int rc = SQLITE_OK;
18188 assert( pFile );
18189 rc = sqlite3OsClose(pFile);
18190 sqlite3_free(pFile);
18191 return rc;
18192 }
18193
18194 /*
18195 ** This function is a wrapper around the OS specific implementation of
18196 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
@@ -22866,30 +24451,30 @@
22866
22867 /*
22868 ** Conversion types fall into various categories as defined by the
22869 ** following enumeration.
22870 */
22871 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
22872 #define etFLOAT 2 /* Floating point. %f */
22873 #define etEXP 3 /* Exponentional notation. %e and %E */
22874 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
22875 #define etSIZE 5 /* Return number of characters processed so far. %n */
22876 #define etSTRING 6 /* Strings. %s */
22877 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
22878 #define etPERCENT 8 /* Percent symbol. %% */
22879 #define etCHARX 9 /* Characters. %c */
22880 /* The rest are extensions, not normally found in printf() */
22881 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
22882 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
22883 NULL pointers replaced by SQL NULL. %Q */
22884 #define etTOKEN 12 /* a pointer to a Token structure */
22885 #define etSRCLIST 13 /* a pointer to a SrcList */
22886 #define etPOINTER 14 /* The %p conversion */
22887 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
22888 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
22889
22890 #define etINVALID 0 /* Any unrecognized conversion type */
22891
22892
22893 /*
22894 ** An "etByte" is an 8-bit unsigned value.
22895 */
@@ -23040,11 +24625,11 @@
23040 etByte flag_altform2; /* True if "!" flag is present */
23041 etByte flag_zeropad; /* True if field width constant starts with zero */
23042 etByte flag_long; /* True if "l" flag is present */
23043 etByte flag_longlong; /* True if the "ll" flag is present */
23044 etByte done; /* Loop termination flag */
23045 etByte xtype = 0; /* Conversion paradigm */
23046 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
23047 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
23048 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
23049 sqlite_uint64 longvalue; /* Value for integer types */
23050 LONGDOUBLE_TYPE realvalue; /* Value for real types */
@@ -25631,22 +27216,17 @@
25631 **
25632 ** 2002-Feb-14: This routine is extended to remove MS-Access style
25633 ** brackets from around identifiers. For example: "[a-b-c]" becomes
25634 ** "a-b-c".
25635 */
25636 SQLITE_PRIVATE int sqlite3Dequote(char *z){
25637 char quote;
25638 int i, j;
25639 if( z==0 ) return -1;
25640 quote = z[0];
25641 switch( quote ){
25642 case '\'': break;
25643 case '"': break;
25644 case '`': break; /* For MySQL compatibility */
25645 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
25646 default: return -1;
25647 }
25648 for(i=1, j=0;; i++){
25649 assert( z[i] );
25650 if( z[i]==quote ){
25651 if( z[i+1]==quote ){
25652 z[j++] = quote;
@@ -25657,11 +27237,10 @@
25657 }else{
25658 z[j++] = z[i];
25659 }
25660 }
25661 z[j] = 0;
25662 return j;
25663 }
25664
25665 /*
25666 ** Generate a Token object from a string
25667 */
@@ -25750,11 +27329,11 @@
25750 int esign = 1; /* sign of exponent */
25751 int e = 0; /* exponent */
25752 int eValid = 1; /* True exponent is either not used or is well-formed */
25753 double result;
25754 int nDigits = 0;
25755 int nonNum = 0;
25756
25757 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
25758 *pResult = 0.0; /* Default return value, in case of an error */
25759
25760 if( enc==SQLITE_UTF8 ){
@@ -25763,11 +27342,11 @@
25763 int i;
25764 incr = 2;
25765 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
25766 for(i=3-enc; i<length && z[i]==0; i+=2){}
25767 nonNum = i<length;
25768 zEnd = z+i+enc-3;
25769 z += (enc&1);
25770 }
25771
25772 /* skip leading spaces */
25773 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
@@ -25779,13 +27358,10 @@
25779 z+=incr;
25780 }else if( *z=='+' ){
25781 z+=incr;
25782 }
25783
25784 /* skip leading zeroes */
25785 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
25786
25787 /* copy max significant digits to significand */
25788 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
25789 s = s*10 + (*z - '0');
25790 z+=incr, nDigits++;
25791 }
@@ -25798,24 +27374,30 @@
25798 /* if decimal point is present */
25799 if( *z=='.' ){
25800 z+=incr;
25801 /* copy digits from after decimal to significand
25802 ** (decrease exponent by d to shift decimal right) */
25803 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
25804 s = s*10 + (*z - '0');
25805 z+=incr, nDigits++, d--;
 
 
 
25806 }
25807 /* skip non-significant digits */
25808 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
25809 }
25810 if( z>=zEnd ) goto do_atof_calc;
25811
25812 /* if exponent is present */
25813 if( *z=='e' || *z=='E' ){
25814 z+=incr;
25815 eValid = 0;
25816 if( z>=zEnd ) goto do_atof_calc;
 
 
 
 
 
25817 /* get sign of exponent */
25818 if( *z=='-' ){
25819 esign = -1;
25820 z+=incr;
25821 }else if( *z=='+' ){
@@ -25828,13 +27410,11 @@
25828 eValid = 1;
25829 }
25830 }
25831
25832 /* skip trailing spaces */
25833 if( nDigits && eValid ){
25834 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
25835 }
25836
25837 do_atof_calc:
25838 /* adjust exponent by d, and update sign */
25839 e = (e*esign) + d;
25840 if( e<0 ) {
@@ -25842,45 +27422,55 @@
25842 e *= -1;
25843 } else {
25844 esign = 1;
25845 }
25846
25847 /* if 0 significand */
25848 if( !s ) {
25849 /* In the IEEE 754 standard, zero is signed.
25850 ** Add the sign if we've seen at least one digit */
25851 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
25852 } else {
25853 /* attempt to reduce exponent */
25854 if( esign>0 ){
25855 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
25856 }else{
25857 while( !(s%10) && e>0 ) e--,s/=10;
 
 
 
 
 
 
 
 
 
 
25858 }
25859
25860 /* adjust the sign of significand */
25861 s = sign<0 ? -s : s;
25862
25863 /* if exponent, scale significand as appropriate
25864 ** and store in result. */
25865 if( e ){
25866 LONGDOUBLE_TYPE scale = 1.0;
25867 /* attempt to handle extremely small/large numbers better */
25868 if( e>307 && e<342 ){
25869 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
25870 if( esign<0 ){
25871 result = s / scale;
25872 result /= 1.0e+308;
25873 }else{
25874 result = s * scale;
25875 result *= 1.0e+308;
25876 }
25877 }else if( e>=342 ){
25878 if( esign<0 ){
25879 result = 0.0*s;
25880 }else{
25881 result = 1e308*1e308*s; /* Infinity */
 
 
25882 }
25883 }else{
25884 /* 1.0e+22 is the largest power of 10 than can be
25885 ** represented exactly. */
25886 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
@@ -25889,20 +27479,18 @@
25889 result = s / scale;
25890 }else{
25891 result = s * scale;
25892 }
25893 }
25894 } else {
25895 result = (double)s;
25896 }
25897 }
25898
25899 /* store the result */
25900 *pResult = result;
25901
25902 /* return true if number and no extra non-whitespace chracters after */
25903 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
25904 #else
25905 return !sqlite3Atoi64(z, pResult, length, enc);
25906 #endif /* SQLITE_OMIT_FLOATING_POINT */
25907 }
25908
@@ -25960,11 +27548,11 @@
25960 int incr;
25961 u64 u = 0;
25962 int neg = 0; /* assume positive */
25963 int i;
25964 int c = 0;
25965 int nonNum = 0;
25966 const char *zStart;
25967 const char *zEnd = zNum + length;
25968 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
25969 if( enc==SQLITE_UTF8 ){
25970 incr = 1;
@@ -25971,11 +27559,11 @@
25971 }else{
25972 incr = 2;
25973 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
25974 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
25975 nonNum = i<length;
25976 zEnd = zNum+i+enc-3;
25977 zNum += (enc&1);
25978 }
25979 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
25980 if( zNum<zEnd ){
25981 if( *zNum=='-' ){
@@ -25998,12 +27586,15 @@
25998 *pNum = (i64)u;
25999 }
26000 testcase( i==18 );
26001 testcase( i==19 );
26002 testcase( i==20 );
26003 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum)
26004 || i>19*incr || nonNum ){
 
 
 
26005 /* zNum is empty or contains non-numeric text or is longer
26006 ** than 19 digits (thus guaranteeing that it is too large) */
26007 return 1;
26008 }else if( i<19*incr ){
26009 /* Less than 19 digits, so we know that it fits in 64 bits */
@@ -26041,11 +27632,10 @@
26041 */
26042 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
26043 #ifndef SQLITE_OMIT_HEX_INTEGER
26044 if( z[0]=='0'
26045 && (z[1]=='x' || z[1]=='X')
26046 && sqlite3Isxdigit(z[2])
26047 ){
26048 u64 u = 0;
26049 int i, k;
26050 for(i=2; z[i]=='0'; i++){}
26051 for(k=i; sqlite3Isxdigit(z[k]); k++){
@@ -26803,11 +28393,11 @@
26803 LogEst y = 40;
26804 if( x<8 ){
26805 if( x<2 ) return 0;
26806 while( x<8 ){ y -= 10; x <<= 1; }
26807 }else{
26808 while( x>255 ){ y += 40; x >>= 4; }
26809 while( x>15 ){ y += 10; x >>= 1; }
26810 }
26811 return a[x&7] + y - 10;
26812 }
26813
@@ -26837,11 +28427,10 @@
26837 ** Note that this routine is only used when one or more of various
26838 ** non-standard compile-time options is enabled.
26839 */
26840 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
26841 u64 n;
26842 if( x<10 ) return 1;
26843 n = x%10;
26844 x /= 10;
26845 if( n>=5 ) n -= 2;
26846 else if( n>=1 ) n -= 1;
26847 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
@@ -26913,11 +28502,11 @@
26913 ** The hashing function.
26914 */
26915 static unsigned int strHash(const char *z){
26916 unsigned int h = 0;
26917 unsigned char c;
26918 while( (c = (unsigned char)*z++)!=0 ){
26919 h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
26920 }
26921 return h;
26922 }
26923
@@ -27006,11 +28595,11 @@
27006 ){
27007 HashElem *elem; /* Used to loop thru the element list */
27008 int count; /* Number of elements left to test */
27009 unsigned int h; /* The computed hash */
27010
27011 if( pH->ht ){
27012 struct _ht *pEntry;
27013 h = strHash(pKey) % pH->htsize;
27014 pEntry = &pH->ht[h];
27015 elem = pEntry->chain;
27016 count = pEntry->count;
@@ -27153,157 +28742,156 @@
27153 /* 10 */ "Vacuum" OpHelp(""),
27154 /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
27155 /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
27156 /* 13 */ "Goto" OpHelp(""),
27157 /* 14 */ "Gosub" OpHelp(""),
27158 /* 15 */ "Return" OpHelp(""),
27159 /* 16 */ "InitCoroutine" OpHelp(""),
27160 /* 17 */ "EndCoroutine" OpHelp(""),
27161 /* 18 */ "Yield" OpHelp(""),
27162 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
27163 /* 20 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
27164 /* 21 */ "Halt" OpHelp(""),
27165 /* 22 */ "Integer" OpHelp("r[P2]=P1"),
27166 /* 23 */ "Int64" OpHelp("r[P2]=P4"),
27167 /* 24 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
27168 /* 25 */ "Null" OpHelp("r[P2..P3]=NULL"),
27169 /* 26 */ "SoftNull" OpHelp("r[P1]=NULL"),
27170 /* 27 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
27171 /* 28 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
27172 /* 29 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
27173 /* 30 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
27174 /* 31 */ "SCopy" OpHelp("r[P2]=r[P1]"),
27175 /* 32 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
27176 /* 33 */ "ResultRow" OpHelp("output=r[P1@P2]"),
27177 /* 34 */ "CollSeq" OpHelp(""),
27178 /* 35 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
27179 /* 36 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
27180 /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
27181 /* 38 */ "MustBeInt" OpHelp(""),
27182 /* 39 */ "RealAffinity" OpHelp(""),
27183 /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
27184 /* 41 */ "Permutation" OpHelp(""),
27185 /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
27186 /* 43 */ "Jump" OpHelp(""),
27187 /* 44 */ "Once" OpHelp(""),
27188 /* 45 */ "If" OpHelp(""),
27189 /* 46 */ "IfNot" OpHelp(""),
27190 /* 47 */ "Column" OpHelp("r[P3]=PX"),
27191 /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
27192 /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
27193 /* 50 */ "Count" OpHelp("r[P2]=count()"),
27194 /* 51 */ "ReadCookie" OpHelp(""),
27195 /* 52 */ "SetCookie" OpHelp(""),
27196 /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
27197 /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
27198 /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
27199 /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
27200 /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
27201 /* 58 */ "SorterOpen" OpHelp(""),
27202 /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
27203 /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
27204 /* 61 */ "Close" OpHelp(""),
27205 /* 62 */ "ColumnsUsed" OpHelp(""),
27206 /* 63 */ "SeekLT" OpHelp("key=r[P3@P4]"),
27207 /* 64 */ "SeekLE" OpHelp("key=r[P3@P4]"),
27208 /* 65 */ "SeekGE" OpHelp("key=r[P3@P4]"),
27209 /* 66 */ "SeekGT" OpHelp("key=r[P3@P4]"),
27210 /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
27211 /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
27212 /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
27213 /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
27214 /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
27215 /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
27216 /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
27217 /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
27218 /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
27219 /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
27220 /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
27221 /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
27222 /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
27223 /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
27224 /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
27225 /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
27226 /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
27227 /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
27228 /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
27229 /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
27230 /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
27231 /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
27232 /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
27233 /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
27234 /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
27235 /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
27236 /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
27237 /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
27238 /* 95 */ "Delete" OpHelp(""),
27239 /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
27240 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
27241 /* 98 */ "ResetCount" OpHelp(""),
27242 /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
27243 /* 100 */ "SorterData" OpHelp("r[P2]=data"),
27244 /* 101 */ "RowKey" OpHelp("r[P2]=key"),
27245 /* 102 */ "RowData" OpHelp("r[P2]=data"),
27246 /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
27247 /* 104 */ "NullRow" OpHelp(""),
27248 /* 105 */ "Last" OpHelp(""),
27249 /* 106 */ "SorterSort" OpHelp(""),
27250 /* 107 */ "Sort" OpHelp(""),
27251 /* 108 */ "Rewind" OpHelp(""),
27252 /* 109 */ "SorterInsert" OpHelp(""),
27253 /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
27254 /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
27255 /* 112 */ "Seek" OpHelp("Move P3 to P1.rowid"),
27256 /* 113 */ "IdxRowid" OpHelp("r[P2]=rowid"),
27257 /* 114 */ "IdxLE" OpHelp("key=r[P3@P4]"),
27258 /* 115 */ "IdxGT" OpHelp("key=r[P3@P4]"),
27259 /* 116 */ "IdxLT" OpHelp("key=r[P3@P4]"),
27260 /* 117 */ "IdxGE" OpHelp("key=r[P3@P4]"),
27261 /* 118 */ "Destroy" OpHelp(""),
27262 /* 119 */ "Clear" OpHelp(""),
27263 /* 120 */ "ResetSorter" OpHelp(""),
27264 /* 121 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
27265 /* 122 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
27266 /* 123 */ "ParseSchema" OpHelp(""),
27267 /* 124 */ "LoadAnalysis" OpHelp(""),
27268 /* 125 */ "DropTable" OpHelp(""),
27269 /* 126 */ "DropIndex" OpHelp(""),
27270 /* 127 */ "DropTrigger" OpHelp(""),
27271 /* 128 */ "IntegrityCk" OpHelp(""),
27272 /* 129 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
27273 /* 130 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
27274 /* 131 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
27275 /* 132 */ "Program" OpHelp(""),
27276 /* 133 */ "Real" OpHelp("r[P2]=P4"),
27277 /* 134 */ "Param" OpHelp(""),
27278 /* 135 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
27279 /* 136 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
27280 /* 137 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
27281 /* 138 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
27282 /* 139 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
27283 /* 140 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
27284 /* 141 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
27285 /* 142 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
27286 /* 143 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
27287 /* 144 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
27288 /* 145 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
27289 /* 146 */ "IncrVacuum" OpHelp(""),
27290 /* 147 */ "Expire" OpHelp(""),
27291 /* 148 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
27292 /* 149 */ "VBegin" OpHelp(""),
27293 /* 150 */ "VCreate" OpHelp(""),
27294 /* 151 */ "VDestroy" OpHelp(""),
27295 /* 152 */ "VOpen" OpHelp(""),
27296 /* 153 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
27297 /* 154 */ "VNext" OpHelp(""),
27298 /* 155 */ "VRename" OpHelp(""),
27299 /* 156 */ "Pagecount" OpHelp(""),
27300 /* 157 */ "MaxPgcnt" OpHelp(""),
27301 /* 158 */ "Init" OpHelp("Start at P2"),
27302 /* 159 */ "CursorHint" OpHelp(""),
27303 /* 160 */ "Noop" OpHelp(""),
27304 /* 161 */ "Explain" OpHelp(""),
27305 };
27306 return azName[i];
27307 }
27308 #endif
27309
@@ -27912,11 +29500,11 @@
27912 #if defined(USE_PREAD64)
27913 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
27914 #else
27915 { "pread64", (sqlite3_syscall_ptr)0, 0 },
27916 #endif
27917 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
27918
27919 { "write", (sqlite3_syscall_ptr)write, 0 },
27920 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
27921
27922 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
@@ -27930,11 +29518,11 @@
27930 #if defined(USE_PREAD64)
27931 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
27932 #else
27933 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
27934 #endif
27935 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
27936 aSyscall[13].pCurrent)
27937
27938 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
27939 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
27940
@@ -29009,20 +30597,26 @@
29009 static int unixLock(sqlite3_file *id, int eFileLock){
29010 /* The following describes the implementation of the various locks and
29011 ** lock transitions in terms of the POSIX advisory shared and exclusive
29012 ** lock primitives (called read-locks and write-locks below, to avoid
29013 ** confusion with SQLite lock names). The algorithms are complicated
29014 ** slightly in order to be compatible with windows systems simultaneously
29015 ** accessing the same database file, in case that is ever required.
29016 **
29017 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
29018 ** byte', each single bytes at well known offsets, and the 'shared byte
29019 ** range', a range of 510 bytes at a well known offset.
29020 **
29021 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
29022 ** byte'. If this is successful, a random byte from the 'shared byte
29023 ** range' is read-locked and the lock on the 'pending byte' released.
 
 
 
 
 
 
29024 **
29025 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
29026 ** A RESERVED lock is implemented by grabbing a write-lock on the
29027 ** 'reserved byte'.
29028 **
@@ -29037,15 +30631,10 @@
29037 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
29038 ** implemented by obtaining a write-lock on the entire 'shared byte
29039 ** range'. Since all other locks require a read-lock on one of the bytes
29040 ** within this range, this ensures that no other locks are held on the
29041 ** database.
29042 **
29043 ** The reason a single byte cannot be used instead of the 'shared byte
29044 ** range' is that some versions of windows do not support read-locks. By
29045 ** locking a random byte from a range, concurrent SHARED locks may exist
29046 ** even if the locking primitive used is always a write-lock.
29047 */
29048 int rc = SQLITE_OK;
29049 unixFile *pFile = (unixFile*)id;
29050 unixInodeInfo *pInode;
29051 struct flock lock;
@@ -31794,14 +33383,16 @@
31794 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
31795 #endif
31796 pShmNode->h = -1;
31797 pDbFd->pInode->pShmNode = pShmNode;
31798 pShmNode->pInode = pDbFd->pInode;
31799 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
31800 if( pShmNode->mutex==0 ){
31801 rc = SQLITE_NOMEM_BKPT;
31802 goto shm_open_err;
 
 
31803 }
31804
31805 if( pInode->bProcessLock==0 ){
31806 int openFlags = O_RDWR | O_CREAT;
31807 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
@@ -32916,24 +34507,28 @@
32916 "/var/tmp",
32917 "/usr/tmp",
32918 "/tmp",
32919 "."
32920 };
32921 unsigned int i;
32922 struct stat buf;
32923 const char *zDir = sqlite3_temp_directory;
32924
32925 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
32926 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
32927 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
32928 if( zDir==0 ) continue;
32929 if( osStat(zDir, &buf) ) continue;
32930 if( !S_ISDIR(buf.st_mode) ) continue;
32931 if( osAccess(zDir, 07) ) continue;
32932 break;
32933 }
32934 return zDir;
 
 
 
 
32935 }
32936
32937 /*
32938 ** Create a temporary file name in zBuf. zBuf must be allocated
32939 ** by the calling process and must be big enough to hold at least
@@ -32945,13 +34540,15 @@
32945
32946 /* It's odd to simulate an io-error here, but really this is just
32947 ** using the io-error infrastructure to test that SQLite handles this
32948 ** function failing.
32949 */
 
32950 SimulateIOError( return SQLITE_IOERR );
32951
32952 zDir = unixTempFileDir();
 
32953 do{
32954 u64 r;
32955 sqlite3_randomness(sizeof(r), &r);
32956 assert( nBuf>2 );
32957 zBuf[nBuf-2] = 0;
@@ -36549,12 +38146,12 @@
36549 */
36550 SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
36551 int rc;
36552 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
36553 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
36554 MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
36555 MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
36556 sqlite3_mutex_enter(pMaster);
36557 sqlite3_mutex_enter(pMem);
36558 winMemAssertMagic();
36559 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
36560 /*
@@ -36595,10 +38192,16 @@
36595 SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
36596 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
36597 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
36598 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
36599 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
 
 
 
 
 
 
36600 #if defined(SQLITE_WIN32_HAS_ANSI)
36601 if( nMin>0 ){
36602 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
36603 memcpy(zDbgBuf, zBuf, nMin);
36604 osOutputDebugStringA(zDbgBuf);
@@ -36920,151 +38523,248 @@
36920 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
36921 }
36922 #endif /* SQLITE_WIN32_MALLOC */
36923
36924 /*
36925 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
36926 **
36927 ** Space to hold the returned string is obtained from malloc.
36928 */
36929 static LPWSTR winUtf8ToUnicode(const char *zFilename){
36930 int nChar;
36931 LPWSTR zWideFilename;
36932
36933 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
36934 if( nChar==0 ){
36935 return 0;
36936 }
36937 zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
36938 if( zWideFilename==0 ){
36939 return 0;
36940 }
36941 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
36942 nChar);
36943 if( nChar==0 ){
36944 sqlite3_free(zWideFilename);
36945 zWideFilename = 0;
36946 }
36947 return zWideFilename;
36948 }
36949
36950 /*
36951 ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
36952 ** obtained from sqlite3_malloc().
 
36953 */
36954 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
36955 int nByte;
36956 char *zFilename;
36957
36958 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
36959 if( nByte == 0 ){
36960 return 0;
36961 }
36962 zFilename = sqlite3MallocZero( nByte );
36963 if( zFilename==0 ){
36964 return 0;
36965 }
36966 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
36967 0, 0);
36968 if( nByte == 0 ){
36969 sqlite3_free(zFilename);
36970 zFilename = 0;
36971 }
36972 return zFilename;
36973 }
36974
36975 /*
36976 ** Convert an ANSI string to Microsoft Unicode, based on the
36977 ** current codepage settings for file apis.
36978 **
36979 ** Space to hold the returned string is obtained
36980 ** from sqlite3_malloc.
36981 */
36982 static LPWSTR winMbcsToUnicode(const char *zFilename){
36983 int nByte;
36984 LPWSTR zMbcsFilename;
36985 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
36986
36987 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
36988 0)*sizeof(WCHAR);
36989 if( nByte==0 ){
36990 return 0;
36991 }
36992 zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
36993 if( zMbcsFilename==0 ){
36994 return 0;
36995 }
36996 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
36997 nByte);
36998 if( nByte==0 ){
36999 sqlite3_free(zMbcsFilename);
37000 zMbcsFilename = 0;
37001 }
37002 return zMbcsFilename;
37003 }
37004
37005 /*
37006 ** Convert Microsoft Unicode to multi-byte character string, based on the
37007 ** user's ANSI codepage.
37008 **
37009 ** Space to hold the returned string is obtained from
37010 ** sqlite3_malloc().
37011 */
37012 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
37013 int nByte;
37014 char *zFilename;
37015 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
37016
37017 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
37018 if( nByte == 0 ){
37019 return 0;
37020 }
37021 zFilename = sqlite3MallocZero( nByte );
37022 if( zFilename==0 ){
37023 return 0;
37024 }
37025 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
37026 nByte, 0, 0);
37027 if( nByte == 0 ){
37028 sqlite3_free(zFilename);
37029 zFilename = 0;
37030 }
37031 return zFilename;
37032 }
37033
37034 /*
37035 ** Convert multibyte character string to UTF-8. Space to hold the
37036 ** returned string is obtained from sqlite3_malloc().
37037 */
37038 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
37039 char *zFilenameUtf8;
37040 LPWSTR zTmpWide;
37041
37042 zTmpWide = winMbcsToUnicode(zFilename);
37043 if( zTmpWide==0 ){
37044 return 0;
37045 }
37046 zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
37047 sqlite3_free(zTmpWide);
37048 return zFilenameUtf8;
37049 }
37050
37051 /*
37052 ** Convert UTF-8 to multibyte character string. Space to hold the
37053 ** returned string is obtained from sqlite3_malloc().
37054 */
37055 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
37056 char *zFilenameMbcs;
37057 LPWSTR zTmpWide;
37058
37059 zTmpWide = winUtf8ToUnicode(zFilename);
37060 if( zTmpWide==0 ){
37061 return 0;
37062 }
37063 zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
37064 sqlite3_free(zTmpWide);
37065 return zFilenameMbcs;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37066 }
37067
37068 /*
37069 ** This function sets the data directory or the temporary directory based on
37070 ** the provided arguments. The type argument must be 1 in order to set the
@@ -37162,11 +38862,11 @@
37162 0,
37163 0);
37164 if( dwLen > 0 ){
37165 /* allocate a buffer and convert to UTF8 */
37166 sqlite3BeginBenignMalloc();
37167 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
37168 sqlite3EndBenignMalloc();
37169 /* free the system buffer allocated by FormatMessage */
37170 osLocalFree(zTemp);
37171 }
37172 }
@@ -37304,20 +39004,21 @@
37304 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
37305 );
37306 }
37307 }
37308
37309 #if SQLITE_OS_WINCE
37310 /*************************************************************************
37311 ** This section contains code for WinCE only.
37312 */
37313 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
37314 /*
37315 ** The MSVC CRT on Windows CE may not have a localtime() function. So
37316 ** create a substitute.
37317 */
37318 /* #include <time.h> */
 
37319 struct tm *__cdecl localtime(const time_t *t)
37320 {
37321 static struct tm y;
37322 FILETIME uTm, lTm;
37323 SYSTEMTIME pTm;
@@ -37337,10 +39038,14 @@
37337 y.tm_sec = pTm.wSecond;
37338 return &y;
37339 }
37340 #endif
37341
 
 
 
 
37342 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
37343
37344 /*
37345 ** Acquire a lock on the handle h
37346 */
@@ -38350,13 +40055,12 @@
38350 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
38351 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
38352 ** the PENDING_LOCK byte is temporary.
38353 */
38354 newLocktype = pFile->locktype;
38355 if( (pFile->locktype==NO_LOCK)
38356 || ( (locktype==EXCLUSIVE_LOCK)
38357 && (pFile->locktype==RESERVED_LOCK))
38358 ){
38359 int cnt = 3;
38360 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
38361 PENDING_BYTE, 0, 1, 0))==0 ){
38362 /* Try 3 times to get the pending lock. This is needed to work
@@ -38946,14 +40650,16 @@
38946 pNew = 0;
38947 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
38948 pShmNode->pNext = winShmNodeList;
38949 winShmNodeList = pShmNode;
38950
38951 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
38952 if( pShmNode->mutex==0 ){
38953 rc = SQLITE_IOERR_NOMEM_BKPT;
38954 goto shm_open_err;
 
 
38955 }
38956
38957 rc = winOpen(pDbFd->pVfs,
38958 pShmNode->zFilename, /* Name of the file (UTF-8) */
38959 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
@@ -39607,11 +41313,11 @@
39607 if( osIsNT() ){
39608 zConverted = winUnicodeToUtf8(zFilename);
39609 }
39610 #ifdef SQLITE_WIN32_HAS_ANSI
39611 else{
39612 zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
39613 }
39614 #endif
39615 /* caller will handle out of memory */
39616 return zConverted;
39617 }
@@ -39628,11 +41334,11 @@
39628 if( osIsNT() ){
39629 zConverted = winUtf8ToUnicode(zFilename);
39630 }
39631 #ifdef SQLITE_WIN32_HAS_ANSI
39632 else{
39633 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
39634 }
39635 #endif
39636 /* caller will handle out of memory */
39637 return zConverted;
39638 }
@@ -39829,11 +41535,11 @@
39829 sqlite3_free(zBuf);
39830 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
39831 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
39832 "winGetTempname3", 0);
39833 }
39834 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
39835 if( zUtf8 ){
39836 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
39837 sqlite3_free(zUtf8);
39838 }else{
39839 sqlite3_free(zBuf);
@@ -40607,11 +42313,11 @@
40607 sqlite3_free(zTemp);
40608 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
40609 "winFullPathname4", zRelative);
40610 }
40611 sqlite3_free(zConverted);
40612 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
40613 sqlite3_free(zTemp);
40614 }
40615 #endif
40616 if( zOut ){
40617 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
@@ -41413,11 +43119,33 @@
41413 ** This file implements that page cache.
41414 */
41415 /* #include "sqliteInt.h" */
41416
41417 /*
41418 ** A complete page cache is an instance of this structure.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41419 */
41420 struct PCache {
41421 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
41422 PgHdr *pSynced; /* Last synced page in dirty page list */
41423 int nRefSum; /* Sum of ref counts over all pages */
@@ -41429,10 +43157,99 @@
41429 u8 eCreate; /* eCreate value for for xFetch() */
41430 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
41431 void *pStress; /* Argument to xStress */
41432 sqlite3_pcache *pCache; /* Pluggable cache module */
41433 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41434
41435 /********************************** Linked List Management ********************/
41436
41437 /* Allowed values for second argument to pcacheManageDirtyList() */
41438 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
@@ -41446,21 +43263,20 @@
41446 ** the dirty list. Doing both moves pPage to the front of the dirty list.
41447 */
41448 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
41449 PCache *p = pPage->pCache;
41450
 
 
 
41451 if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
41452 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
41453 assert( pPage->pDirtyPrev || pPage==p->pDirty );
41454
41455 /* Update the PCache1.pSynced variable if necessary. */
41456 if( p->pSynced==pPage ){
41457 PgHdr *pSynced = pPage->pDirtyPrev;
41458 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
41459 pSynced = pSynced->pDirtyPrev;
41460 }
41461 p->pSynced = pSynced;
41462 }
41463
41464 if( pPage->pDirtyNext ){
41465 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
41466 }else{
@@ -41468,14 +43284,19 @@
41468 p->pDirtyTail = pPage->pDirtyPrev;
41469 }
41470 if( pPage->pDirtyPrev ){
41471 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
41472 }else{
 
 
 
 
41473 assert( pPage==p->pDirty );
41474 p->pDirty = pPage->pDirtyNext;
41475 if( p->pDirty==0 && p->bPurgeable ){
41476 assert( p->eCreate==1 );
 
41477 p->eCreate = 2;
41478 }
41479 }
41480 pPage->pDirtyNext = 0;
41481 pPage->pDirtyPrev = 0;
@@ -41493,23 +43314,34 @@
41493 assert( p->eCreate==2 );
41494 p->eCreate = 1;
41495 }
41496 }
41497 p->pDirty = pPage;
41498 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
 
 
 
 
 
 
 
 
41499 p->pSynced = pPage;
41500 }
41501 }
 
41502 }
41503
41504 /*
41505 ** Wrapper around the pluggable caches xUnpin method. If the cache is
41506 ** being used for an in-memory database, this function is a no-op.
41507 */
41508 static void pcacheUnpin(PgHdr *p){
41509 if( p->pCache->bPurgeable ){
 
41510 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
 
41511 }
41512 }
41513
41514 /*
41515 ** Compute the number of pages of cache requested. p->szCache is the
@@ -41575,10 +43407,11 @@
41575 p->eCreate = 2;
41576 p->xStress = xStress;
41577 p->pStress = pStress;
41578 p->szCache = 100;
41579 p->szSpill = 1;
 
41580 return sqlite3PcacheSetPageSize(p, szPage);
41581 }
41582
41583 /*
41584 ** Change the page size for PCache object. The caller must ensure that there
@@ -41597,10 +43430,11 @@
41597 if( pCache->pCache ){
41598 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
41599 }
41600 pCache->pCache = pNew;
41601 pCache->szPage = szPage;
 
41602 }
41603 return SQLITE_OK;
41604 }
41605
41606 /*
@@ -41631,15 +43465,17 @@
41631 PCache *pCache, /* Obtain the page from this cache */
41632 Pgno pgno, /* Page number to obtain */
41633 int createFlag /* If true, create page if it does not exist already */
41634 ){
41635 int eCreate;
 
41636
41637 assert( pCache!=0 );
41638 assert( pCache->pCache!=0 );
41639 assert( createFlag==3 || createFlag==0 );
41640 assert( pgno>0 );
 
41641
41642 /* eCreate defines what to do if the page does not exist.
41643 ** 0 Do not allocate a new page. (createFlag==0)
41644 ** 1 Allocate a new page if doing so is inexpensive.
41645 ** (createFlag==1 AND bPurgeable AND pDirty)
@@ -41648,16 +43484,19 @@
41648 */
41649 eCreate = createFlag & pCache->eCreate;
41650 assert( eCreate==0 || eCreate==1 || eCreate==2 );
41651 assert( createFlag==0 || pCache->eCreate==eCreate );
41652 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
41653 return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
 
 
 
41654 }
41655
41656 /*
41657 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
41658 ** page because new clean pages are available for reuse and the cache
41659 ** size limit has been reached, then this routine can be invoked to
41660 ** try harder to allocate a page. This routine might invoke the stress
41661 ** callback to spill dirty pages to the journal. It will then try to
41662 ** allocate the new page and will only fail to allocate a new page on
41663 ** an OOM error.
@@ -41675,11 +43514,15 @@
41675 if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
41676 /* Find a dirty page to write-out and recycle. First try to find a
41677 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
41678 ** cleared), but if that is not possible settle for any other
41679 ** unreferenced dirty page.
41680 */
 
 
 
 
41681 for(pPg=pCache->pSynced;
41682 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
41683 pPg=pPg->pDirtyPrev
41684 );
41685 pCache->pSynced = pPg;
@@ -41693,11 +43536,13 @@
41693 "spill page %d making room for %d - cache used: %d/%d",
41694 pPg->pgno, pgno,
41695 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
41696 numberOfCachePages(pCache));
41697 #endif
 
41698 rc = pCache->xStress(pCache->pStress, pPg);
 
41699 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
41700 return rc;
41701 }
41702 }
41703 }
@@ -41753,10 +43598,11 @@
41753 if( !pPgHdr->pPage ){
41754 return pcacheFetchFinishWithInit(pCache, pgno, pPage);
41755 }
41756 pCache->nRefSum++;
41757 pPgHdr->nRef++;
 
41758 return pPgHdr;
41759 }
41760
41761 /*
41762 ** Decrement the reference count on a page. If the page is clean and the
@@ -41766,12 +43612,15 @@
41766 assert( p->nRef>0 );
41767 p->pCache->nRefSum--;
41768 if( (--p->nRef)==0 ){
41769 if( p->flags&PGHDR_CLEAN ){
41770 pcacheUnpin(p);
41771 }else if( p->pDirtyPrev!=0 ){
41772 /* Move the page to the head of the dirty list. */
 
 
 
41773 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
41774 }
41775 }
41776 }
41777
@@ -41778,10 +43627,11 @@
41778 /*
41779 ** Increase the reference count of a supplied page by 1.
41780 */
41781 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
41782 assert(p->nRef>0);
 
41783 p->nRef++;
41784 p->pCache->nRefSum++;
41785 }
41786
41787 /*
@@ -41789,10 +43639,11 @@
41789 ** page. This function deletes that reference, so after it returns the
41790 ** page pointed to by p is invalid.
41791 */
41792 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
41793 assert( p->nRef==1 );
 
41794 if( p->flags&PGHDR_DIRTY ){
41795 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
41796 }
41797 p->pCache->nRefSum--;
41798 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
@@ -41802,30 +43653,36 @@
41802 ** Make sure the page is marked as dirty. If it isn't dirty already,
41803 ** make it so.
41804 */
41805 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
41806 assert( p->nRef>0 );
41807 if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
 
41808 p->flags &= ~PGHDR_DONT_WRITE;
41809 if( p->flags & PGHDR_CLEAN ){
41810 p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
 
41811 assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
41812 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
41813 }
 
41814 }
41815 }
41816
41817 /*
41818 ** Make sure the page is marked as clean. If it isn't clean already,
41819 ** make it so.
41820 */
41821 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
41822 if( (p->flags & PGHDR_DIRTY) ){
 
41823 assert( (p->flags & PGHDR_CLEAN)==0 );
41824 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
41825 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
41826 p->flags |= PGHDR_CLEAN;
 
 
41827 if( p->nRef==0 ){
41828 pcacheUnpin(p);
41829 }
41830 }
41831 }
@@ -41833,14 +43690,27 @@
41833 /*
41834 ** Make every page in the cache clean.
41835 */
41836 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
41837 PgHdr *p;
 
41838 while( (p = pCache->pDirty)!=0 ){
41839 sqlite3PcacheMakeClean(p);
41840 }
41841 }
 
 
 
 
 
 
 
 
 
 
 
 
41842
41843 /*
41844 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
41845 */
41846 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
@@ -41856,10 +43726,12 @@
41856 */
41857 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
41858 PCache *pCache = p->pCache;
41859 assert( p->nRef>0 );
41860 assert( newPgno>0 );
 
 
41861 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
41862 p->pgno = newPgno;
41863 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
41864 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
41865 }
@@ -41876,18 +43748,19 @@
41876 */
41877 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
41878 if( pCache->pCache ){
41879 PgHdr *p;
41880 PgHdr *pNext;
 
41881 for(p=pCache->pDirty; p; p=pNext){
41882 pNext = p->pDirtyNext;
41883 /* This routine never gets call with a positive pgno except right
41884 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
41885 ** it must be that pgno==0.
41886 */
41887 assert( p->pgno>0 );
41888 if( ALWAYS(p->pgno>pgno) ){
41889 assert( p->flags&PGHDR_DIRTY );
41890 sqlite3PcacheMakeClean(p);
41891 }
41892 }
41893 if( pgno==0 && pCache->nRefSum ){
@@ -41906,10 +43779,11 @@
41906 /*
41907 ** Close a cache.
41908 */
41909 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
41910 assert( pCache->pCache!=0 );
 
41911 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
41912 }
41913
41914 /*
41915 ** Discard the contents of the cache.
@@ -42074,10 +43948,21 @@
42074 ** Return the size of the header added by this middleware layer
42075 ** in the page-cache hierarchy.
42076 */
42077 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
42078
 
 
 
 
 
 
 
 
 
 
 
42079
42080 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
42081 /*
42082 ** For all dirty pages currently in the cache, invoke the specified
42083 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
@@ -42783,12 +44668,12 @@
42783 pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
42784 #endif
42785
42786 #if SQLITE_THREADSAFE
42787 if( sqlite3GlobalConfig.bCoreMutex ){
42788 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
42789 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
42790 }
42791 #endif
42792 if( pcache1.separateCache
42793 && sqlite3GlobalConfig.nPage!=0
42794 && sqlite3GlobalConfig.pPage==0
@@ -43390,12 +45275,13 @@
43390 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
43391 ** The cost of a TEST using the same batch number is O(logN). The cost
43392 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
43393 ** primitives are constant time. The cost of DESTROY is O(N).
43394 **
43395 ** There is an added cost of O(N) when switching between TEST and
43396 ** SMALLEST primitives.
 
43397 */
43398 /* #include "sqliteInt.h" */
43399
43400
43401 /*
@@ -43512,11 +45398,13 @@
43512 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
43513 ** routine returns NULL.
43514 */
43515 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
43516 assert( p!=0 );
43517 if( p->nFresh==0 ){
 
 
43518 struct RowSetChunk *pNew;
43519 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
43520 if( pNew==0 ){
43521 return 0;
43522 }
@@ -43546,11 +45434,13 @@
43546 if( pEntry==0 ) return;
43547 pEntry->v = rowid;
43548 pEntry->pRight = 0;
43549 pLast = p->pLast;
43550 if( pLast ){
43551 if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
 
 
43552 p->rsFlags &= ~ROWSET_SORTED;
43553 }
43554 pLast->pRight = pEntry;
43555 }else{
43556 p->pEntry = pEntry;
@@ -43668,27 +45558,33 @@
43668 struct RowSetEntry **ppList,
43669 int iDepth
43670 ){
43671 struct RowSetEntry *p; /* Root of the new tree */
43672 struct RowSetEntry *pLeft; /* Left subtree */
43673 if( *ppList==0 ){
43674 return 0;
 
43675 }
43676 if( iDepth==1 ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43677 p = *ppList;
43678 *ppList = p->pRight;
43679 p->pLeft = p->pRight = 0;
43680 return p;
43681 }
43682 pLeft = rowSetNDeepTree(ppList, iDepth-1);
43683 p = *ppList;
43684 if( p==0 ){
43685 return pLeft;
43686 }
43687 p->pLeft = pLeft;
43688 *ppList = p->pRight;
43689 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
43690 return p;
43691 }
43692
43693 /*
43694 ** Convert a sorted list of elements into a binary tree. Make the tree
@@ -43711,63 +45607,41 @@
43711 p->pRight = rowSetNDeepTree(&pList, iDepth);
43712 }
43713 return p;
43714 }
43715
43716 /*
43717 ** Take all the entries on p->pEntry and on the trees in p->pForest and
43718 ** sort them all together into one big ordered list on p->pEntry.
43719 **
43720 ** This routine should only be called once in the life of a RowSet.
43721 */
43722 static void rowSetToList(RowSet *p){
43723
43724 /* This routine is called only once */
43725 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
43726
43727 if( (p->rsFlags & ROWSET_SORTED)==0 ){
43728 p->pEntry = rowSetEntrySort(p->pEntry);
43729 }
43730
43731 /* While this module could theoretically support it, sqlite3RowSetNext()
43732 ** is never called after sqlite3RowSetText() for the same RowSet. So
43733 ** there is never a forest to deal with. Should this change, simply
43734 ** remove the assert() and the #if 0. */
43735 assert( p->pForest==0 );
43736 #if 0
43737 while( p->pForest ){
43738 struct RowSetEntry *pTree = p->pForest->pLeft;
43739 if( pTree ){
43740 struct RowSetEntry *pHead, *pTail;
43741 rowSetTreeToList(pTree, &pHead, &pTail);
43742 p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
43743 }
43744 p->pForest = p->pForest->pRight;
43745 }
43746 #endif
43747 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
43748 }
43749
43750 /*
43751 ** Extract the smallest element from the RowSet.
43752 ** Write the element into *pRowid. Return 1 on success. Return
43753 ** 0 if the RowSet is already empty.
43754 **
43755 ** After this routine has been called, the sqlite3RowSetInsert()
43756 ** routine may not be called again.
 
 
 
 
 
43757 */
43758 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
43759 assert( p!=0 );
 
43760
43761 /* Merge the forest into a single sorted list on first call */
43762 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
 
 
 
 
 
43763
43764 /* Return the next entry on the list */
43765 if( p->pEntry ){
43766 *pRowid = p->pEntry->v;
43767 p->pEntry = p->pEntry->pRight;
43768 if( p->pEntry==0 ){
 
43769 sqlite3RowSetClear(p);
43770 }
43771 return 1;
43772 }else{
43773 return 0;
@@ -43786,17 +45660,19 @@
43786 struct RowSetEntry *p, *pTree;
43787
43788 /* This routine is never called after sqlite3RowSetNext() */
43789 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
43790
43791 /* Sort entries into the forest on the first test of a new batch
 
43792 */
43793 if( iBatch!=pRowSet->iBatch ){
43794 p = pRowSet->pEntry;
43795 if( p ){
43796 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
43797 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
 
43798 p = rowSetEntrySort(p);
43799 }
43800 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
43801 ppPrevTree = &pTree->pRight;
43802 if( pTree->pLeft==0 ){
@@ -44866,10 +46742,11 @@
44866 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
44867 ** is therefore not possible for an in-memory pager to enter the ERROR
44868 ** state.
44869 */
44870 if( MEMDB ){
 
44871 assert( p->noSync );
44872 assert( p->journalMode==PAGER_JOURNALMODE_OFF
44873 || p->journalMode==PAGER_JOURNALMODE_MEMORY
44874 );
44875 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
@@ -44952,11 +46829,11 @@
44952 /* There must be at least one outstanding reference to the pager if
44953 ** in ERROR state. Otherwise the pager should have already dropped
44954 ** back to OPEN state.
44955 */
44956 assert( pPager->errCode!=SQLITE_OK );
44957 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
44958 break;
44959 }
44960
44961 return 1;
44962 }
@@ -45164,10 +47041,12 @@
45164 }
45165 }
45166
45167 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
45168 }
 
 
45169 #endif
45170
45171 /*
45172 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
45173 ** on the cache using a hash function. This is used for testing
@@ -45812,17 +47691,21 @@
45812 /* If Pager.errCode is set, the contents of the pager cache cannot be
45813 ** trusted. Now that there are no outstanding references to the pager,
45814 ** it can safely move back to PAGER_OPEN state. This happens in both
45815 ** normal and exclusive-locking mode.
45816 */
 
45817 if( pPager->errCode ){
45818 assert( !MEMDB );
45819 pager_reset(pPager);
45820 pPager->changeCountDone = pPager->tempFile;
45821 pPager->eState = PAGER_OPEN;
45822 pPager->errCode = SQLITE_OK;
 
 
45823 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
 
45824 }
45825
45826 pPager->journalOff = 0;
45827 pPager->journalHdr = 0;
45828 pPager->setMaster = 0;
@@ -45861,10 +47744,33 @@
45861 }
45862 return rc;
45863 }
45864
45865 static int pager_truncate(Pager *pPager, Pgno nPage);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45866
45867 /*
45868 ** This routine ends a transaction. A transaction is usually ended by
45869 ** either a COMMIT or a ROLLBACK operation. This routine may be called
45870 ** after rollback of a hot-journal, or if an error occurs while opening
@@ -45965,11 +47871,11 @@
45965 }
45966 pPager->journalOff = 0;
45967 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45968 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
45969 ){
45970 rc = zeroJournalHdr(pPager, hasMaster);
45971 pPager->journalOff = 0;
45972 }else{
45973 /* This branch may be executed with Pager.journalMode==MEMORY if
45974 ** a hot-journal was just rolled back. In this case the journal
45975 ** file should be closed and deleted. If this connection writes to
@@ -46000,12 +47906,18 @@
46000 #endif
46001
46002 sqlite3BitvecDestroy(pPager->pInJournal);
46003 pPager->pInJournal = 0;
46004 pPager->nRec = 0;
46005 sqlite3PcacheCleanAll(pPager->pPCache);
46006 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
 
 
 
 
 
 
46007
46008 if( pagerUseWal(pPager) ){
46009 /* Drop the WAL write-lock, if any. Also, if the connection was in
46010 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
46011 ** lock held on the database file.
@@ -46285,11 +48197,11 @@
46285 pPg = 0;
46286 }else{
46287 pPg = sqlite3PagerLookup(pPager, pgno);
46288 }
46289 assert( pPg || !MEMDB );
46290 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
46291 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
46292 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
46293 (isMainJrnl?"main-journal":"sub-journal")
46294 ));
46295 if( isMainJrnl ){
@@ -46335,11 +48247,10 @@
46335 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
46336 rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
46337 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
46338 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
46339 if( rc!=SQLITE_OK ) return rc;
46340 pPg->flags &= ~PGHDR_NEED_READ;
46341 sqlite3PcacheMakeDirty(pPg);
46342 }
46343 if( pPg ){
46344 /* No page should ever be explicitly rolled back that is in use, except
46345 ** for page 1 which is held in use in order to keep the lock on the
@@ -46349,33 +48260,14 @@
46349 */
46350 void *pData;
46351 pData = pPg->pData;
46352 memcpy(pData, (u8*)aData, pPager->pageSize);
46353 pPager->xReiniter(pPg);
46354 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
46355 /* If the contents of this page were just restored from the main
46356 ** journal file, then its content must be as they were when the
46357 ** transaction was first opened. In this case we can mark the page
46358 ** as clean, since there will be no need to write it out to the
46359 ** database.
46360 **
46361 ** There is one exception to this rule. If the page is being rolled
46362 ** back as part of a savepoint (or statement) rollback from an
46363 ** unsynced portion of the main journal file, then it is not safe
46364 ** to mark the page as clean. This is because marking the page as
46365 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
46366 ** already in the journal file (recorded in Pager.pInJournal) and
46367 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
46368 ** again within this transaction, it will be marked as dirty but
46369 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
46370 ** be written out into the database file before its journal file
46371 ** segment is synced. If a crash occurs during or following this,
46372 ** database corruption may ensue.
46373 */
46374 assert( !pagerUseWal(pPager) );
46375 sqlite3PcacheMakeClean(pPg);
46376 }
46377 pager_set_pagehash(pPg);
46378
46379 /* If this was page 1, then restore the value of Pager.dbFileVers.
46380 ** Do this before any decoding. */
46381 if( pgno==1 ){
@@ -47162,25 +49054,24 @@
47162 ** available from the WAL sub-system if the log file is empty or
47163 ** contains no valid committed transactions.
47164 */
47165 assert( pPager->eState==PAGER_OPEN );
47166 assert( pPager->eLock>=SHARED_LOCK );
 
 
47167 nPage = sqlite3WalDbsize(pPager->pWal);
47168
47169 /* If the number of pages in the database is not available from the
47170 ** WAL sub-system, determine the page counte based on the size of
47171 ** the database file. If the size of the database file is not an
47172 ** integer multiple of the page-size, round up the result.
47173 */
47174 if( nPage==0 ){
47175 i64 n = 0; /* Size of db file in bytes */
47176 assert( isOpen(pPager->fd) || pPager->tempFile );
47177 if( isOpen(pPager->fd) ){
47178 int rc = sqlite3OsFileSize(pPager->fd, &n);
47179 if( rc!=SQLITE_OK ){
47180 return rc;
47181 }
47182 }
47183 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
47184 }
47185
47186 /* If the current number of pages in the file is greater than the
@@ -48252,12 +50143,13 @@
48252 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
48253 int rc = SQLITE_OK; /* Return code */
48254
48255 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
48256 assert( !pagerUseWal(pPager) );
48257 assert( pPager->eState==PAGER_WRITER_DBMOD );
48258 assert( pPager->eLock==EXCLUSIVE_LOCK );
 
48259
48260 /* If the file is a temp-file has not yet been opened, open it now. It
48261 ** is not possible for rc to be other than SQLITE_OK if this branch
48262 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
48263 */
@@ -48921,10 +50813,11 @@
48921 */
48922 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
48923 if( rc==SQLITE_OK && !locked ){
48924 Pgno nPage; /* Number of pages in database file */
48925
 
48926 rc = pagerPagecount(pPager, &nPage);
48927 if( rc==SQLITE_OK ){
48928 /* If the database is zero pages in size, that means that either (1) the
48929 ** journal is a remnant from a prior database with the same name where
48930 ** the database file but not the journal was deleted, or (2) the initial
@@ -49013,21 +50906,21 @@
49013 int rc = SQLITE_OK; /* Return code */
49014
49015 /* This routine is only called from b-tree and only when there are no
49016 ** outstanding pages. This implies that the pager state should either
49017 ** be OPEN or READER. READER is only possible if the pager is or was in
49018 ** exclusive access mode.
49019 */
49020 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
49021 assert( assert_pager_state(pPager) );
49022 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49023 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
49024
49025 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
49026 int bHotJournal = 1; /* True if there exists a hot journal-file */
49027
49028 assert( !MEMDB );
 
49029
49030 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
49031 if( rc!=SQLITE_OK ){
49032 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
49033 goto failed;
@@ -49109,11 +51002,11 @@
49109 */
49110 if( isOpen(pPager->jfd) ){
49111 assert( rc==SQLITE_OK );
49112 rc = pagerSyncHotJournal(pPager);
49113 if( rc==SQLITE_OK ){
49114 rc = pager_playback(pPager, 1);
49115 pPager->eState = PAGER_OPEN;
49116 }
49117 }else if( !pPager->exclusiveMode ){
49118 pagerUnlockDb(pPager, SHARED_LOCK);
49119 }
@@ -49205,11 +51098,11 @@
49205 if( pagerUseWal(pPager) ){
49206 assert( rc==SQLITE_OK );
49207 rc = pagerBeginReadTransaction(pPager);
49208 }
49209
49210 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
49211 rc = pagerPagecount(pPager, &pPager->dbSize);
49212 }
49213
49214 failed:
49215 if( rc!=SQLITE_OK ){
@@ -49338,11 +51231,11 @@
49338 rc = sqlite3OsFetch(pPager->fd,
49339 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
49340 );
49341
49342 if( rc==SQLITE_OK && pData ){
49343 if( pPager->eState>PAGER_READER ){
49344 pPg = sqlite3PagerLookup(pPager, pgno);
49345 }
49346 if( pPg==0 ){
49347 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
49348 }else{
@@ -49405,11 +51298,12 @@
49405 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
49406 rc = SQLITE_CORRUPT_BKPT;
49407 goto pager_acquire_err;
49408 }
49409
49410 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
 
49411 if( pgno>pPager->mxPgno ){
49412 rc = SQLITE_FULL;
49413 goto pager_acquire_err;
49414 }
49415 if( noContent ){
@@ -49547,28 +51441,28 @@
49547 /* Open the journal file if it is not already open. */
49548 if( !isOpen(pPager->jfd) ){
49549 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
49550 sqlite3MemJournalOpen(pPager->jfd);
49551 }else{
49552 const int flags = /* VFS flags to open journal file */
49553 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
49554 (pPager->tempFile ?
49555 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
49556 (SQLITE_OPEN_MAIN_JOURNAL)
49557 );
49558
 
 
 
 
 
 
 
 
49559 /* Verify that the database still has the same name as it did when
49560 ** it was originally opened. */
49561 rc = databaseIsUnmoved(pPager);
49562 if( rc==SQLITE_OK ){
49563 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
49564 rc = sqlite3JournalOpen(
49565 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
49566 );
49567 #else
49568 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
49569 #endif
49570 }
49571 }
49572 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
49573 }
49574
@@ -49935,10 +51829,11 @@
49935 return pPager->errCode;
49936 }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
49937 if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
49938 return SQLITE_OK;
49939 }else if( pPager->sectorSize > (u32)pPager->pageSize ){
 
49940 return pagerWriteLargeSector(pPg);
49941 }else{
49942 return pager_write(pPg);
49943 }
49944 }
@@ -49965,18 +51860,25 @@
49965 ** on the given page is unused. The pager marks the page as clean so
49966 ** that it does not get written to disk.
49967 **
49968 ** Tests show that this optimization can quadruple the speed of large
49969 ** DELETE operations.
 
 
 
 
 
 
49970 */
49971 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
49972 Pager *pPager = pPg->pPager;
49973 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
49974 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
49975 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
49976 pPg->flags |= PGHDR_DONT_WRITE;
49977 pPg->flags &= ~PGHDR_WRITEABLE;
 
49978 pager_set_pagehash(pPg);
49979 }
49980 }
49981
49982 /*
@@ -50166,22 +52068,26 @@
50166 );
50167 assert( assert_pager_state(pPager) );
50168
50169 /* If a prior error occurred, report that error again. */
50170 if( NEVER(pPager->errCode) ) return pPager->errCode;
 
 
 
50171
50172 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
50173 pPager->zFilename, zMaster, pPager->dbSize));
50174
50175 /* If no database changes have been made, return early. */
50176 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
50177
50178 if( MEMDB ){
 
 
50179 /* If this is an in-memory db, or no pages have been written to, or this
50180 ** function has already been called, it is mostly a no-op. However, any
50181 ** backup in progress needs to be restarted.
50182 */
50183 sqlite3BackupRestart(pPager->pBackup);
50184 }else{
50185 if( pagerUseWal(pPager) ){
50186 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50187 PgHdr *pPageOne = 0;
@@ -50516,14 +52422,14 @@
50516 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
50517 }
50518 }
50519
50520 /*
50521 ** Return true if this is an in-memory pager.
50522 */
50523 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
50524 return MEMDB;
50525 }
50526
50527 /*
50528 ** Check that there are at least nSavepoint savepoints open. If there are
50529 ** currently less than nSavepoints open, then open one or more savepoints
@@ -50799,11 +52705,12 @@
50799 assert( assert_pager_state(pPager) );
50800
50801 /* In order to be able to rollback, an in-memory database must journal
50802 ** the page we are moving from.
50803 */
50804 if( MEMDB ){
 
50805 rc = sqlite3PagerWrite(pPg);
50806 if( rc ) return rc;
50807 }
50808
50809 /* If the page being moved is dirty and has not been saved by the latest
@@ -50856,11 +52763,11 @@
50856 pPg->flags &= ~PGHDR_NEED_SYNC;
50857 pPgOld = sqlite3PagerLookup(pPager, pgno);
50858 assert( !pPgOld || pPgOld->nRef==1 );
50859 if( pPgOld ){
50860 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
50861 if( MEMDB ){
50862 /* Do not discard pages from an in-memory database since we might
50863 ** need to rollback later. Just move the page out of the way. */
50864 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
50865 }else{
50866 sqlite3PcacheDrop(pPgOld);
@@ -50873,12 +52780,11 @@
50873
50874 /* For an in-memory database, make sure the original page continues
50875 ** to exist, in case the transaction needs to roll back. Use pPgOld
50876 ** as the original page since it has already been allocated.
50877 */
50878 if( MEMDB ){
50879 assert( pPgOld );
50880 sqlite3PcacheMove(pPgOld, origPgno);
50881 sqlite3PagerUnrefNotNull(pPgOld);
50882 }
50883
50884 if( needSyncPgno ){
@@ -51126,11 +53032,12 @@
51126 #ifndef SQLITE_OMIT_VACUUM
51127 /*
51128 ** Unless this is an in-memory or temporary database, clear the pager cache.
51129 */
51130 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
51131 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
 
51132 }
51133 #endif
51134
51135 #ifndef SQLITE_OMIT_WAL
51136 /*
@@ -51305,10 +53212,11 @@
51305 if( rc==SQLITE_OK ){
51306 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
51307 pPager->pageSize, (u8*)pPager->pTmpSpace);
51308 pPager->pWal = 0;
51309 pagerFixMaplimit(pPager);
 
51310 }
51311 }
51312 return rc;
51313 }
51314
@@ -54760,10 +56668,27 @@
54760 /* Try to open on pSnapshot when the next read-transaction starts
54761 */
54762 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
54763 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
54764 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54765 #endif /* SQLITE_ENABLE_SNAPSHOT */
54766
54767 #ifdef SQLITE_ENABLE_ZIPVFS
54768 /*
54769 ** If the argument is not NULL, it points to a Wal object that holds a
@@ -57475,15 +59400,15 @@
57475 flagByte &= ~PTF_LEAF;
57476 pPage->childPtrSize = 4-4*pPage->leaf;
57477 pPage->xCellSize = cellSizePtr;
57478 pBt = pPage->pBt;
57479 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
57480 /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
57481 ** table b-tree page. */
57482 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
57483 /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
57484 ** table b-tree page. */
57485 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
57486 pPage->intKey = 1;
57487 if( pPage->leaf ){
57488 pPage->intKeyLeaf = 1;
57489 pPage->xParseCell = btreeParseCellPtr;
@@ -57493,15 +59418,15 @@
57493 pPage->xParseCell = btreeParseCellPtrNoPayload;
57494 }
57495 pPage->maxLocal = pBt->maxLeaf;
57496 pPage->minLocal = pBt->minLeaf;
57497 }else if( flagByte==PTF_ZERODATA ){
57498 /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
57499 ** index b-tree page. */
57500 assert( (PTF_ZERODATA)==2 );
57501 /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
57502 ** index b-tree page. */
57503 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
57504 pPage->intKey = 0;
57505 pPage->intKeyLeaf = 0;
57506 pPage->xParseCell = btreeParseCellPtrIndex;
57507 pPage->maxLocal = pBt->maxLocal;
@@ -62344,12 +64269,12 @@
62344 for(i=iFirst; i<iEnd; i++){
62345 int sz, rc;
62346 u8 *pSlot;
62347 sz = cachedCellSize(pCArray, i);
62348 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
 
62349 pData -= sz;
62350 if( pData<pBegin ) return 1;
62351 pSlot = pData;
62352 }
62353 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
62354 ** database. But they might for a corrupt database. Hence use memmove()
62355 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
@@ -62507,11 +64432,11 @@
62507
62508 #ifdef SQLITE_DEBUG
62509 for(i=0; i<nNew && !CORRUPT_DB; i++){
62510 u8 *pCell = pCArray->apCell[i+iNew];
62511 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
62512 if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
62513 pCell = &pTmp[pCell - aData];
62514 }
62515 assert( 0==memcmp(pCell, &aData[iOff],
62516 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
62517 }
@@ -63938,10 +65863,32 @@
63938
63939 iCellDepth = pCur->iPage;
63940 iCellIdx = pCur->aiIdx[iCellDepth];
63941 pPage = pCur->apPage[iCellDepth];
63942 pCell = findCell(pPage, iCellIdx);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63943
63944 /* If the page containing the entry to delete is not a leaf page, move
63945 ** the cursor to the largest entry in the tree that is smaller than
63946 ** the entry being deleted. This cell will replace the cell being deleted
63947 ** from the internal node. The 'previous' entry is used for this instead
@@ -63965,32 +65912,10 @@
63965 ** invalidate any incrblob cursors open on the row being deleted. */
63966 if( pCur->pKeyInfo==0 ){
63967 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
63968 }
63969
63970 /* If the bPreserve flag is set to true, then the cursor position must
63971 ** be preserved following this delete operation. If the current delete
63972 ** will cause a b-tree rebalance, then this is done by saving the cursor
63973 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
63974 ** returning.
63975 **
63976 ** Or, if the current delete will not cause a rebalance, then the cursor
63977 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
63978 ** before or after the deleted entry. In this case set bSkipnext to true. */
63979 if( bPreserve ){
63980 if( !pPage->leaf
63981 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
63982 ){
63983 /* A b-tree rebalance will be required after deleting this entry.
63984 ** Save the cursor key. */
63985 rc = saveCursorKey(pCur);
63986 if( rc ) return rc;
63987 }else{
63988 bSkipnext = 1;
63989 }
63990 }
63991
63992 /* Make the page containing the entry to be deleted writable. Then free any
63993 ** overflow pages associated with the entry and finally remove the cell
63994 ** itself from within the page. */
63995 rc = sqlite3PagerWrite(pPage->pDbPage);
63996 if( rc ) return rc;
@@ -67111,14 +69036,10 @@
67111 ** freed before the copy is made.
67112 */
67113 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
67114 int rc = SQLITE_OK;
67115
67116 /* The pFrom==0 case in the following assert() is when an sqlite3_value
67117 ** from sqlite3_value_dup() is used as the argument
67118 ** to sqlite3_result_value(). */
67119 assert( pTo->db==pFrom->db || pFrom->db==0 );
67120 assert( (pFrom->flags & MEM_RowSet)==0 );
67121 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
67122 memcpy(pTo, pFrom, MEMCELLSIZE);
67123 pTo->flags &= ~MEM_Dyn;
67124 if( pTo->flags&(MEM_Str|MEM_Blob) ){
@@ -68102,10 +70023,11 @@
68102 ** Swap all content between two VDBE structures.
68103 */
68104 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
68105 Vdbe tmp, *pTmp;
68106 char *zTmp;
 
68107 tmp = *pA;
68108 *pA = *pB;
68109 *pB = tmp;
68110 pTmp = pA->pNext;
68111 pA->pNext = pB->pNext;
@@ -68568,77 +70490,88 @@
68568 ** indicate what the prepared statement actually does.
68569 **
68570 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
68571 **
68572 ** (5) Reclaim the memory allocated for storing labels.
 
 
 
 
68573 */
68574 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
68575 int i;
68576 int nMaxArgs = *pMaxFuncArgs;
68577 Op *pOp;
68578 Parse *pParse = p->pParse;
68579 int *aLabel = pParse->aLabel;
68580 p->readOnly = 1;
68581 p->bIsReader = 0;
68582 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
68583 u8 opcode = pOp->opcode;
68584
68585 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
68586 ** cases from this switch! */
68587 switch( opcode ){
68588 case OP_Transaction: {
68589 if( pOp->p2!=0 ) p->readOnly = 0;
68590 /* fall thru */
68591 }
68592 case OP_AutoCommit:
68593 case OP_Savepoint: {
68594 p->bIsReader = 1;
68595 break;
68596 }
 
 
 
 
 
 
 
68597 #ifndef SQLITE_OMIT_WAL
68598 case OP_Checkpoint:
68599 #endif
68600 case OP_Vacuum:
68601 case OP_JournalMode: {
68602 p->readOnly = 0;
68603 p->bIsReader = 1;
68604 break;
68605 }
68606 #ifndef SQLITE_OMIT_VIRTUALTABLE
68607 case OP_VUpdate: {
68608 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
68609 break;
68610 }
68611 case OP_VFilter: {
68612 int n;
68613 assert( p->nOp - i >= 3 );
68614 assert( pOp[-1].opcode==OP_Integer );
68615 n = pOp[-1].p1;
68616 if( n>nMaxArgs ) nMaxArgs = n;
68617 break;
68618 }
68619 #endif
68620 case OP_Next:
68621 case OP_NextIfOpen:
68622 case OP_SorterNext: {
68623 pOp->p4.xAdvance = sqlite3BtreeNext;
68624 pOp->p4type = P4_ADVANCE;
68625 break;
68626 }
68627 case OP_Prev:
68628 case OP_PrevIfOpen: {
68629 pOp->p4.xAdvance = sqlite3BtreePrevious;
68630 pOp->p4type = P4_ADVANCE;
68631 break;
68632 }
68633 }
68634
68635 pOp->opflags = sqlite3OpcodeProperty[opcode];
68636 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
68637 assert( ADDR(pOp->p2)<pParse->nLabel );
68638 pOp->p2 = aLabel[ADDR(pOp->p2)];
68639 }
 
68640 }
68641 sqlite3DbFree(p->db, pParse->aLabel);
68642 pParse->aLabel = 0;
68643 pParse->nLabel = 0;
68644 *pMaxFuncArgs = nMaxArgs;
@@ -68814,56 +70747,54 @@
68814
68815 /*
68816 ** Delete a P4 value if necessary.
68817 */
68818 static void freeP4(sqlite3 *db, int p4type, void *p4){
68819 if( p4 ){
68820 assert( db );
68821 switch( p4type ){
68822 case P4_FUNCCTX: {
68823 freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
68824 /* Fall through into the next case */
68825 }
68826 case P4_REAL:
68827 case P4_INT64:
68828 case P4_DYNAMIC:
68829 case P4_INTARRAY: {
68830 sqlite3DbFree(db, p4);
68831 break;
68832 }
68833 case P4_KEYINFO: {
68834 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
68835 break;
68836 }
68837 #ifdef SQLITE_ENABLE_CURSOR_HINTS
68838 case P4_EXPR: {
68839 sqlite3ExprDelete(db, (Expr*)p4);
68840 break;
68841 }
68842 #endif
68843 case P4_MPRINTF: {
68844 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
68845 break;
68846 }
68847 case P4_FUNCDEF: {
68848 freeEphemeralFunction(db, (FuncDef*)p4);
68849 break;
68850 }
68851 case P4_MEM: {
68852 if( db->pnBytesFreed==0 ){
68853 sqlite3ValueFree((sqlite3_value*)p4);
68854 }else{
68855 Mem *p = (Mem*)p4;
68856 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
68857 sqlite3DbFree(db, p);
68858 }
68859 break;
68860 }
68861 case P4_VTAB : {
68862 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
68863 break;
68864 }
68865 }
68866 }
68867 }
68868
68869 /*
@@ -69340,10 +71271,14 @@
69340 break;
69341 }
69342 case P4_ADVANCE: {
69343 zTemp[0] = 0;
69344 break;
 
 
 
 
69345 }
69346 default: {
69347 zP4 = pOp->p4.z;
69348 if( zP4==0 ){
69349 zP4 = zTemp;
@@ -71531,10 +73466,11 @@
71531 idx += getVarint32(&aKey[idx], serial_type);
71532 pMem->enc = pKeyInfo->enc;
71533 pMem->db = pKeyInfo->db;
71534 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
71535 pMem->szMalloc = 0;
 
71536 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
71537 pMem++;
71538 if( (++u)>=p->nField ) break;
71539 }
71540 assert( u<=pKeyInfo->nField + 1 );
@@ -72511,10 +74447,94 @@
72511 pVtab->zErrMsg = 0;
72512 }
72513 }
72514 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72515
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72516 /************** End of vdbeaux.c *********************************************/
72517 /************** Begin file vdbeapi.c *****************************************/
72518 /*
72519 ** 2004 May 26
72520 **
@@ -74119,10 +76139,191 @@
74119 v = pVdbe->aCounter[op];
74120 if( resetFlag ) pVdbe->aCounter[op] = 0;
74121 return (int)v;
74122 }
74123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74124 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
74125 /*
74126 ** Return status data for a single loop within query pStmt.
74127 */
74128 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
@@ -74469,10 +76670,20 @@
74469 sqlite3_max_blobsize = p->n;
74470 }
74471 }
74472 #endif
74473
 
 
 
 
 
 
 
 
 
 
74474 /*
74475 ** The next global variable is incremented each time the OP_Found opcode
74476 ** is executed. This is used to test whether or not the foreign key
74477 ** operation implemented using OP_FkIsZero is working. This variable
74478 ** has no function other than to help verify the correct operation of the
@@ -74588,11 +76799,11 @@
74588 nByte =
74589 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
74590 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
74591
74592 assert( iCur>=0 && iCur<p->nCursor );
74593 if( p->apCsr[iCur] ){
74594 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
74595 p->apCsr[iCur] = 0;
74596 }
74597 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
74598 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
@@ -74665,24 +76876,27 @@
74665 u8 enc /* Use this text encoding */
74666 ){
74667 if( affinity>=SQLITE_AFF_NUMERIC ){
74668 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
74669 || affinity==SQLITE_AFF_NUMERIC );
74670 if( (pRec->flags & MEM_Int)==0 ){
74671 if( (pRec->flags & MEM_Real)==0 ){
74672 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
74673 }else{
74674 sqlite3VdbeIntegerAffinity(pRec);
74675 }
74676 }
74677 }else if( affinity==SQLITE_AFF_TEXT ){
74678 /* Only attempt the conversion to TEXT if there is an integer or real
74679 ** representation (blob and NULL do not get converted) but no string
74680 ** representation.
74681 */
74682 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
74683 sqlite3VdbeMemStringify(pRec, enc, 1);
 
 
 
74684 }
74685 pRec->flags &= ~(MEM_Real|MEM_Int);
74686 }
74687 }
74688
@@ -75004,11 +77218,11 @@
75004 Mem *pOut;
75005 assert( pOp->p2>0 );
75006 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
75007 pOut = &p->aMem[pOp->p2];
75008 memAboutToChange(p, pOut);
75009 if( VdbeMemDynamic(pOut) ){
75010 return out2PrereleaseWithClear(pOut);
75011 }else{
75012 pOut->flags = MEM_Int;
75013 return pOut;
75014 }
@@ -75136,41 +77350,43 @@
75136 }
75137 #endif
75138
75139 /* Sanity checking on other operands */
75140 #ifdef SQLITE_DEBUG
75141 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
75142 if( (pOp->opflags & OPFLG_IN1)!=0 ){
75143 assert( pOp->p1>0 );
75144 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
75145 assert( memIsValid(&aMem[pOp->p1]) );
75146 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
75147 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
75148 }
75149 if( (pOp->opflags & OPFLG_IN2)!=0 ){
75150 assert( pOp->p2>0 );
75151 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
75152 assert( memIsValid(&aMem[pOp->p2]) );
75153 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
75154 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
75155 }
75156 if( (pOp->opflags & OPFLG_IN3)!=0 ){
75157 assert( pOp->p3>0 );
75158 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
75159 assert( memIsValid(&aMem[pOp->p3]) );
75160 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
75161 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
75162 }
75163 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
75164 assert( pOp->p2>0 );
75165 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
75166 memAboutToChange(p, &aMem[pOp->p2]);
75167 }
75168 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
75169 assert( pOp->p3>0 );
75170 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
75171 memAboutToChange(p, &aMem[pOp->p3]);
 
 
75172 }
75173 #endif
75174 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
75175 pOrigOp = pOp;
75176 #endif
@@ -75406,12 +77622,10 @@
75406 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
75407 ** every program. So a jump past the last instruction of the program
75408 ** is the same as executing Halt.
75409 */
75410 case OP_Halt: {
75411 const char *zType;
75412 const char *zLogFmt;
75413 VdbeFrame *pFrame;
75414 int pcx;
75415
75416 pcx = (int)(pOp - aOp);
75417 if( pOp->p1==SQLITE_OK && p->pFrame ){
@@ -75436,38 +77650,32 @@
75436 break;
75437 }
75438 p->rc = pOp->p1;
75439 p->errorAction = (u8)pOp->p2;
75440 p->pc = pcx;
 
75441 if( p->rc ){
75442 if( pOp->p5 ){
75443 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
75444 "FOREIGN KEY" };
75445 assert( pOp->p5>=1 && pOp->p5<=4 );
75446 testcase( pOp->p5==1 );
75447 testcase( pOp->p5==2 );
75448 testcase( pOp->p5==3 );
75449 testcase( pOp->p5==4 );
75450 zType = azType[pOp->p5-1];
 
 
 
75451 }else{
75452 zType = 0;
75453 }
75454 assert( zType!=0 || pOp->p4.z!=0 );
75455 zLogFmt = "abort at %d in [%s]: %s";
75456 if( zType && pOp->p4.z ){
75457 sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
75458 }else if( pOp->p4.z ){
75459 sqlite3VdbeError(p, "%s", pOp->p4.z);
75460 }else{
75461 sqlite3VdbeError(p, "%s constraint failed", zType);
75462 }
75463 sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
75464 }
75465 rc = sqlite3VdbeHalt(p);
75466 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
75467 if( rc==SQLITE_BUSY ){
75468 p->rc = rc = SQLITE_BUSY;
75469 }else{
75470 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
75471 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
75472 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
75473 }
@@ -75529,14 +77737,11 @@
75529 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
75530
75531 #ifndef SQLITE_OMIT_UTF16
75532 if( encoding!=SQLITE_UTF8 ){
75533 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
75534 if( rc ){
75535 assert( rc==SQLITE_TOOBIG ); /* This is the only possible error here */
75536 goto too_big;
75537 }
75538 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
75539 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
75540 assert( VdbeMemDynamic(pOut)==0 );
75541 pOut->szMalloc = 0;
75542 pOut->flags |= MEM_Static;
@@ -75545,26 +77750,30 @@
75545 }
75546 pOp->p4type = P4_DYNAMIC;
75547 pOp->p4.z = pOut->z;
75548 pOp->p1 = pOut->n;
75549 }
 
75550 #endif
75551 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
75552 goto too_big;
75553 }
 
75554 /* Fall through to the next case, OP_String */
75555 }
75556
75557 /* Opcode: String P1 P2 P3 P4 P5
75558 ** Synopsis: r[P2]='P4' (len=P1)
75559 **
75560 ** The string value P4 of length P1 (bytes) is stored in register P2.
75561 **
75562 ** If P5!=0 and the content of register P3 is greater than zero, then
75563 ** the datatype of the register P2 is converted to BLOB. The content is
75564 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
75565 ** of a string, as if it had been CAST.
 
 
75566 */
75567 case OP_String: { /* out2 */
75568 assert( pOp->p4.z!=0 );
75569 pOut = out2Prerelease(p, pOp);
75570 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
@@ -75571,16 +77780,15 @@
75571 pOut->z = pOp->p4.z;
75572 pOut->n = pOp->p1;
75573 pOut->enc = encoding;
75574 UPDATE_MAX_BLOBSIZE(pOut);
75575 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
75576 if( pOp->p5 ){
75577 assert( pOp->p3>0 );
75578 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
75579 pIn3 = &aMem[pOp->p3];
75580 assert( pIn3->flags & MEM_Int );
75581 if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
75582 }
75583 #endif
75584 break;
75585 }
75586
@@ -76478,15 +78686,17 @@
76478 }
76479 }else{
76480 /* Neither operand is NULL. Do a comparison. */
76481 affinity = pOp->p5 & SQLITE_AFF_MASK;
76482 if( affinity>=SQLITE_AFF_NUMERIC ){
76483 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76484 applyNumericAffinity(pIn1,0);
76485 }
76486 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
76487 applyNumericAffinity(pIn3,0);
 
 
76488 }
76489 }else if( affinity==SQLITE_AFF_TEXT ){
76490 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
76491 testcase( pIn1->flags & MEM_Int );
76492 testcase( pIn1->flags & MEM_Real );
@@ -77215,11 +79425,13 @@
77215 }
77216 nData += len;
77217 testcase( serial_type==127 );
77218 testcase( serial_type==128 );
77219 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
77220 }while( (--pRec)>=pData0 );
 
 
77221
77222 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
77223 ** which determines the total number of bytes in the header. The varint
77224 ** value is the size of the header in bytes including the size varint
77225 ** itself. */
@@ -77363,11 +79575,11 @@
77363 db->autoCommit = 0;
77364 db->isTransactionSavepoint = 1;
77365 }else{
77366 db->nSavepoint++;
77367 }
77368
77369 /* Link the new savepoint into the database handle's list. */
77370 pNew->pNext = db->pSavepoint;
77371 db->pSavepoint = pNew;
77372 pNew->nDeferredCons = db->nDeferredCons;
77373 pNew->nDeferredImmCons = db->nDeferredImmCons;
@@ -78720,13 +80932,13 @@
78720 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
78721 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
78722 ** is part of an INSERT operation. The difference is only important to
78723 ** the update hook.
78724 **
78725 ** Parameter P4 may point to a string containing the table-name, or
78726 ** may be NULL. If it is not NULL, then the update-hook
78727 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
78728 **
78729 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
78730 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
78731 ** and register P2 becomes ephemeral. If the cursor is changed, the
78732 ** value of register P2 will then change. Make sure this does not
@@ -78748,21 +80960,23 @@
78748 i64 iKey; /* The integer ROWID or key for the record to be inserted */
78749 VdbeCursor *pC; /* Cursor to table into which insert is written */
78750 int nZero; /* Number of zero-bytes to append */
78751 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
78752 const char *zDb; /* database name - used by the update hook */
78753 const char *zTbl; /* Table name - used by the opdate hook */
78754 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
78755
 
78756 pData = &aMem[pOp->p2];
78757 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
78758 assert( memIsValid(pData) );
78759 pC = p->apCsr[pOp->p1];
78760 assert( pC!=0 );
78761 assert( pC->eCurType==CURTYPE_BTREE );
78762 assert( pC->uc.pCursor!=0 );
78763 assert( pC->isTable );
 
78764 REGISTER_TRACE(pOp->p2, pData);
78765
78766 if( pOp->opcode==OP_Insert ){
78767 pKey = &aMem[pOp->p3];
78768 assert( pKey->flags & MEM_Int );
@@ -78771,10 +80985,32 @@
78771 iKey = pKey->u.i;
78772 }else{
78773 assert( pOp->opcode==OP_InsertInt );
78774 iKey = pOp->p3;
78775 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78776
78777 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
78778 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
78779 if( pData->flags & MEM_Null ){
78780 pData->z = 0;
@@ -78795,22 +81031,17 @@
78795 pC->deferredMoveto = 0;
78796 pC->cacheStatus = CACHE_STALE;
78797
78798 /* Invoke the update-hook if required. */
78799 if( rc ) goto abort_due_to_error;
78800 if( db->xUpdateCallback && pOp->p4.z ){
78801 zDb = db->aDb[pC->iDb].zName;
78802 zTbl = pOp->p4.z;
78803 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
78804 assert( pC->isTable );
78805 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
78806 assert( pC->iDb>=0 );
78807 }
78808 break;
78809 }
78810
78811 /* Opcode: Delete P1 P2 * P4 P5
78812 **
78813 ** Delete the record at which the P1 cursor is currently pointing.
78814 **
78815 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
78816 ** the cursor will be left pointing at either the next or the previous
@@ -78830,42 +81061,77 @@
78830 ** change count is incremented (otherwise not).
78831 **
78832 ** P1 must not be pseudo-table. It has to be a real table with
78833 ** multiple rows.
78834 **
78835 ** If P4 is not NULL, then it is the name of the table that P1 is
78836 ** pointing to. The update hook will be invoked, if it exists.
78837 ** If P4 is not NULL then the P1 cursor must have been positioned
78838 ** using OP_NotFound prior to invoking this opcode.
 
 
 
 
 
 
78839 */
78840 case OP_Delete: {
78841 VdbeCursor *pC;
78842 u8 hasUpdateCallback;
 
 
78843
 
78844 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
78845 pC = p->apCsr[pOp->p1];
78846 assert( pC!=0 );
78847 assert( pC->eCurType==CURTYPE_BTREE );
78848 assert( pC->uc.pCursor!=0 );
78849 assert( pC->deferredMoveto==0 );
78850
78851 hasUpdateCallback = db->xUpdateCallback && pOp->p4.z && pC->isTable;
78852 if( pOp->p5 && hasUpdateCallback ){
78853 sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
78854 }
78855
78856 #ifdef SQLITE_DEBUG
78857 /* The seek operation that positioned the cursor prior to OP_Delete will
78858 ** have also set the pC->movetoTarget field to the rowid of the row that
78859 ** is being deleted */
78860 if( pOp->p4.z && pC->isTable && pOp->p5==0 ){
78861 i64 iKey = 0;
78862 sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
78863 assert( pC->movetoTarget==iKey );
78864 }
78865 #endif
78866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78867 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
78868 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
78869 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
78870 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
78871
@@ -78883,19 +81149,22 @@
78883 }
78884 #endif
78885
78886 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
78887 pC->cacheStatus = CACHE_STALE;
 
78888
78889 /* Invoke the update-hook if required. */
78890 if( rc ) goto abort_due_to_error;
78891 if( hasUpdateCallback ){
78892 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
78893 db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
78894 assert( pC->iDb>=0 );
 
 
78895 }
78896 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
78897 break;
78898 }
78899 /* Opcode: ResetCount * * * * *
78900 **
78901 ** The value of the change counter is copied to the database handle
@@ -80371,25 +82640,10 @@
80371 if( pIn1->u.i==0 ) goto jump_to_p2;
80372 break;
80373 }
80374
80375
80376 /* Opcode: JumpZeroIncr P1 P2 * * *
80377 ** Synopsis: if (r[P1]++)==0 ) goto P2
80378 **
80379 ** The register P1 must contain an integer. If register P1 is initially
80380 ** zero, then jump to P2. Increment register P1 regardless of whether or
80381 ** not the jump is taken.
80382 */
80383 case OP_JumpZeroIncr: { /* jump, in1 */
80384 pIn1 = &aMem[pOp->p1];
80385 assert( pIn1->flags&MEM_Int );
80386 VdbeBranchTaken(pIn1->u.i==0, 2);
80387 if( (pIn1->u.i++)==0 ) goto jump_to_p2;
80388 break;
80389 }
80390
80391 /* Opcode: AggStep0 * P2 P3 P4 P5
80392 ** Synopsis: accum=r[P3] step(r[P2@P5])
80393 **
80394 ** Execute the step function for an aggregate. The
80395 ** function has P5 arguments. P4 is a pointer to the FuncDef
@@ -81278,15 +83532,16 @@
81278 #ifndef NDEBUG
81279 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
81280
81281 #ifdef SQLITE_DEBUG
81282 if( db->flags & SQLITE_VdbeTrace ){
 
81283 if( rc!=0 ) printf("rc=%d\n",rc);
81284 if( pOrigOp->opflags & (OPFLG_OUT2) ){
81285 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
81286 }
81287 if( pOrigOp->opflags & OPFLG_OUT3 ){
81288 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
81289 }
81290 }
81291 #endif /* SQLITE_DEBUG */
81292 #endif /* NDEBUG */
@@ -81386,10 +83641,12 @@
81386 int iOffset; /* Byte offset of blob in cursor data */
81387 int iCol; /* Table column this handle is open on */
81388 BtCursor *pCsr; /* Cursor pointing at blob row */
81389 sqlite3_stmt *pStmt; /* Statement holding cursor open */
81390 sqlite3 *db; /* The associated database */
 
 
81391 };
81392
81393
81394 /*
81395 ** This function is used by both blob_open() and blob_reopen(). It seeks
@@ -81529,10 +83786,12 @@
81529 }
81530 rc = SQLITE_ERROR;
81531 sqlite3BtreeLeaveAll(db);
81532 goto blob_open_out;
81533 }
 
 
81534
81535 /* Now search pTab for the exact column. */
81536 for(iCol=0; iCol<pTab->nCol; iCol++) {
81537 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
81538 break;
@@ -81750,10 +84009,34 @@
81750 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
81751 ** returned, clean-up the statement handle.
81752 */
81753 assert( db == v->db );
81754 sqlite3BtreeEnterCursor(p->pCsr);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81755 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
81756 sqlite3BtreeLeaveCursor(p->pCsr);
81757 if( rc==SQLITE_ABORT ){
81758 sqlite3VdbeFinalize(v);
81759 p->pStmt = 0;
@@ -82767,11 +85050,10 @@
82767 int nField, /* Number of key fields in each record */
82768 VdbeCursor *pCsr /* Cursor that holds the new sorter */
82769 ){
82770 int pgsz; /* Page size of main database */
82771 int i; /* Used to iterate through aTask[] */
82772 int mxCache; /* Cache size */
82773 VdbeSorter *pSorter; /* The new sorter */
82774 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
82775 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
82776 int sz; /* Size of pSorter in bytes */
82777 int rc = SQLITE_OK;
@@ -82824,15 +85106,24 @@
82824 SortSubtask *pTask = &pSorter->aTask[i];
82825 pTask->pSorter = pSorter;
82826 }
82827
82828 if( !sqlite3TempInMemory(db) ){
 
82829 u32 szPma = sqlite3GlobalConfig.szPma;
82830 pSorter->mnPmaSize = szPma * pgsz;
 
82831 mxCache = db->aDb[0].pSchema->cache_size;
82832 if( mxCache<(int)szPma ) mxCache = (int)szPma;
82833 pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
 
 
 
 
 
 
 
82834
82835 /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
82836 ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
82837 ** large heap allocations.
82838 */
@@ -84592,10 +86883,19 @@
84592 *************************************************************************
84593 **
84594 ** This file contains code use to implement an in-memory rollback journal.
84595 ** The in-memory rollback journal is used to journal transactions for
84596 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
 
 
 
 
 
 
 
 
 
84597 */
84598 /* #include "sqliteInt.h" */
84599
84600 /* Forward references to internal structures */
84601 typedef struct MemJournal MemJournal;
@@ -85918,10 +88218,11 @@
85918 notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
85919 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
85920 assert( pNC->nRef>=nRef );
85921 if( nRef!=pNC->nRef ){
85922 ExprSetProperty(pExpr, EP_VarSelect);
 
85923 }
85924 }
85925 break;
85926 }
85927 case TK_VARIABLE: {
@@ -87125,19 +89426,17 @@
87125 if( pToken ){
87126 if( nExtra==0 ){
87127 pNew->flags |= EP_IntValue;
87128 pNew->u.iValue = iValue;
87129 }else{
87130 int c;
87131 pNew->u.zToken = (char*)&pNew[1];
87132 assert( pToken->z!=0 || pToken->n==0 );
87133 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
87134 pNew->u.zToken[pToken->n] = 0;
87135 if( dequote && nExtra>=3
87136 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
87137 sqlite3Dequote(pNew->u.zToken);
87138 if( c=='"' ) pNew->flags |= EP_DblQuoted;
87139 }
87140 }
87141 }
87142 #if SQLITE_MAX_EXPR_DEPTH>0
87143 pNew->nHeight = 1;
@@ -87215,10 +89514,26 @@
87215 if( p ) {
87216 sqlite3ExprCheckHeight(pParse, p->nHeight);
87217 }
87218 return p;
87219 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87220
87221 /*
87222 ** If the expression is always either TRUE or FALSE (respectively),
87223 ** then return 1. If one cannot determine the truth value of the
87224 ** expression at compile-time return 0.
@@ -87376,12 +89691,12 @@
87376 }
87377
87378 /*
87379 ** Recursively delete an expression tree.
87380 */
87381 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
87382 if( p==0 ) return;
87383 /* Sanity check: Assert that the IntValue is non-negative if it exists */
87384 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
87385 if( !ExprHasProperty(p, EP_TokenOnly) ){
87386 /* The Expr.x union is never used at the same time as Expr.pRight */
87387 assert( p->x.pList==0 || p->pRight==0 );
@@ -87395,10 +89710,13 @@
87395 }
87396 }
87397 if( !ExprHasProperty(p, EP_Static) ){
87398 sqlite3DbFree(db, p);
87399 }
 
 
 
87400 }
87401
87402 /*
87403 ** Return the number of bytes allocated for the expression structure
87404 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
@@ -87447,11 +89765,11 @@
87447 static int dupedExprStructSize(Expr *p, int flags){
87448 int nSize;
87449 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
87450 assert( EXPR_FULLSIZE<=0xfff );
87451 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
87452 if( 0==(flags&EXPRDUP_REDUCE) ){
87453 nSize = EXPR_FULLSIZE;
87454 }else{
87455 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
87456 assert( !ExprHasProperty(p, EP_FromJoin) );
87457 assert( !ExprHasProperty(p, EP_MemToken) );
@@ -87509,92 +89827,92 @@
87509 ** to store the copy of expression p, the copies of p->u.zToken
87510 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
87511 ** if any. Before returning, *pzBuffer is set to the first byte past the
87512 ** portion of the buffer copied into by this function.
87513 */
87514 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
87515 Expr *pNew = 0; /* Value to return */
87516 assert( flags==0 || flags==EXPRDUP_REDUCE );
 
 
87517 assert( db!=0 );
87518 if( p ){
87519 const int isReduced = (flags&EXPRDUP_REDUCE);
87520 u8 *zAlloc;
87521 u32 staticFlag = 0;
87522
87523 assert( pzBuffer==0 || isReduced );
87524
87525 /* Figure out where to write the new Expr structure. */
87526 if( pzBuffer ){
87527 zAlloc = *pzBuffer;
87528 staticFlag = EP_Static;
87529 }else{
87530 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, flags));
87531 }
87532 pNew = (Expr *)zAlloc;
87533
87534 if( pNew ){
87535 /* Set nNewSize to the size allocated for the structure pointed to
87536 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
87537 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
87538 ** by the copy of the p->u.zToken string (if any).
87539 */
87540 const unsigned nStructSize = dupedExprStructSize(p, flags);
87541 const int nNewSize = nStructSize & 0xfff;
87542 int nToken;
87543 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
87544 nToken = sqlite3Strlen30(p->u.zToken) + 1;
87545 }else{
87546 nToken = 0;
87547 }
87548 if( isReduced ){
87549 assert( ExprHasProperty(p, EP_Reduced)==0 );
87550 memcpy(zAlloc, p, nNewSize);
87551 }else{
87552 u32 nSize = (u32)exprStructSize(p);
87553 memcpy(zAlloc, p, nSize);
87554 if( nSize<EXPR_FULLSIZE ){
87555 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
87556 }
87557 }
87558
87559 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
87560 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
87561 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
87562 pNew->flags |= staticFlag;
87563
87564 /* Copy the p->u.zToken string, if any. */
87565 if( nToken ){
87566 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
87567 memcpy(zToken, p->u.zToken, nToken);
87568 }
87569
87570 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
87571 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
87572 if( ExprHasProperty(p, EP_xIsSelect) ){
87573 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
87574 }else{
87575 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
87576 }
87577 }
87578
87579 /* Fill in pNew->pLeft and pNew->pRight. */
87580 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
87581 zAlloc += dupedExprNodeSize(p, flags);
87582 if( ExprHasProperty(pNew, EP_Reduced) ){
87583 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
87584 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
87585 }
87586 if( pzBuffer ){
87587 *pzBuffer = zAlloc;
87588 }
87589 }else{
87590 if( !ExprHasProperty(p, EP_TokenOnly) ){
87591 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
87592 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
87593 }
87594 }
87595
87596 }
87597 }
87598 return pNew;
87599 }
87600
@@ -87642,11 +89960,11 @@
87642 ** truncated version of the usual Expr structure that will be stored as
87643 ** part of the in-memory representation of the database schema.
87644 */
87645 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
87646 assert( flags==0 || flags==EXPRDUP_REDUCE );
87647 return exprDup(db, p, flags, 0);
87648 }
87649 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
87650 ExprList *pNew;
87651 struct ExprList_item *pItem, *pOldItem;
87652 int i;
@@ -87864,11 +90182,11 @@
87864 struct ExprList_item *pItem;
87865 assert( pList->nExpr>0 );
87866 pItem = &pList->a[pList->nExpr-1];
87867 assert( pItem->zName==0 );
87868 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
87869 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
87870 }
87871 }
87872
87873 /*
87874 ** Set the ExprList.a[].zSpan element of the most recently added item
@@ -87913,22 +90231,24 @@
87913 }
87914
87915 /*
87916 ** Delete an entire expression list.
87917 */
87918 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
87919 int i;
87920 struct ExprList_item *pItem;
87921 if( pList==0 ) return;
87922 assert( pList->a!=0 || pList->nExpr==0 );
87923 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
87924 sqlite3ExprDelete(db, pItem->pExpr);
87925 sqlite3DbFree(db, pItem->zName);
87926 sqlite3DbFree(db, pItem->zSpan);
87927 }
87928 sqlite3DbFree(db, pList->a);
87929 sqlite3DbFree(db, pList);
 
 
 
87930 }
87931
87932 /*
87933 ** Return the bitwise-OR of all Expr.flags fields in the given
87934 ** ExprList.
@@ -88970,10 +91290,23 @@
88970 #endif
88971 }
88972 }
88973 }
88974
 
 
 
 
 
 
 
 
 
 
 
 
 
88975 /*
88976 ** Clear a cache entry.
88977 */
88978 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
88979 if( p->tempReg ){
@@ -88980,10 +91313,13 @@
88980 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
88981 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
88982 }
88983 p->tempReg = 0;
88984 }
 
 
 
88985 }
88986
88987
88988 /*
88989 ** Record in the column cache that a particular column from a
@@ -89023,10 +91359,12 @@
89023 p->iTable = iTab;
89024 p->iColumn = iCol;
89025 p->iReg = iReg;
89026 p->tempReg = 0;
89027 p->lru = pParse->iCacheCnt++;
 
 
89028 return;
89029 }
89030 }
89031
89032 /* Replace the last recently used */
@@ -89044,28 +91382,27 @@
89044 p->iTable = iTab;
89045 p->iColumn = iCol;
89046 p->iReg = iReg;
89047 p->tempReg = 0;
89048 p->lru = pParse->iCacheCnt++;
 
89049 return;
89050 }
89051 }
89052
89053 /*
89054 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
89055 ** Purge the range of registers from the column cache.
89056 */
89057 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
89058 int i;
89059 int iLast = iReg + nReg - 1;
89060 struct yColCache *p;
89061 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89062 int r = p->iReg;
89063 if( r>=iReg && r<=iLast ){
89064 cacheEntryClear(pParse, p);
89065 p->iReg = 0;
89066 }
89067 }
89068 }
89069
89070 /*
89071 ** Remember the current column cache context. Any new entries added
@@ -89097,11 +91434,10 @@
89097 }
89098 #endif
89099 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89100 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
89101 cacheEntryClear(pParse, p);
89102 p->iReg = 0;
89103 }
89104 }
89105 }
89106
89107 /*
@@ -89232,11 +91568,10 @@
89232 }
89233 #endif
89234 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
89235 if( p->iReg ){
89236 cacheEntryClear(pParse, p);
89237 p->iReg = 0;
89238 }
89239 }
89240 }
89241
89242 /*
@@ -89273,10 +91608,11 @@
89273 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
89274 }
89275 return 0;
89276 }
89277 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
 
89278
89279 /*
89280 ** Convert an expression node to a TK_REGISTER
89281 */
89282 static void exprToRegister(Expr *p, int iReg){
@@ -93567,43 +95903,46 @@
93567 */
93568 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
93569 analysisInfo sInfo;
93570 HashElem *i;
93571 char *zSql;
93572 int rc;
93573
93574 assert( iDb>=0 && iDb<db->nDb );
93575 assert( db->aDb[iDb].pBt!=0 );
93576
93577 /* Clear any prior statistics */
93578 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93579 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
93580 Index *pIdx = sqliteHashData(i);
93581 sqlite3DefaultRowEst(pIdx);
93582 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
93583 sqlite3DeleteIndexSamples(db, pIdx);
93584 pIdx->aSample = 0;
93585 #endif
93586 }
93587
93588 /* Check to make sure the sqlite_stat1 table exists */
93589 sInfo.db = db;
93590 sInfo.zDatabase = db->aDb[iDb].zName;
93591 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
93592 return SQLITE_ERROR;
 
 
 
 
 
 
 
93593 }
93594
93595 /* Load new statistics out of the sqlite_stat1 table */
93596 zSql = sqlite3MPrintf(db,
93597 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
93598 if( zSql==0 ){
93599 rc = SQLITE_NOMEM_BKPT;
93600 }else{
93601 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
93602 sqlite3DbFree(db, zSql);
93603 }
93604
93605
93606 /* Load the statistics from the sqlite_stat4 table. */
93607 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
93608 if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
93609 db->lookaside.bDisable++;
@@ -95067,20 +97406,14 @@
95067 ** contains lookaside memory. (Table objects in the schema do not use
95068 ** lookaside memory, but some ephemeral Table objects do.) Or the
95069 ** db parameter can be used with db->pnBytesFreed to measure the memory
95070 ** used by the Table object.
95071 */
95072 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
95073 Index *pIndex, *pNext;
95074 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
95075
95076 assert( !pTable || pTable->nRef>0 );
95077
95078 /* Do not delete the table until the reference count reaches zero. */
95079 if( !pTable ) return;
95080 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
95081
95082 /* Record the number of outstanding lookaside allocations in schema Tables
95083 ** prior to doing any free() operations. Since schema Tables do not use
95084 ** lookaside, this number should not change. */
95085 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
95086 db->lookaside.nOut : 0 );
@@ -95116,10 +97449,17 @@
95116 sqlite3DbFree(db, pTable);
95117
95118 /* Verify that no lookaside memory was used by schema tables */
95119 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
95120 }
 
 
 
 
 
 
 
95121
95122 /*
95123 ** Unlink the given table from the hash tables and the delete the
95124 ** table structure with all its indices and foreign keys.
95125 */
@@ -95561,10 +97901,11 @@
95561 pCol->szEst = 1;
95562 }else{
95563 zType = z + sqlite3Strlen30(z) + 1;
95564 memcpy(zType, pType->z, pType->n);
95565 zType[pType->n] = 0;
 
95566 pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
95567 pCol->colFlags |= COLFLAG_HASTYPE;
95568 }
95569 p->nCol++;
95570 pParse->constraintName.n = 0;
@@ -96695,11 +99036,11 @@
96695 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
96696 }else{
96697 pTable->nCol = 0;
96698 nErr++;
96699 }
96700 if( pSelTab ) sqlite3DeleteTable(db, pSelTab);
96701 sqlite3SelectDelete(db, pSel);
96702 db->lookaside.bDisable--;
96703 } else {
96704 nErr++;
96705 }
@@ -97248,10 +99589,11 @@
97248 tnum = memRootPage;
97249 }else{
97250 tnum = pIndex->tnum;
97251 }
97252 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
 
97253
97254 /* Open the sorter cursor if we are to use one. */
97255 iSorter = pParse->nTab++;
97256 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
97257 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
@@ -97271,12 +99613,11 @@
97271 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
97272 (char *)pKey, P4_KEYINFO);
97273 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
97274
97275 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
97276 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
97277 if( IsUniqueIndex(pIndex) && pKey!=0 ){
97278 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
97279 sqlite3VdbeGoto(v, j2);
97280 addr2 = sqlite3VdbeCurrentAddr(v);
97281 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
97282 pIndex->nKeyCol); VdbeCoverage(v);
@@ -99526,11 +101867,11 @@
99526
99527 /* Check that there isn't an ORDER BY without a LIMIT clause.
99528 */
99529 if( pOrderBy && (pLimit == 0) ) {
99530 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
99531 goto limit_where_cleanup_2;
99532 }
99533
99534 /* We only need to generate a select expression if there
99535 ** is a limit/offset term to enforce.
99536 */
@@ -99548,44 +101889,34 @@
99548 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
99549 ** );
99550 */
99551
99552 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
99553 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
99554 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
99555 if( pEList == 0 ) goto limit_where_cleanup_2;
99556
99557 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
99558 ** and the SELECT subtree. */
99559 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
99560 if( pSelectSrc == 0 ) {
99561 sqlite3ExprListDelete(pParse->db, pEList);
99562 goto limit_where_cleanup_2;
99563 }
99564
99565 /* generate the SELECT expression tree. */
99566 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
99567 pOrderBy,0,pLimit,pOffset);
99568 if( pSelect == 0 ) return 0;
99569
99570 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
99571 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
99572 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
99573 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
99574 if( pInClause == 0 ) goto limit_where_cleanup_1;
99575
99576 pInClause->x.pSelect = pSelect;
99577 pInClause->flags |= EP_xIsSelect;
99578 sqlite3ExprSetHeightAndFlags(pParse, pInClause);
99579 return pInClause;
99580
99581 /* something went wrong. clean up anything allocated. */
99582 limit_where_cleanup_1:
99583 sqlite3SelectDelete(pParse->db, pSelect);
99584 return 0;
99585
99586 limit_where_cleanup_2:
99587 sqlite3ExprDelete(pParse->db, pWhere);
99588 sqlite3ExprListDelete(pParse->db, pOrderBy);
99589 sqlite3ExprDelete(pParse->db, pLimit);
99590 sqlite3ExprDelete(pParse->db, pOffset);
99591 return 0;
@@ -99632,15 +101963,16 @@
99632 int iEphCur = 0; /* Ephemeral table holding all primary key values */
99633 int iRowSet = 0; /* Register for rowset of rows to delete */
99634 int addrBypass = 0; /* Address of jump over the delete logic */
99635 int addrLoop = 0; /* Top of the delete loop */
99636 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
 
 
99637
99638 #ifndef SQLITE_OMIT_TRIGGER
99639 int isView; /* True if attempting to delete from a view */
99640 Trigger *pTrigger; /* List of table triggers, if required */
99641 int bComplex; /* True if there are either triggers or FKs */
99642 #endif
99643
99644 memset(&sContext, 0, sizeof(sContext));
99645 db = pParse->db;
99646 if( pParse->nErr || db->mallocFailed ){
@@ -99664,11 +101996,10 @@
99664 isView = pTab->pSelect!=0;
99665 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
99666 #else
99667 # define pTrigger 0
99668 # define isView 0
99669 # define bComplex 0
99670 #endif
99671 #ifdef SQLITE_OMIT_VIEW
99672 # undef isView
99673 # define isView 0
99674 #endif
@@ -99749,10 +102080,13 @@
99749 ** API function sqlite3_count_changes) to be set incorrectly. */
99750 if( rcauth==SQLITE_OK
99751 && pWhere==0
99752 && !bComplex
99753 && !IsVirtual(pTab)
 
 
 
99754 ){
99755 assert( !isView );
99756 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
99757 if( HasRowid(pTab) ){
99758 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
@@ -99763,11 +102097,12 @@
99763 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
99764 }
99765 }else
99766 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
99767 {
99768 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
 
99769 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
99770 if( HasRowid(pTab) ){
99771 /* For a rowid table, initialize the RowSet to an empty set */
99772 pPk = 0;
99773 nPk = 1;
@@ -100098,18 +102433,23 @@
100098 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
100099 }
100100
100101 /* Delete the index and table entries. Skip this step if pTab is really
100102 ** a view (in which case the only effect of the DELETE statement is to
100103 ** fire the INSTEAD OF triggers). */
 
 
 
 
 
 
 
100104 if( pTab->pSelect==0 ){
100105 u8 p5 = 0;
100106 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
100107 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
100108 if( count ){
100109 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
100110 }
100111 if( eMode!=ONEPASS_OFF ){
100112 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
100113 }
100114 if( iIdxNoSeek>=0 ){
100115 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
@@ -101669,10 +104009,18 @@
101669 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
101670 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
101671 const char *zProc;
101672 sqlite3 *db = sqlite3_context_db_handle(context);
101673 char *zErrMsg = 0;
 
 
 
 
 
 
 
 
101674
101675 if( argc==2 ){
101676 zProc = (const char *)sqlite3_value_text(argv[1]);
101677 }else{
101678 zProc = 0;
@@ -103268,11 +105616,10 @@
103268
103269 action = pFKey->aAction[iAction];
103270 if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
103271 return 0;
103272 }
103273
103274 pTrigger = pFKey->apTrigger[iAction];
103275
103276 if( action!=OE_None && !pTrigger ){
103277 char const *zFrom; /* Name of child table */
103278 int nFrom; /* Length in bytes of zFrom */
@@ -104945,13 +107292,22 @@
104945 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
104946 }
104947 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
104948 sqlite3MultiWrite(pParse);
104949 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
104950 regNewData, 1, 0, OE_Replace,
104951 ONEPASS_SINGLE, -1);
104952 }else{
 
 
 
 
 
 
 
 
 
 
104953 if( pTab->pIndex ){
104954 sqlite3MultiWrite(pParse);
104955 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
104956 }
104957 }
@@ -105217,11 +107573,11 @@
105217 if( useSeekResult ){
105218 pik_flags |= OPFLAG_USESEEKRESULT;
105219 }
105220 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
105221 if( !pParse->nested ){
105222 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
105223 }
105224 sqlite3VdbeChangeP5(v, pik_flags);
105225 }
105226
105227 /*
@@ -105617,11 +107973,11 @@
105617 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
105618 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
105619 }
105620 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
105621 sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
105622 pDest->zName, 0);
105623 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
105624 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
105625 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
105626 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
105627 }else{
@@ -106856,12 +109212,13 @@
106856 if( pzErrMsg ) *pzErrMsg = 0;
106857
106858 /* Ticket #1863. To avoid a creating security problems for older
106859 ** applications that relink against newer versions of SQLite, the
106860 ** ability to run load_extension is turned off by default. One
106861 ** must call sqlite3_enable_load_extension() to turn on extension
106862 ** loading. Otherwise you get the following error.
 
106863 */
106864 if( (db->flags & SQLITE_LoadExtension)==0 ){
106865 if( pzErrMsg ){
106866 *pzErrMsg = sqlite3_mprintf("not authorized");
106867 }
@@ -106996,13 +109353,13 @@
106996 ** default so as not to open security holes in older applications.
106997 */
106998 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
106999 sqlite3_mutex_enter(db->mutex);
107000 if( onoff ){
107001 db->flags |= SQLITE_LoadExtension;
107002 }else{
107003 db->flags &= ~SQLITE_LoadExtension;
107004 }
107005 sqlite3_mutex_leave(db->mutex);
107006 return SQLITE_OK;
107007 }
107008
@@ -110575,11 +112932,11 @@
110575 sqlite3ExprListDelete(db, p->pGroupBy);
110576 sqlite3ExprDelete(db, p->pHaving);
110577 sqlite3ExprListDelete(db, p->pOrderBy);
110578 sqlite3ExprDelete(db, p->pLimit);
110579 sqlite3ExprDelete(db, p->pOffset);
110580 sqlite3WithDelete(db, p->pWith);
110581 if( bFree ) sqlite3DbFree(db, p);
110582 p = pPrior;
110583 bFree = 1;
110584 }
110585 }
@@ -110670,11 +113027,11 @@
110670
110671 /*
110672 ** Delete the given Select structure and all of its substructures.
110673 */
110674 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
110675 clearSelect(db, p, 1);
110676 }
110677
110678 /*
110679 ** Return a pointer to the right-most SELECT statement in a compound.
110680 */
@@ -112290,23 +114647,23 @@
112290
112291 /*
112292 ** Get a VDBE for the given parser context. Create a new one if necessary.
112293 ** If an error occurs, return NULL and leave a message in pParse.
112294 */
112295 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
112296 Vdbe *v = pParse->pVdbe;
112297 if( v==0 ){
112298 v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
112299 if( v ) sqlite3VdbeAddOp0(v, OP_Init);
112300 if( pParse->pToplevel==0
112301 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
112302 ){
112303 pParse->okConstFactor = 1;
112304 }
112305
112306 }
112307 return v;
 
 
 
 
112308 }
112309
112310
112311 /*
112312 ** Compute the iLimit and iOffset fields of the SELECT based on the
@@ -114286,16 +116643,22 @@
114286 Expr *pWhere, /* The WHERE clause of the outer query */
114287 int iCursor /* Cursor number of the subquery */
114288 ){
114289 Expr *pNew;
114290 int nChng = 0;
 
114291 if( pWhere==0 ) return 0;
114292 if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
114293 return 0; /* restrictions (1) and (2) */
 
 
 
 
 
114294 }
114295 if( pSubq->pLimit!=0 ){
114296 return 0; /* restriction (3) */
114297 }
114298 while( pWhere->op==TK_AND ){
114299 nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
114300 pWhere = pWhere->pLeft;
114301 }
@@ -115593,10 +117956,17 @@
115593 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
115594 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
115595 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
115596 ** original setting of the SF_Distinct flag, not the current setting */
115597 assert( sDistinct.isTnct );
 
 
 
 
 
 
 
115598 }
115599
115600 /* If there is an ORDER BY clause, then create an ephemeral index to
115601 ** do the sorting. But this sorting ephemeral index might end up
115602 ** being unused if the data can be extracted in pre-sorted order.
@@ -117831,11 +120201,12 @@
117831 /* Begin the database scan
117832 */
117833 if( HasRowid(pTab) ){
117834 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
117835 pWInfo = sqlite3WhereBegin(
117836 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
 
117837 );
117838 if( pWInfo==0 ) goto update_cleanup;
117839 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
117840
117841 /* Remember the rowid of every item to be updated.
@@ -118069,15 +120440,34 @@
118069 addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
118070 }
118071 VdbeCoverageNeverTaken(v);
118072 }
118073 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
118074
118075 /* If changing the record number, delete the old record. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118076 if( hasFK || chngKey || pPk!=0 ){
118077 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
118078 }
 
118079 if( bReplace || chngKey ){
118080 sqlite3VdbeJumpHere(v, addr1);
118081 }
118082
118083 if( hasFK ){
@@ -119969,11 +122359,11 @@
119969 int addrSkip; /* Jump here for next iteration of skip-scan */
119970 int addrCont; /* Jump here to continue with the next loop cycle */
119971 int addrFirst; /* First instruction of interior of the loop */
119972 int addrBody; /* Beginning of the body of this loop */
119973 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
119974 int iLikeRepCntr; /* LIKE range processing counter register */
119975 int addrLikeRep; /* LIKE range processing address */
119976 #endif
119977 u8 iFrom; /* Which entry in the FROM clause */
119978 u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
119979 int p1, p2; /* Operands of the opcode used to ends the loop */
@@ -120307,11 +122697,11 @@
120307 */
120308 struct WhereInfo {
120309 Parse *pParse; /* Parsing and code generating context */
120310 SrcList *pTabList; /* List of tables in the join */
120311 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
120312 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
120313 WhereLoop *pLoops; /* List of all WhereLoop objects */
120314 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
120315 LogEst nRowOut; /* Estimated number of output rows */
120316 LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
120317 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
@@ -120391,10 +122781,18 @@
120391 /*
120392 ** Bitmasks for the operators on WhereTerm objects. These are all
120393 ** operators that are of interest to the query planner. An
120394 ** OR-ed combination of these values can be used when searching for
120395 ** particular WhereTerms within a WhereClause.
 
 
 
 
 
 
 
 
120396 */
120397 #define WO_IN 0x0001
120398 #define WO_EQ 0x0002
120399 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
120400 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -120977,13 +123375,14 @@
120977 return regBase;
120978 }
120979
120980 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
120981 /*
120982 ** If the most recently coded instruction is a constant range contraint
120983 ** that originated from the LIKE optimization, then change the P3 to be
120984 ** pLoop->iLikeRepCntr and set P5.
 
120985 **
120986 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
120987 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
120988 ** scan loop run twice, once for strings and a second time for BLOBs.
120989 ** The OP_String opcodes on the second pass convert the upper and lower
@@ -121004,12 +123403,12 @@
121004 assert( pLevel->iLikeRepCntr>0 );
121005 pOp = sqlite3VdbeGetOp(v, -1);
121006 assert( pOp!=0 );
121007 assert( pOp->opcode==OP_String8
121008 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
121009 pOp->p3 = pLevel->iLikeRepCntr;
121010 pOp->p5 = 1;
121011 }
121012 }
121013 #else
121014 # define whereLikeOptimizationStringFixup(A,B,C)
121015 #endif
@@ -121358,11 +123757,17 @@
121358 pCompare->pLeft = 0;
121359 sqlite3ExprDelete(db, pCompare);
121360 }
121361 }
121362 }
121363 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
 
 
 
 
 
 
121364 sqlite3ExprCachePop(pParse);
121365 }else
121366 #endif /* SQLITE_OMIT_VIRTUALTABLE */
121367
121368 if( (pLoop->wsFlags & WHERE_IPK)!=0
@@ -121586,18 +123991,21 @@
121586 nExtraReg = 1;
121587 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
121588 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
121589 assert( pRangeStart!=0 ); /* LIKE opt constraints */
121590 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
121591 pLevel->iLikeRepCntr = ++pParse->nMem;
 
 
 
 
 
121592 testcase( bRev );
121593 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
121594 sqlite3VdbeAddOp2(v, OP_Integer,
121595 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
121596 pLevel->iLikeRepCntr);
121597 VdbeComment((v, "LIKE loop counter"));
121598 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
121599 }
121600 #endif
121601 if( pRangeStart==0
121602 && (j = pIdx->aiColumn[nEq])>=0
121603 && pIdx->pTable->aCol[j].notNull==0
@@ -121731,11 +124139,11 @@
121731 disableTerm(pLevel, pRangeStart);
121732 disableTerm(pLevel, pRangeEnd);
121733 if( omitTable ){
121734 /* pIdx is a covering index. No need to access the main table. */
121735 }else if( HasRowid(pIdx->pTable) ){
121736 if( pWInfo->eOnePass!=ONEPASS_OFF ){
121737 iRowidReg = ++pParse->nMem;
121738 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
121739 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
121740 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
121741 VdbeCoverage(v);
@@ -121927,11 +124335,12 @@
121927 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
121928 */
121929 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
121930 | WHERE_FORCE_TABLE
121931 | WHERE_ONETABLE_ONLY
121932 | WHERE_NO_AUTOINDEX;
 
121933 for(ii=0; ii<pOrWc->nTerm; ii++){
121934 WhereTerm *pOrTerm = &pOrWc->a[ii];
121935 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
121936 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
121937 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
@@ -122107,15 +124516,21 @@
122107 assert( pE!=0 );
122108 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
122109 continue;
122110 }
122111 if( pTerm->wtFlags & TERM_LIKECOND ){
 
 
 
 
 
122112 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
122113 continue;
122114 #else
122115 assert( pLevel->iLikeRepCntr>0 );
122116 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
 
122117 VdbeCoverage(v);
122118 #endif
122119 }
122120 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
122121 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
@@ -123467,14 +125882,14 @@
123467 if( p->op==TK_COLUMN ){
123468 mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
123469 return mask;
123470 }
123471 mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
123472 mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
123473 if( ExprHasProperty(p, EP_xIsSelect) ){
123474 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
123475 }else{
123476 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
123477 }
123478 return mask;
123479 }
123480 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
@@ -123810,11 +126225,14 @@
123810 ** Initialize a WHERE clause scanner object. Return a pointer to the
123811 ** first match. Return NULL if there are no matches.
123812 **
123813 ** The scanner will be searching the WHERE clause pWC. It will look
123814 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
123815 ** iCur. The <op> must be one of the operators described by opMask.
 
 
 
123816 **
123817 ** If the search is for X and the WHERE clause contains terms of the
123818 ** form X=Y then this routine might also return terms of the form
123819 ** "Y <op> <expr>". The number of levels of transitivity is limited,
123820 ** but is enough to handle most commonly occurring SQL statements.
@@ -123858,15 +126276,16 @@
123858 return whereScanNext(pScan);
123859 }
123860
123861 /*
123862 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
123863 ** where X is a reference to the iColumn of table iCur and <op> is one of
123864 ** the WO_xx operator codes specified by the op parameter.
123865 ** Return a pointer to the term. Return 0 if not found.
123866 **
123867 ** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx
 
123868 ** rather than the iColumn-th column of table iCur.
123869 **
123870 ** The term returned might by Y=<expr> if there is another constraint in
123871 ** the WHERE clause that specifies that X=Y. Any such constraints will be
123872 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
@@ -125200,15 +127619,16 @@
125200 /*
125201 ** Print a WhereLoop object for debugging purposes
125202 */
125203 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
125204 WhereInfo *pWInfo = pWC->pWInfo;
125205 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
125206 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
125207 Table *pTab = pItem->pTab;
 
125208 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
125209 p->iTab, nb, p->maskSelf, nb, p->prereq);
125210 sqlite3DebugPrintf(" %12s",
125211 pItem->zAlias ? pItem->zAlias : pTab->zName);
125212 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
125213 const char *zName;
125214 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
@@ -127429,13 +129849,13 @@
127429 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
127430 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
127431 && nRowEst
127432 ){
127433 Bitmask notUsed;
127434 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
127435 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
127436 if( rc==pWInfo->pResultSet->nExpr ){
127437 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
127438 }
127439 }
127440 if( pWInfo->pOrderBy ){
127441 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
@@ -127646,18 +130066,18 @@
127646 ** the first cursor in an array of cursors for all indices. iIdxCur should
127647 ** be used to compute the appropriate cursor depending on which index is
127648 ** used.
127649 */
127650 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
127651 Parse *pParse, /* The parser context */
127652 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
127653 Expr *pWhere, /* The WHERE clause */
127654 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
127655 ExprList *pResultSet, /* Result set of the query */
127656 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
127657 int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number,
127658 ** If WHERE_USE_LIMIT, then the limit amount */
127659 ){
127660 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
127661 int nTabList; /* Number of elements in pTabList */
127662 WhereInfo *pWInfo; /* Will become the return value of this function */
127663 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -127728,11 +130148,11 @@
127728 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
127729 pWInfo->nLevel = nTabList;
127730 pWInfo->pParse = pParse;
127731 pWInfo->pTabList = pTabList;
127732 pWInfo->pOrderBy = pOrderBy;
127733 pWInfo->pResultSet = pResultSet;
127734 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
127735 pWInfo->wctrlFlags = wctrlFlags;
127736 pWInfo->iLimit = iAuxArg;
127737 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
127738 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
@@ -127801,17 +130221,17 @@
127801 /* Analyze all of the subexpressions. */
127802 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
127803 if( db->mallocFailed ) goto whereBeginError;
127804
127805 if( wctrlFlags & WHERE_WANT_DISTINCT ){
127806 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
127807 /* The DISTINCT marking is pointless. Ignore it. */
127808 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
127809 }else if( pOrderBy==0 ){
127810 /* Try to ORDER BY the result set to make distinct processing easier */
127811 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
127812 pWInfo->pOrderBy = pResultSet;
127813 }
127814 }
127815
127816 /* Construct the WhereLoop objects */
127817 #if defined(WHERETRACE_ENABLED)
@@ -127886,14 +130306,14 @@
127886 }
127887 }
127888 #endif
127889 /* Attempt to omit tables from the join that do not effect the result */
127890 if( pWInfo->nLevel>=2
127891 && pResultSet!=0
127892 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
127893 ){
127894 Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
127895 if( sWLB.pOrderBy ){
127896 tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
127897 }
127898 while( pWInfo->nLevel>=2 ){
127899 WhereTerm *pTerm, *pEnd;
@@ -128155,17 +130575,12 @@
128155 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
128156 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
128157 }
128158 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
128159 if( pLevel->addrLikeRep ){
128160 int op;
128161 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
128162 op = OP_DecrJumpZero;
128163 }else{
128164 op = OP_JumpZeroIncr;
128165 }
128166 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
128167 VdbeCoverage(v);
128168 }
128169 #endif
128170 if( pLevel->iLeftJoin ){
128171 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
@@ -128567,11 +130982,11 @@
128567 #endif
128568 /************* Begin control #defines *****************************************/
128569 #define YYCODETYPE unsigned char
128570 #define YYNOCODE 251
128571 #define YYACTIONTYPE unsigned short int
128572 #define YYWILDCARD 70
128573 #define sqlite3ParserTOKENTYPE Token
128574 typedef union {
128575 int yyinit;
128576 sqlite3ParserTOKENTYPE yy0;
128577 struct LimitVal yy64;
@@ -128671,402 +131086,404 @@
128671 ** yy_reduce_ofst[] For each state, the offset into yy_action for
128672 ** shifting non-terminals after a reduce.
128673 ** yy_default[] Default action for each state.
128674 **
128675 *********** Begin parsing tables **********************************************/
128676 #define YY_ACTTAB_COUNT (1499)
128677 static const YYACTIONTYPE yy_action[] = {
128678 /* 0 */ 315, 1302, 146, 921, 2, 194, 922, 342, 952, 91,
128679 /* 10 */ 91, 91, 91, 84, 89, 89, 89, 89, 88, 88,
128680 /* 20 */ 87, 87, 87, 86, 339, 87, 87, 87, 86, 339,
128681 /* 30 */ 331, 819, 819, 91, 91, 91, 91, 339, 89, 89,
128682 /* 40 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 319,
128683 /* 50 */ 933, 933, 92, 93, 83, 831, 834, 823, 823, 90,
128684 /* 60 */ 90, 91, 91, 91, 91, 123, 89, 89, 89, 89,
128685 /* 70 */ 88, 88, 87, 87, 87, 86, 339, 315, 952, 89,
128686 /* 80 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
128687 /* 90 */ 365, 772, 360, 24, 933, 933, 947, 694, 933, 933,
128688 /* 100 */ 773, 937, 933, 933, 434, 715, 328, 434, 819, 819,
128689 /* 110 */ 203, 160, 278, 391, 273, 390, 190, 933, 933, 370,
128690 /* 120 */ 934, 935, 367, 271, 953, 48, 679, 953, 48, 92,
128691 /* 130 */ 93, 83, 831, 834, 823, 823, 90, 90, 91, 91,
128692 /* 140 */ 91, 91, 123, 89, 89, 89, 89, 88, 88, 87,
128693 /* 150 */ 87, 87, 86, 339, 315, 682, 337, 336, 218, 412,
128694 /* 160 */ 398, 68, 412, 403, 934, 935, 743, 959, 934, 935,
128695 /* 170 */ 810, 937, 934, 935, 957, 221, 958, 88, 88, 87,
128696 /* 180 */ 87, 87, 86, 339, 291, 819, 819, 934, 935, 185,
128697 /* 190 */ 94, 792, 388, 385, 384, 1240, 1240, 792, 804, 960,
128698 /* 200 */ 960, 290, 798, 383, 123, 315, 92, 93, 83, 831,
128699 /* 210 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
128700 /* 220 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
128701 /* 230 */ 339, 681, 741, 803, 803, 803, 819, 819, 944, 56,
128702 /* 240 */ 253, 353, 242, 85, 82, 168, 253, 358, 252, 110,
128703 /* 250 */ 96, 233, 397, 698, 677, 683, 683, 92, 93, 83,
128704 /* 260 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
128705 /* 270 */ 433, 89, 89, 89, 89, 88, 88, 87, 87, 87,
128706 /* 280 */ 86, 339, 315, 434, 439, 651, 396, 57, 733, 733,
128707 /* 290 */ 234, 291, 107, 287, 395, 86, 339, 810, 427, 728,
128708 /* 300 */ 933, 933, 185, 953, 30, 388, 385, 384, 215, 949,
128709 /* 310 */ 434, 933, 933, 819, 819, 697, 383, 162, 161, 407,
128710 /* 320 */ 400, 85, 82, 168, 677, 804, 335, 113, 771, 798,
128711 /* 330 */ 953, 48, 22, 351, 92, 93, 83, 831, 834, 823,
128712 /* 340 */ 823, 90, 90, 91, 91, 91, 91, 870, 89, 89,
128713 /* 350 */ 89, 89, 88, 88, 87, 87, 87, 86, 339, 315,
128714 /* 360 */ 803, 803, 803, 268, 123, 412, 394, 1, 933, 933,
128715 /* 370 */ 934, 935, 933, 933, 85, 82, 168, 232, 5, 343,
128716 /* 380 */ 194, 934, 935, 952, 85, 82, 168, 54, 956, 434,
128717 /* 390 */ 819, 819, 431, 938, 939, 792, 67, 759, 350, 144,
128718 /* 400 */ 166, 770, 123, 896, 889, 955, 348, 288, 758, 953,
128719 /* 410 */ 47, 92, 93, 83, 831, 834, 823, 823, 90, 90,
128720 /* 420 */ 91, 91, 91, 91, 892, 89, 89, 89, 89, 88,
128721 /* 430 */ 88, 87, 87, 87, 86, 339, 315, 113, 934, 935,
128722 /* 440 */ 687, 893, 934, 935, 253, 358, 252, 85, 82, 168,
128723 /* 450 */ 820, 820, 956, 952, 338, 938, 939, 894, 701, 721,
128724 /* 460 */ 359, 289, 233, 397, 434, 349, 434, 819, 819, 955,
128725 /* 470 */ 866, 722, 23, 389, 832, 835, 692, 357, 904, 667,
128726 /* 480 */ 194, 702, 402, 952, 953, 48, 953, 48, 92, 93,
128727 /* 490 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
128728 /* 500 */ 91, 824, 89, 89, 89, 89, 88, 88, 87, 87,
128729 /* 510 */ 87, 86, 339, 315, 434, 113, 434, 680, 434, 332,
128730 /* 520 */ 434, 408, 889, 356, 380, 940, 401, 720, 948, 864,
128731 /* 530 */ 191, 165, 329, 689, 953, 9, 953, 9, 953, 9,
128732 /* 540 */ 953, 9, 718, 948, 819, 819, 953, 8, 325, 111,
128733 /* 550 */ 327, 153, 224, 952, 410, 113, 189, 337, 336, 913,
128734 /* 560 */ 1295, 852, 75, 1295, 73, 92, 93, 83, 831, 834,
128735 /* 570 */ 823, 823, 90, 90, 91, 91, 91, 91, 359, 89,
128736 /* 580 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
128737 /* 590 */ 315, 730, 148, 236, 797, 366, 789, 892, 1179, 434,
128738 /* 600 */ 960, 960, 400, 148, 314, 212, 873, 911, 757, 404,
128739 /* 610 */ 872, 300, 320, 434, 893, 311, 237, 271, 405, 953,
128740 /* 620 */ 34, 819, 819, 225, 371, 945, 360, 913, 1296, 113,
128741 /* 630 */ 894, 1296, 417, 953, 35, 1245, 922, 342, 259, 247,
128742 /* 640 */ 290, 315, 92, 93, 83, 831, 834, 823, 823, 90,
128743 /* 650 */ 90, 91, 91, 91, 91, 148, 89, 89, 89, 89,
128744 /* 660 */ 88, 88, 87, 87, 87, 86, 339, 310, 434, 796,
128745 /* 670 */ 434, 240, 819, 819, 266, 911, 876, 876, 373, 346,
128746 /* 680 */ 167, 654, 655, 656, 259, 244, 19, 246, 953, 11,
128747 /* 690 */ 953, 26, 222, 92, 93, 83, 831, 834, 823, 823,
128748 /* 700 */ 90, 90, 91, 91, 91, 91, 757, 89, 89, 89,
128749 /* 710 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 434,
128750 /* 720 */ 261, 434, 264, 696, 434, 241, 434, 344, 971, 308,
128751 /* 730 */ 757, 434, 796, 434, 324, 434, 393, 423, 434, 953,
128752 /* 740 */ 36, 953, 37, 20, 953, 38, 953, 27, 434, 819,
128753 /* 750 */ 819, 953, 28, 953, 39, 953, 40, 738, 953, 41,
128754 /* 760 */ 71, 738, 737, 245, 307, 973, 737, 259, 953, 10,
128755 /* 770 */ 92, 93, 83, 831, 834, 823, 823, 90, 90, 91,
128756 /* 780 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
128757 /* 790 */ 87, 87, 87, 86, 339, 315, 434, 372, 434, 259,
128758 /* 800 */ 149, 434, 167, 953, 42, 188, 187, 186, 219, 434,
128759 /* 810 */ 748, 434, 974, 434, 796, 434, 953, 98, 953, 43,
128760 /* 820 */ 862, 953, 44, 434, 920, 2, 819, 819, 757, 953,
128761 /* 830 */ 31, 953, 45, 953, 46, 953, 32, 74, 307, 912,
128762 /* 840 */ 220, 259, 259, 953, 115, 909, 315, 92, 93, 83,
128763 /* 850 */ 831, 834, 823, 823, 90, 90, 91, 91, 91, 91,
128764 /* 860 */ 434, 89, 89, 89, 89, 88, 88, 87, 87, 87,
128765 /* 870 */ 86, 339, 434, 248, 434, 215, 949, 819, 819, 333,
128766 /* 880 */ 953, 116, 895, 860, 176, 259, 974, 400, 361, 259,
128767 /* 890 */ 951, 887, 953, 117, 953, 52, 884, 315, 92, 93,
128768 /* 900 */ 83, 831, 834, 823, 823, 90, 90, 91, 91, 91,
128769 /* 910 */ 91, 434, 89, 89, 89, 89, 88, 88, 87, 87,
128770 /* 920 */ 87, 86, 339, 434, 113, 434, 258, 883, 819, 819,
128771 /* 930 */ 727, 953, 33, 363, 259, 673, 321, 189, 430, 321,
128772 /* 940 */ 368, 365, 364, 953, 99, 953, 49, 365, 315, 92,
128773 /* 950 */ 81, 83, 831, 834, 823, 823, 90, 90, 91, 91,
128774 /* 960 */ 91, 91, 434, 89, 89, 89, 89, 88, 88, 87,
128775 /* 970 */ 87, 87, 86, 339, 434, 723, 434, 214, 165, 819,
128776 /* 980 */ 819, 772, 953, 100, 322, 124, 1269, 158, 65, 710,
128777 /* 990 */ 773, 700, 699, 320, 953, 101, 953, 97, 255, 315,
128778 /* 1000 */ 216, 93, 83, 831, 834, 823, 823, 90, 90, 91,
128779 /* 1010 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
128780 /* 1020 */ 87, 87, 87, 86, 339, 434, 251, 434, 707, 708,
128781 /* 1030 */ 819, 819, 223, 953, 114, 908, 794, 254, 309, 193,
128782 /* 1040 */ 67, 381, 869, 869, 199, 953, 112, 953, 105, 269,
128783 /* 1050 */ 726, 260, 67, 83, 831, 834, 823, 823, 90, 90,
128784 /* 1060 */ 91, 91, 91, 91, 263, 89, 89, 89, 89, 88,
128785 /* 1070 */ 88, 87, 87, 87, 86, 339, 79, 429, 690, 3,
128786 /* 1080 */ 1174, 228, 434, 113, 340, 340, 868, 868, 265, 79,
128787 /* 1090 */ 429, 735, 3, 859, 70, 432, 434, 340, 340, 434,
128788 /* 1100 */ 1259, 434, 953, 104, 434, 670, 416, 766, 432, 434,
128789 /* 1110 */ 193, 434, 413, 434, 418, 806, 953, 102, 420, 953,
128790 /* 1120 */ 103, 953, 48, 123, 953, 51, 810, 418, 424, 953,
128791 /* 1130 */ 53, 953, 50, 953, 25, 267, 123, 711, 113, 810,
128792 /* 1140 */ 428, 277, 695, 272, 764, 113, 76, 77, 690, 434,
128793 /* 1150 */ 795, 113, 276, 78, 436, 435, 412, 414, 798, 76,
128794 /* 1160 */ 77, 113, 855, 859, 376, 199, 78, 436, 435, 953,
128795 /* 1170 */ 29, 798, 744, 113, 755, 79, 429, 675, 3, 415,
128796 /* 1180 */ 109, 292, 293, 340, 340, 806, 802, 678, 672, 803,
128797 /* 1190 */ 803, 803, 805, 18, 432, 661, 660, 662, 927, 209,
128798 /* 1200 */ 150, 352, 803, 803, 803, 805, 18, 6, 306, 280,
128799 /* 1210 */ 282, 284, 786, 418, 250, 386, 243, 886, 694, 362,
128800 /* 1220 */ 286, 163, 275, 79, 429, 810, 3, 857, 856, 159,
128801 /* 1230 */ 419, 340, 340, 298, 930, 968, 126, 196, 965, 903,
128802 /* 1240 */ 901, 323, 432, 136, 55, 76, 77, 742, 147, 58,
128803 /* 1250 */ 121, 129, 78, 436, 435, 65, 783, 798, 354, 131,
128804 /* 1260 */ 355, 418, 379, 132, 133, 134, 175, 139, 151, 369,
128805 /* 1270 */ 888, 180, 791, 810, 61, 851, 871, 69, 429, 375,
128806 /* 1280 */ 3, 756, 210, 257, 181, 340, 340, 145, 803, 803,
128807 /* 1290 */ 803, 805, 18, 76, 77, 377, 432, 262, 182, 183,
128808 /* 1300 */ 78, 436, 435, 663, 312, 798, 392, 714, 713, 712,
128809 /* 1310 */ 330, 705, 692, 313, 704, 418, 686, 406, 752, 685,
128810 /* 1320 */ 274, 684, 942, 64, 279, 195, 281, 810, 753, 839,
128811 /* 1330 */ 751, 283, 72, 750, 285, 422, 803, 803, 803, 805,
128812 /* 1340 */ 18, 334, 426, 95, 411, 229, 409, 76, 77, 230,
128813 /* 1350 */ 734, 66, 231, 294, 78, 436, 435, 204, 295, 798,
128814 /* 1360 */ 217, 296, 297, 669, 21, 305, 304, 303, 206, 301,
128815 /* 1370 */ 437, 928, 664, 205, 208, 207, 438, 658, 657, 652,
128816 /* 1380 */ 118, 108, 119, 226, 650, 341, 157, 170, 169, 239,
128817 /* 1390 */ 803, 803, 803, 805, 18, 125, 120, 235, 238, 317,
128818 /* 1400 */ 318, 345, 106, 790, 867, 127, 865, 128, 130, 724,
128819 /* 1410 */ 249, 172, 174, 882, 135, 137, 59, 138, 173, 60,
128820 /* 1420 */ 885, 123, 171, 177, 178, 881, 7, 12, 179, 256,
128821 /* 1430 */ 874, 140, 193, 962, 374, 141, 666, 152, 378, 276,
128822 /* 1440 */ 184, 382, 142, 122, 62, 13, 387, 703, 270, 14,
128823 /* 1450 */ 63, 227, 809, 808, 837, 732, 15, 841, 736, 4,
128824 /* 1460 */ 765, 211, 399, 164, 213, 143, 760, 201, 70, 316,
128825 /* 1470 */ 67, 838, 836, 891, 198, 192, 16, 197, 890, 917,
128826 /* 1480 */ 154, 17, 202, 421, 918, 155, 200, 156, 425, 840,
128827 /* 1490 */ 807, 1261, 676, 80, 302, 299, 347, 1260, 923,
 
128828 };
128829 static const YYCODETYPE yy_lookahead[] = {
128830 /* 0 */ 19, 144, 145, 146, 147, 24, 1, 2, 27, 80,
128831 /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
128832 /* 20 */ 91, 92, 93, 94, 95, 91, 92, 93, 94, 95,
128833 /* 30 */ 19, 50, 51, 80, 81, 82, 83, 95, 85, 86,
128834 /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 157,
128835 /* 50 */ 27, 28, 71, 72, 73, 74, 75, 76, 77, 78,
128836 /* 60 */ 79, 80, 81, 82, 83, 66, 85, 86, 87, 88,
128837 /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 85,
128838 /* 80 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
128839 /* 90 */ 152, 33, 152, 22, 27, 28, 179, 180, 27, 28,
128840 /* 100 */ 42, 27, 27, 28, 152, 188, 95, 152, 50, 51,
128841 /* 110 */ 99, 100, 101, 102, 103, 104, 105, 27, 28, 227,
128842 /* 120 */ 97, 98, 230, 112, 172, 173, 172, 172, 173, 71,
128843 /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
128844 /* 140 */ 82, 83, 66, 85, 86, 87, 88, 89, 90, 91,
128845 /* 150 */ 92, 93, 94, 95, 19, 172, 89, 90, 218, 207,
128846 /* 160 */ 208, 26, 207, 208, 97, 98, 91, 100, 97, 98,
128847 /* 170 */ 69, 97, 97, 98, 107, 237, 109, 89, 90, 91,
128848 /* 180 */ 92, 93, 94, 95, 152, 50, 51, 97, 98, 99,
128849 /* 190 */ 55, 59, 102, 103, 104, 119, 120, 59, 97, 132,
128850 /* 200 */ 133, 152, 101, 113, 66, 19, 71, 72, 73, 74,
128851 /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 187,
128852 /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
128853 /* 230 */ 95, 172, 210, 132, 133, 134, 50, 51, 185, 53,
128854 /* 240 */ 108, 109, 110, 221, 222, 223, 108, 109, 110, 22,
128855 /* 250 */ 22, 119, 120, 181, 27, 27, 28, 71, 72, 73,
128856 /* 260 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
128857 /* 270 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
128858 /* 280 */ 94, 95, 19, 152, 148, 149, 115, 24, 117, 118,
128859 /* 290 */ 154, 152, 156, 152, 163, 94, 95, 69, 249, 163,
128860 /* 300 */ 27, 28, 99, 172, 173, 102, 103, 104, 194, 195,
128861 /* 310 */ 152, 27, 28, 50, 51, 181, 113, 89, 90, 152,
128862 /* 320 */ 206, 221, 222, 223, 97, 97, 187, 196, 175, 101,
128863 /* 330 */ 172, 173, 196, 219, 71, 72, 73, 74, 75, 76,
128864 /* 340 */ 77, 78, 79, 80, 81, 82, 83, 11, 85, 86,
128865 /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
128866 /* 360 */ 132, 133, 134, 23, 66, 207, 208, 22, 27, 28,
128867 /* 370 */ 97, 98, 27, 28, 221, 222, 223, 199, 22, 243,
128868 /* 380 */ 24, 97, 98, 27, 221, 222, 223, 209, 152, 152,
128869 /* 390 */ 50, 51, 168, 169, 170, 59, 26, 124, 100, 58,
128870 /* 400 */ 152, 175, 66, 240, 163, 169, 170, 152, 124, 172,
128871 /* 410 */ 173, 71, 72, 73, 74, 75, 76, 77, 78, 79,
128872 /* 420 */ 80, 81, 82, 83, 12, 85, 86, 87, 88, 89,
128873 /* 430 */ 90, 91, 92, 93, 94, 95, 19, 196, 97, 98,
128874 /* 440 */ 23, 29, 97, 98, 108, 109, 110, 221, 222, 223,
128875 /* 450 */ 50, 51, 152, 97, 168, 169, 170, 45, 37, 47,
128876 /* 460 */ 219, 224, 119, 120, 152, 229, 152, 50, 51, 169,
128877 /* 470 */ 170, 59, 231, 52, 74, 75, 106, 236, 152, 21,
128878 /* 480 */ 24, 60, 163, 27, 172, 173, 172, 173, 71, 72,
128879 /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
128880 /* 500 */ 83, 101, 85, 86, 87, 88, 89, 90, 91, 92,
128881 /* 510 */ 93, 94, 95, 19, 152, 196, 152, 23, 152, 207,
128882 /* 520 */ 152, 207, 163, 65, 19, 171, 152, 190, 191, 229,
128883 /* 530 */ 211, 212, 111, 179, 172, 173, 172, 173, 172, 173,
128884 /* 540 */ 172, 173, 190, 191, 50, 51, 172, 173, 186, 22,
128885 /* 550 */ 186, 24, 186, 97, 186, 196, 51, 89, 90, 22,
128886 /* 560 */ 23, 103, 137, 26, 139, 71, 72, 73, 74, 75,
128887 /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 219, 85,
128888 /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
128889 /* 590 */ 19, 195, 152, 152, 23, 236, 163, 12, 140, 152,
128890 /* 600 */ 132, 133, 206, 152, 164, 23, 31, 70, 26, 19,
128891 /* 610 */ 35, 160, 107, 152, 29, 164, 152, 112, 28, 172,
128892 /* 620 */ 173, 50, 51, 183, 49, 185, 152, 22, 23, 196,
128893 /* 630 */ 45, 26, 47, 172, 173, 0, 1, 2, 152, 16,
128894 /* 640 */ 152, 19, 71, 72, 73, 74, 75, 76, 77, 78,
128895 /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
128896 /* 660 */ 89, 90, 91, 92, 93, 94, 95, 164, 152, 152,
128897 /* 670 */ 152, 152, 50, 51, 16, 70, 108, 109, 110, 193,
128898 /* 680 */ 98, 7, 8, 9, 152, 62, 22, 64, 172, 173,
128899 /* 690 */ 172, 173, 218, 71, 72, 73, 74, 75, 76, 77,
128900 /* 700 */ 78, 79, 80, 81, 82, 83, 124, 85, 86, 87,
128901 /* 710 */ 88, 89, 90, 91, 92, 93, 94, 95, 19, 152,
128902 /* 720 */ 62, 152, 64, 181, 152, 193, 152, 241, 246, 247,
128903 /* 730 */ 26, 152, 152, 152, 217, 152, 91, 249, 152, 172,
128904 /* 740 */ 173, 172, 173, 79, 172, 173, 172, 173, 152, 50,
128905 /* 750 */ 51, 172, 173, 172, 173, 172, 173, 116, 172, 173,
128906 /* 760 */ 138, 116, 121, 140, 22, 23, 121, 152, 172, 173,
128907 /* 770 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
128908 /* 780 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
128909 /* 790 */ 91, 92, 93, 94, 95, 19, 152, 217, 152, 152,
128910 /* 800 */ 24, 152, 98, 172, 173, 108, 109, 110, 193, 152,
128911 /* 810 */ 213, 152, 70, 152, 152, 152, 172, 173, 172, 173,
128912 /* 820 */ 152, 172, 173, 152, 146, 147, 50, 51, 124, 172,
128913 /* 830 */ 173, 172, 173, 172, 173, 172, 173, 138, 22, 23,
128914 /* 840 */ 193, 152, 152, 172, 173, 152, 19, 71, 72, 73,
128915 /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
128916 /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
128917 /* 870 */ 94, 95, 152, 152, 152, 194, 195, 50, 51, 217,
128918 /* 880 */ 172, 173, 193, 193, 26, 152, 70, 206, 152, 152,
128919 /* 890 */ 26, 163, 172, 173, 172, 173, 152, 19, 71, 72,
128920 /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
128921 /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
128922 /* 920 */ 93, 94, 95, 152, 196, 152, 193, 152, 50, 51,
128923 /* 930 */ 193, 172, 173, 19, 152, 166, 167, 51, 166, 167,
128924 /* 940 */ 152, 152, 28, 172, 173, 172, 173, 152, 19, 71,
128925 /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
128926 /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
128927 /* 970 */ 92, 93, 94, 95, 152, 193, 152, 211, 212, 50,
128928 /* 980 */ 51, 33, 172, 173, 244, 245, 23, 123, 130, 26,
128929 /* 990 */ 42, 100, 101, 107, 172, 173, 172, 173, 152, 19,
128930 /* 1000 */ 22, 72, 73, 74, 75, 76, 77, 78, 79, 80,
128931 /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
128932 /* 1020 */ 91, 92, 93, 94, 95, 152, 237, 152, 7, 8,
128933 /* 1030 */ 50, 51, 237, 172, 173, 23, 23, 23, 26, 26,
128934 /* 1040 */ 26, 23, 132, 133, 26, 172, 173, 172, 173, 23,
128935 /* 1050 */ 163, 152, 26, 73, 74, 75, 76, 77, 78, 79,
128936 /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
128937 /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 27, 22,
128938 /* 1080 */ 23, 210, 152, 196, 27, 28, 132, 133, 152, 19,
128939 /* 1090 */ 20, 23, 22, 27, 26, 38, 152, 27, 28, 152,
128940 /* 1100 */ 122, 152, 172, 173, 152, 163, 191, 23, 38, 152,
128941 /* 1110 */ 26, 152, 163, 152, 57, 27, 172, 173, 163, 172,
128942 /* 1120 */ 173, 172, 173, 66, 172, 173, 69, 57, 163, 172,
128943 /* 1130 */ 173, 172, 173, 172, 173, 152, 66, 152, 196, 69,
128944 /* 1140 */ 163, 101, 152, 152, 152, 196, 89, 90, 97, 152,
128945 /* 1150 */ 152, 196, 112, 96, 97, 98, 207, 208, 101, 89,
128946 /* 1160 */ 90, 196, 23, 97, 233, 26, 96, 97, 98, 172,
128947 /* 1170 */ 173, 101, 152, 196, 152, 19, 20, 23, 22, 152,
128948 /* 1180 */ 26, 152, 152, 27, 28, 97, 152, 152, 152, 132,
128949 /* 1190 */ 133, 134, 135, 136, 38, 152, 152, 152, 152, 232,
128950 /* 1200 */ 197, 214, 132, 133, 134, 135, 136, 198, 150, 210,
128951 /* 1210 */ 210, 210, 201, 57, 238, 176, 214, 201, 180, 238,
128952 /* 1220 */ 214, 184, 175, 19, 20, 69, 22, 175, 175, 198,
128953 /* 1230 */ 226, 27, 28, 200, 155, 39, 242, 122, 41, 159,
128954 /* 1240 */ 159, 159, 38, 22, 239, 89, 90, 91, 220, 239,
128955 /* 1250 */ 71, 189, 96, 97, 98, 130, 201, 101, 18, 192,
128956 /* 1260 */ 159, 57, 18, 192, 192, 192, 158, 189, 220, 159,
128957 /* 1270 */ 201, 158, 189, 69, 137, 201, 235, 19, 20, 46,
128958 /* 1280 */ 22, 159, 159, 234, 158, 27, 28, 22, 132, 133,
128959 /* 1290 */ 134, 135, 136, 89, 90, 177, 38, 159, 158, 158,
128960 /* 1300 */ 96, 97, 98, 159, 177, 101, 107, 174, 174, 174,
128961 /* 1310 */ 48, 182, 106, 177, 182, 57, 174, 125, 216, 176,
128962 /* 1320 */ 174, 174, 174, 107, 215, 159, 215, 69, 216, 159,
128963 /* 1330 */ 216, 215, 137, 216, 215, 177, 132, 133, 134, 135,
128964 /* 1340 */ 136, 95, 177, 129, 126, 225, 127, 89, 90, 228,
128965 /* 1350 */ 205, 128, 228, 204, 96, 97, 98, 25, 203, 101,
128966 /* 1360 */ 5, 202, 201, 162, 26, 10, 11, 12, 13, 14,
128967 /* 1370 */ 161, 13, 17, 153, 6, 153, 151, 151, 151, 151,
128968 /* 1380 */ 165, 178, 165, 178, 4, 3, 22, 32, 15, 34,
128969 /* 1390 */ 132, 133, 134, 135, 136, 245, 165, 142, 43, 248,
128970 /* 1400 */ 248, 68, 16, 120, 23, 131, 23, 111, 123, 20,
128971 /* 1410 */ 16, 56, 125, 1, 123, 131, 79, 111, 63, 79,
128972 /* 1420 */ 28, 66, 67, 36, 122, 1, 5, 22, 107, 140,
128973 /* 1430 */ 54, 54, 26, 61, 44, 107, 20, 24, 19, 112,
128974 /* 1440 */ 105, 53, 22, 40, 22, 22, 53, 30, 23, 22,
128975 /* 1450 */ 22, 53, 23, 23, 23, 116, 22, 11, 23, 22,
128976 /* 1460 */ 28, 23, 26, 122, 23, 22, 124, 122, 26, 114,
128977 /* 1470 */ 26, 23, 23, 23, 22, 36, 36, 26, 23, 23,
128978 /* 1480 */ 22, 36, 122, 24, 23, 22, 26, 22, 24, 23,
128979 /* 1490 */ 23, 122, 23, 22, 15, 23, 141, 122, 1,
128980 };
128981 #define YY_SHIFT_USE_DFLT (-72)
 
128982 #define YY_SHIFT_COUNT (439)
128983 #define YY_SHIFT_MIN (-71)
128984 #define YY_SHIFT_MAX (1497)
128985 static const short yy_shift_ofst[] = {
128986 /* 0 */ 5, 1057, 1355, 1070, 1204, 1204, 1204, 138, -19, 58,
128987 /* 10 */ 58, 186, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 67,
128988 /* 20 */ 67, 90, 132, 336, 76, 135, 263, 340, 417, 494,
128989 /* 30 */ 571, 622, 699, 776, 827, 827, 827, 827, 827, 827,
128990 /* 40 */ 827, 827, 827, 827, 827, 827, 827, 827, 827, 878,
128991 /* 50 */ 827, 929, 980, 980, 1156, 1204, 1204, 1204, 1204, 1204,
128992 /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
128993 /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
128994 /* 80 */ 1204, 1204, 1204, 1258, 1204, 1204, 1204, 1204, 1204, 1204,
128995 /* 90 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, -71, -47, -47,
128996 /* 100 */ -47, -47, -47, -6, 88, -66, 23, 458, 505, 468,
128997 /* 110 */ 468, 23, 201, 343, -58, -72, -72, -72, 11, 11,
128998 /* 120 */ 11, 412, 412, 341, 537, 605, 23, 23, 23, 23,
128999 /* 130 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
129000 /* 140 */ 23, 23, 23, 23, 23, 23, 635, 298, 74, 74,
129001 /* 150 */ 343, -1, -1, -1, -1, -1, -1, -72, -72, -72,
129002 /* 160 */ 228, 101, 101, 203, 75, 71, 273, 284, 345, 23,
129003 /* 170 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
129004 /* 180 */ 23, 23, 23, 23, 23, 23, 421, 421, 421, 23,
129005 /* 190 */ 23, 582, 23, 23, 23, 356, 23, 23, 585, 23,
129006 /* 200 */ 23, 23, 23, 23, 23, 23, 23, 23, 23, 568,
129007 /* 210 */ 575, 456, 456, 456, 704, 171, 645, 674, 858, 590,
129008 /* 220 */ 590, 914, 858, 914, 370, 963, 886, 948, 590, 425,
129009 /* 230 */ 948, 948, 864, 641, 527, 1196, 1115, 1115, 1197, 1197,
129010 /* 240 */ 1115, 1221, 1179, 1125, 1240, 1240, 1240, 1240, 1115, 1244,
129011 /* 250 */ 1125, 1221, 1179, 1179, 1125, 1115, 1244, 1137, 1233, 1115,
129012 /* 260 */ 1115, 1244, 1265, 1115, 1244, 1115, 1244, 1265, 1199, 1199,
129013 /* 270 */ 1199, 1262, 1265, 1199, 1206, 1199, 1262, 1199, 1199, 1192,
129014 /* 280 */ 1216, 1192, 1216, 1192, 1216, 1192, 1216, 1115, 1115, 1195,
129015 /* 290 */ 1265, 1246, 1246, 1265, 1214, 1218, 1223, 1219, 1125, 1332,
129016 /* 300 */ 1338, 1358, 1358, 1368, 1368, 1368, 1368, -72, -72, -72,
129017 /* 310 */ -72, -72, -72, -72, -72, 400, 623, 742, 816, 658,
129018 /* 320 */ 697, 227, 1012, 664, 1013, 1014, 1018, 1026, 1051, 891,
129019 /* 330 */ 1021, 1040, 1068, 1084, 1066, 1139, 910, 954, 1154, 1088,
129020 /* 340 */ 978, 1380, 1382, 1364, 1255, 1373, 1333, 1386, 1381, 1383,
129021 /* 350 */ 1283, 1274, 1296, 1285, 1389, 1287, 1394, 1412, 1291, 1284,
129022 /* 360 */ 1337, 1340, 1306, 1392, 1387, 1302, 1424, 1421, 1405, 1321,
129023 /* 370 */ 1289, 1376, 1406, 1377, 1372, 1390, 1328, 1413, 1416, 1419,
129024 /* 380 */ 1327, 1335, 1420, 1388, 1422, 1423, 1425, 1427, 1393, 1417,
129025 /* 390 */ 1428, 1398, 1403, 1429, 1430, 1431, 1339, 1434, 1435, 1437,
129026 /* 400 */ 1436, 1341, 1438, 1441, 1432, 1439, 1443, 1342, 1442, 1440,
129027 /* 410 */ 1444, 1445, 1442, 1448, 1449, 1450, 1451, 1455, 1452, 1446,
129028 /* 420 */ 1456, 1458, 1459, 1460, 1461, 1463, 1464, 1460, 1466, 1465,
129029 /* 430 */ 1467, 1469, 1471, 1345, 1360, 1369, 1375, 1472, 1479, 1497,
129030 };
129031 #define YY_REDUCE_USE_DFLT (-144)
129032 #define YY_REDUCE_COUNT (314)
129033 #define YY_REDUCE_MIN (-143)
129034 #define YY_REDUCE_MAX (1231)
129035 static const short yy_reduce_ofst[] = {
129036 /* 0 */ -143, 949, 136, 131, -48, -45, 158, 241, 22, 153,
129037 /* 10 */ 226, 163, 362, 364, 366, 312, 314, 368, 237, 236,
129038 /* 20 */ 300, 440, 114, 359, 319, 100, 100, 100, 100, 100,
129039 /* 30 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
129040 /* 40 */ 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
129041 /* 50 */ 100, 100, 100, 100, 374, 447, 461, 516, 518, 567,
129042 /* 60 */ 569, 572, 574, 579, 581, 583, 586, 596, 631, 644,
129043 /* 70 */ 646, 649, 657, 659, 661, 663, 671, 708, 720, 722,
129044 /* 80 */ 759, 771, 773, 810, 822, 824, 861, 873, 875, 930,
129045 /* 90 */ 944, 947, 952, 957, 959, 961, 997, 100, 100, 100,
129046 /* 100 */ 100, 100, 100, 100, 100, 100, 486, -108, -83, 224,
129047 /* 110 */ 286, 451, 100, 681, 100, 100, 100, 100, 354, 354,
129048 /* 120 */ 354, 337, 352, 49, 482, 482, 503, 532, -60, 615,
129049 /* 130 */ 647, 689, 690, 737, 782, -62, 517, 789, 474, 795,
129050 /* 140 */ 580, 733, 32, 662, 488, 139, 678, 433, 769, 772,
129051 /* 150 */ 396, 728, 887, 942, 955, 965, 977, 740, 766, 178,
129052 /* 160 */ -46, -17, 59, 53, 118, 141, 167, 248, 255, 326,
129053 /* 170 */ 441, 464, 519, 668, 693, 721, 736, 744, 775, 788,
129054 /* 180 */ 846, 899, 912, 936, 983, 985, 72, 134, 542, 990,
129055 /* 190 */ 991, 597, 992, 998, 1020, 871, 1022, 1027, 915, 1029,
129056 /* 200 */ 1030, 1034, 118, 1035, 1036, 1043, 1044, 1045, 1046, 931,
129057 /* 210 */ 967, 999, 1000, 1001, 597, 1003, 1009, 1058, 1011, 987,
129058 /* 220 */ 1002, 976, 1016, 981, 1039, 1037, 1038, 1047, 1006, 1004,
129059 /* 230 */ 1052, 1053, 1033, 1031, 1079, 994, 1080, 1081, 1005, 1010,
129060 /* 240 */ 1082, 1028, 1062, 1055, 1067, 1071, 1072, 1073, 1101, 1108,
129061 /* 250 */ 1069, 1048, 1078, 1083, 1074, 1110, 1113, 1041, 1049, 1122,
129062 /* 260 */ 1123, 1126, 1118, 1138, 1140, 1144, 1141, 1127, 1133, 1134,
129063 /* 270 */ 1135, 1129, 1136, 1142, 1143, 1146, 1132, 1147, 1148, 1102,
129064 /* 280 */ 1109, 1112, 1111, 1114, 1116, 1117, 1119, 1166, 1170, 1120,
129065 /* 290 */ 1158, 1121, 1124, 1165, 1145, 1149, 1155, 1159, 1161, 1201,
129066 /* 300 */ 1209, 1220, 1222, 1225, 1226, 1227, 1228, 1151, 1152, 1150,
129067 /* 310 */ 1215, 1217, 1203, 1205, 1231,
129068 };
129069 static const YYACTIONTYPE yy_default[] = {
129070 /* 0 */ 1250, 1240, 1240, 1240, 1174, 1174, 1174, 1240, 1071, 1100,
129071 /* 10 */ 1100, 1224, 1301, 1301, 1301, 1301, 1301, 1301, 1173, 1301,
129072 /* 20 */ 1301, 1301, 1301, 1240, 1075, 1106, 1301, 1301, 1301, 1301,
@@ -129130,78 +131547,104 @@
129130 */
129131 #ifdef YYFALLBACK
129132 static const YYCODETYPE yyFallback[] = {
129133 0, /* $ => nothing */
129134 0, /* SEMI => nothing */
129135 27, /* EXPLAIN => ID */
129136 27, /* QUERY => ID */
129137 27, /* PLAN => ID */
129138 27, /* BEGIN => ID */
129139 0, /* TRANSACTION => nothing */
129140 27, /* DEFERRED => ID */
129141 27, /* IMMEDIATE => ID */
129142 27, /* EXCLUSIVE => ID */
129143 0, /* COMMIT => nothing */
129144 27, /* END => ID */
129145 27, /* ROLLBACK => ID */
129146 27, /* SAVEPOINT => ID */
129147 27, /* RELEASE => ID */
129148 0, /* TO => nothing */
129149 0, /* TABLE => nothing */
129150 0, /* CREATE => nothing */
129151 27, /* IF => ID */
129152 0, /* NOT => nothing */
129153 0, /* EXISTS => nothing */
129154 27, /* TEMP => ID */
129155 0, /* LP => nothing */
129156 0, /* RP => nothing */
129157 0, /* AS => nothing */
129158 27, /* WITHOUT => ID */
129159 0, /* COMMA => nothing */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129160 0, /* ID => nothing */
129161 0, /* INDEXED => nothing */
129162 27, /* ABORT => ID */
129163 27, /* ACTION => ID */
129164 27, /* AFTER => ID */
129165 27, /* ANALYZE => ID */
129166 27, /* ASC => ID */
129167 27, /* ATTACH => ID */
129168 27, /* BEFORE => ID */
129169 27, /* BY => ID */
129170 27, /* CASCADE => ID */
129171 27, /* CAST => ID */
129172 27, /* COLUMNKW => ID */
129173 27, /* CONFLICT => ID */
129174 27, /* DATABASE => ID */
129175 27, /* DESC => ID */
129176 27, /* DETACH => ID */
129177 27, /* EACH => ID */
129178 27, /* FAIL => ID */
129179 27, /* FOR => ID */
129180 27, /* IGNORE => ID */
129181 27, /* INITIALLY => ID */
129182 27, /* INSTEAD => ID */
129183 27, /* LIKE_KW => ID */
129184 27, /* MATCH => ID */
129185 27, /* NO => ID */
129186 27, /* KEY => ID */
129187 27, /* OF => ID */
129188 27, /* OFFSET => ID */
129189 27, /* PRAGMA => ID */
129190 27, /* RAISE => ID */
129191 27, /* RECURSIVE => ID */
129192 27, /* REPLACE => ID */
129193 27, /* RESTRICT => ID */
129194 27, /* ROW => ID */
129195 27, /* TRIGGER => ID */
129196 27, /* VACUUM => ID */
129197 27, /* VIEW => ID */
129198 27, /* VIRTUAL => ID */
129199 27, /* WITH => ID */
129200 27, /* REINDEX => ID */
129201 27, /* RENAME => ID */
129202 27, /* CTIME_KW => ID */
129203 };
129204 #endif /* YYFALLBACK */
129205
129206 /* The following structure represents a single element of the
129207 ** parser's stack. Information stored includes:
@@ -129288,29 +131731,29 @@
129288 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
129289 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
129290 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
129291 "TABLE", "CREATE", "IF", "NOT",
129292 "EXISTS", "TEMP", "LP", "RP",
129293 "AS", "WITHOUT", "COMMA", "ID",
 
 
 
 
 
 
 
129294 "INDEXED", "ABORT", "ACTION", "AFTER",
129295 "ANALYZE", "ASC", "ATTACH", "BEFORE",
129296 "BY", "CASCADE", "CAST", "COLUMNKW",
129297 "CONFLICT", "DATABASE", "DESC", "DETACH",
129298 "EACH", "FAIL", "FOR", "IGNORE",
129299 "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
129300 "NO", "KEY", "OF", "OFFSET",
129301 "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
129302 "RESTRICT", "ROW", "TRIGGER", "VACUUM",
129303 "VIEW", "VIRTUAL", "WITH", "REINDEX",
129304 "RENAME", "CTIME_KW", "ANY", "OR",
129305 "AND", "IS", "BETWEEN", "IN",
129306 "ISNULL", "NOTNULL", "NE", "EQ",
129307 "GT", "LE", "LT", "GE",
129308 "ESCAPE", "BITAND", "BITOR", "LSHIFT",
129309 "RSHIFT", "PLUS", "MINUS", "STAR",
129310 "SLASH", "REM", "CONCAT", "COLLATE",
129311 "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
129312 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
129313 "CHECK", "REFERENCES", "AUTOINCR", "ON",
129314 "INSERT", "DELETE", "UPDATE", "SET",
129315 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
129316 "ALL", "EXCEPT", "INTERSECT", "SELECT",
@@ -131086,26 +133529,27 @@
131086 yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
131087 }
131088 break;
131089 case 156: /* expr ::= VARIABLE */
131090 {
131091 Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
131092 if( t.n>=2 && t.z[0]=='#' && sqlite3Isdigit(t.z[1]) ){
 
 
131093 /* When doing a nested parse, one can include terms in an expression
131094 ** that look like this: #1 #2 ... These terms refer to registers
131095 ** in the virtual machine. #N is the N-th register. */
 
 
131096 spanSet(&yymsp[0].minor.yy342, &t, &t);
131097 if( pParse->nested==0 ){
131098 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
131099 yymsp[0].minor.yy342.pExpr = 0;
131100 }else{
131101 yymsp[0].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
131102 if( yymsp[0].minor.yy342.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy342.pExpr->iTable);
131103 }
131104 }else{
131105 spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, t);
131106 sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
131107 }
131108 }
131109 break;
131110 case 157: /* expr ::= expr COLLATE ID|STRING */
131111 {
@@ -131286,60 +133730,37 @@
131286 break;
131287 case 188: /* expr ::= LP select RP */
131288 {
131289 spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
131290 yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
131291 if( yymsp[-2].minor.yy342.pExpr ){
131292 yymsp[-2].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
131293 ExprSetProperty(yymsp[-2].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131294 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-2].minor.yy342.pExpr);
131295 }else{
131296 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131297 }
131298 }
131299 break;
131300 case 189: /* expr ::= expr in_op LP select RP */
131301 {
131302 yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
131303 if( yymsp[-4].minor.yy342.pExpr ){
131304 yymsp[-4].minor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
131305 ExprSetProperty(yymsp[-4].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131306 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
131307 }else{
131308 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131309 }
131310 exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
131311 yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
131312 }
131313 break;
131314 case 190: /* expr ::= expr in_op nm dbnm */
131315 {
131316 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
 
131317 yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
131318 if( yymsp[-3].minor.yy342.pExpr ){
131319 yymsp[-3].minor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
131320 ExprSetProperty(yymsp[-3].minor.yy342.pExpr, EP_xIsSelect|EP_Subquery);
131321 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-3].minor.yy342.pExpr);
131322 }else{
131323 sqlite3SrcListDelete(pParse->db, pSrc);
131324 }
131325 exprNot(pParse, yymsp[-2].minor.yy392, &yymsp[-3].minor.yy342);
131326 yymsp[-3].minor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
131327 }
131328 break;
131329 case 191: /* expr ::= EXISTS LP select RP */
131330 {
131331 Expr *p;
131332 spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
131333 p = yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
131334 if( p ){
131335 p->x.pSelect = yymsp[-1].minor.yy159;
131336 ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
131337 sqlite3ExprSetHeightAndFlags(pParse, p);
131338 }else{
131339 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
131340 }
131341 }
131342 break;
131343 case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
131344 {
131345 spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
@@ -132820,11 +135241,11 @@
132820 ** will take responsibility for freeing the Table structure.
132821 */
132822 sqlite3DeleteTable(db, pParse->pNewTable);
132823 }
132824
132825 sqlite3WithDelete(db, pParse->pWithToFree);
132826 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
132827 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
132828 sqlite3DbFree(db, pParse->azVar);
132829 while( pParse->pAinc ){
132830 AutoincInfo *p = pParse->pAinc;
@@ -134030,10 +136451,11 @@
134030 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
134031 } aFlagOp[] = {
134032 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
134033 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
134034 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
 
134035 };
134036 unsigned int i;
134037 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
134038 for(i=0; i<ArraySize(aFlagOp); i++){
134039 if( aFlagOp[i].op==op ){
@@ -135148,10 +137570,31 @@
135148 db->pRollbackArg = pArg;
135149 sqlite3_mutex_leave(db->mutex);
135150 return pRet;
135151 }
135152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135153 #ifndef SQLITE_OMIT_WAL
135154 /*
135155 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
135156 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
135157 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
@@ -160507,19 +162950,21 @@
160507 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
160508 **
160509 ** http://www.icu-project.org/userguide/posix.html#case_mappings
160510 */
160511 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
160512 const UChar *zInput;
160513 UChar *zOutput = 0;
160514 int nInput;
160515 int nOut;
160516 int cnt;
 
160517 UErrorCode status;
160518 const char *zLocale = 0;
160519
160520 assert(nArg==1 || nArg==2);
 
160521 if( nArg==2 ){
160522 zLocale = (const char *)sqlite3_value_text(apArg[1]);
160523 }
160524
160525 zInput = sqlite3_value_text16(apArg[0]);
@@ -160539,23 +162984,27 @@
160539 sqlite3_result_error_nomem(p);
160540 return;
160541 }
160542 zOutput = zNew;
160543 status = U_ZERO_ERROR;
160544 if( sqlite3_user_data(p) ){
160545 nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
160546 }else{
160547 nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
160548 }
160549 if( !U_SUCCESS(status) ){
160550 if( status==U_BUFFER_OVERFLOW_ERROR ) continue;
160551 icuFunctionError(p,
160552 sqlite3_user_data(p) ? "u_strToUpper" : "u_strToLower", status);
160553 return;
160554 }
160555 }
160556 sqlite3_result_text16(p, zOutput, nOut, xFree);
 
 
 
 
160557 }
160558
160559 /*
160560 ** Collation sequence destructor function. The pCtx argument points to
160561 ** a UCollator structure previously allocated using ucol_open().
@@ -161368,10 +163817,42 @@
161368 const char *zTarget,
161369 const char *zRbu,
161370 const char *zState
161371 );
161372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161373 /*
161374 ** Internally, each RBU connection uses a separate SQLite database
161375 ** connection to access the target and rbu update databases. This
161376 ** API allows the application direct access to these database handles.
161377 **
@@ -161646,10 +164127,11 @@
161646 typedef struct rbu_file rbu_file;
161647 typedef struct RbuUpdateStmt RbuUpdateStmt;
161648
161649 #if !defined(SQLITE_AMALGAMATION)
161650 typedef unsigned int u32;
 
161651 typedef unsigned char u8;
161652 typedef sqlite3_int64 i64;
161653 #endif
161654
161655 /*
@@ -161658,10 +164140,12 @@
161658 ** format.
161659 */
161660 #define WAL_LOCK_WRITE 0
161661 #define WAL_LOCK_CKPT 1
161662 #define WAL_LOCK_READ0 3
 
 
161663
161664 /*
161665 ** A structure to store values read from the rbu_state table in memory.
161666 */
161667 struct RbuState {
@@ -161837,10 +164321,14 @@
161837 int nFrameAlloc; /* Allocated size of aFrame[] array */
161838 RbuFrame *aFrame;
161839 int pgsz;
161840 u8 *aBuf;
161841 i64 iWalCksum;
 
 
 
 
161842 };
161843
161844 /*
161845 ** An rbu VFS is implemented using an instance of this structure.
161846 */
@@ -161862,10 +164350,11 @@
161862 sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
161863
161864 int openFlags; /* Flags this file was opened with */
161865 u32 iCookie; /* Cookie value for main db files */
161866 u8 iWriteVer; /* "write-version" value for main db files */
 
161867
161868 int nShm; /* Number of entries in apShm[] array */
161869 char **apShm; /* Array of mmap'd *-shm regions */
161870 char *zDel; /* Delete this when closing file */
161871
@@ -161872,10 +164361,15 @@
161872 const char *zWal; /* Wal filename for this main db file */
161873 rbu_file *pWalFd; /* Wal file descriptor for this main db */
161874 rbu_file *pMainNext; /* Next MAIN_DB file */
161875 };
161876
 
 
 
 
 
161877
161878 /*************************************************************************
161879 ** The following three functions, found below:
161880 **
161881 ** rbuDeltaGetInt()
@@ -162320,12 +164814,15 @@
162320 }
162321
162322
162323 /*
162324 ** The implementation of the rbu_target_name() SQL function. This function
162325 ** accepts one argument - the name of a table in the RBU database. If the
162326 ** table name matches the pattern:
 
 
 
162327 **
162328 ** data[0-9]_<name>
162329 **
162330 ** where <name> is any sequence of 1 or more characters, <name> is returned.
162331 ** Otherwise, if the only argument does not match the above pattern, an SQL
@@ -162332,25 +164829,37 @@
162332 ** NULL is returned.
162333 **
162334 ** "data_t1" -> "t1"
162335 ** "data0123_t2" -> "t2"
162336 ** "dataAB_t3" -> NULL
 
 
 
162337 */
162338 static void rbuTargetNameFunc(
162339 sqlite3_context *context,
162340 int argc,
162341 sqlite3_value **argv
162342 ){
 
162343 const char *zIn;
162344 assert( argc==1 );
162345
162346 zIn = (const char*)sqlite3_value_text(argv[0]);
162347 if( zIn && strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
162348 int i;
162349 for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
162350 if( zIn[i]=='_' && zIn[i+1] ){
162351 sqlite3_result_text(context, &zIn[i+1], -1, SQLITE_STATIC);
 
 
 
 
 
 
 
 
162352 }
162353 }
162354 }
162355
162356 /*
@@ -162364,11 +164873,12 @@
162364 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
162365 int rc;
162366 memset(pIter, 0, sizeof(RbuObjIter));
162367
162368 rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
162369 "SELECT rbu_target_name(name) AS target, name FROM sqlite_master "
 
162370 "WHERE type IN ('table', 'view') AND target IS NOT NULL "
162371 "ORDER BY name"
162372 );
162373
162374 if( rc==SQLITE_OK ){
@@ -162740,10 +165250,11 @@
162740 }
162741 sqlite3_finalize(pStmt);
162742 pStmt = 0;
162743
162744 if( p->rc==SQLITE_OK
 
162745 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
162746 ){
162747 p->rc = SQLITE_ERROR;
162748 p->zErrmsg = sqlite3_mprintf(
162749 "table %q %s rbu_rowid column", pIter->zDataTbl,
@@ -162879,10 +165390,12 @@
162879 if( pIter->eType==RBU_PK_IPK ){
162880 int i;
162881 for(i=0; pIter->abTblPk[i]==0; i++);
162882 assert( i<pIter->nTblCol );
162883 zCol = pIter->azTblCol[i];
 
 
162884 }else{
162885 zCol = "rbu_rowid";
162886 }
162887 zType = "INTEGER";
162888 }else{
@@ -163419,20 +165932,29 @@
163419 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
163420 );
163421 }
163422
163423 /* And to delete index entries */
163424 if( p->rc==SQLITE_OK ){
163425 p->rc = prepareFreeAndCollectError(
163426 p->dbMain, &pIter->pDelete, &p->zErrmsg,
163427 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
163428 );
163429 }
163430
163431 /* Create the SELECT statement to read keys in sorted order */
163432 if( p->rc==SQLITE_OK ){
163433 char *zSql;
 
 
 
 
 
 
 
 
 
163434 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
163435 zSql = sqlite3_mprintf(
163436 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
163437 zCollist, p->zStateDb, pIter->zDataTbl,
163438 zCollist, zLimit
@@ -163455,11 +165977,13 @@
163455 sqlite3_free(zImposterCols);
163456 sqlite3_free(zImposterPK);
163457 sqlite3_free(zWhere);
163458 sqlite3_free(zBind);
163459 }else{
163460 int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
 
 
163461 const char *zTbl = pIter->zTbl; /* Table this step applies to */
163462 const char *zWrite; /* Imposter table name */
163463
163464 char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
163465 char *zWhere = rbuObjIterGetWhere(p, pIter);
@@ -163482,20 +166006,22 @@
163482 zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
163483 )
163484 );
163485 }
163486
163487 /* Create the DELETE statement to write to the target PK b-tree */
163488 if( p->rc==SQLITE_OK ){
 
 
163489 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
163490 sqlite3_mprintf(
163491 "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
163492 )
163493 );
163494 }
163495
163496 if( pIter->abIndexed ){
163497 const char *zRbuRowid = "";
163498 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
163499 zRbuRowid = ", rbu_rowid";
163500 }
163501
@@ -163541,14 +166067,20 @@
163541 rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
163542 }
163543
163544 /* Create the SELECT statement to read keys from data_xxx */
163545 if( p->rc==SQLITE_OK ){
 
 
 
 
163546 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
163547 sqlite3_mprintf(
163548 "SELECT %s, rbu_control%s FROM '%q'%s",
163549 zCollist, (bRbuRowid ? ", rbu_rowid" : ""),
 
 
163550 pIter->zDataTbl, zLimit
163551 )
163552 );
163553 }
163554
@@ -163639,44 +166171,231 @@
163639 }
163640
163641 return p->rc;
163642 }
163643
163644 static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
 
 
 
 
163645 sqlite3 *db = 0;
163646 if( p->rc==SQLITE_OK ){
163647 const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
163648 p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
163649 if( p->rc ){
163650 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163651 sqlite3_close(db);
163652 db = 0;
163653 }
163654 }
163655 return db;
163656 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163657
163658 /*
163659 ** Open the database handle and attach the RBU database as "rbu". If an
163660 ** error occurs, leave an error code and message in the RBU handle.
163661 */
163662 static void rbuOpenDatabase(sqlite3rbu *p){
163663 assert( p->rc==SQLITE_OK );
163664 assert( p->dbMain==0 && p->dbRbu==0 );
 
163665
163666 p->eStage = 0;
163667 p->dbMain = rbuOpenDbhandle(p, p->zTarget);
163668 p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
 
 
 
163669
163670 /* If using separate RBU and state databases, attach the state database to
163671 ** the RBU db handle now. */
163672 if( p->zState ){
163673 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
163674 memcpy(p->zStateDb, "stat", 4);
163675 }else{
163676 memcpy(p->zStateDb, "main", 4);
163677 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163678
163679 if( p->rc==SQLITE_OK ){
163680 p->rc = sqlite3_create_function(p->dbMain,
163681 "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
163682 );
@@ -163688,11 +166407,11 @@
163688 );
163689 }
163690
163691 if( p->rc==SQLITE_OK ){
163692 p->rc = sqlite3_create_function(p->dbRbu,
163693 "rbu_target_name", 1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
163694 );
163695 }
163696
163697 if( p->rc==SQLITE_OK ){
163698 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
@@ -163947,13 +166666,19 @@
163947 ** If an error occurs, leave an error code and error message in the rbu
163948 ** handle.
163949 */
163950 static void rbuMoveOalFile(sqlite3rbu *p){
163951 const char *zBase = sqlite3_db_filename(p->dbMain, "main");
 
 
 
163952
163953 char *zWal = sqlite3_mprintf("%s-wal", zBase);
163954 char *zOal = sqlite3_mprintf("%s-oal", zBase);
 
 
 
163955
163956 assert( p->eStage==RBU_STAGE_MOVE );
163957 assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
163958 if( zWal==0 || zOal==0 ){
163959 p->rc = SQLITE_NOMEM;
@@ -163970,12 +166695,12 @@
163970 rbuFileSuffix3(zBase, zWal);
163971 rbuFileSuffix3(zBase, zOal);
163972
163973 /* Re-open the databases. */
163974 rbuObjIterFinalize(&p->objiter);
163975 sqlite3_close(p->dbMain);
163976 sqlite3_close(p->dbRbu);
 
163977 p->dbMain = 0;
163978 p->dbRbu = 0;
163979
163980 #if defined(_WIN32_WCE)
163981 {
@@ -164133,23 +166858,28 @@
164133
164134 pVal = sqlite3_column_value(pIter->pSelect, i);
164135 p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
164136 if( p->rc ) return;
164137 }
164138 if( pIter->zIdx==0
164139 && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
164140 ){
164141 /* For a virtual table, or a table with no primary key, the
164142 ** SELECT statement is:
164143 **
164144 ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
164145 **
164146 ** Hence column_value(pIter->nCol+1).
164147 */
164148 assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
164149 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
164150 p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
 
 
 
 
 
164151 }
164152 if( p->rc==SQLITE_OK ){
164153 sqlite3_step(pWriter);
164154 p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
164155 }
@@ -164224,17 +166954,22 @@
164224 return p->rc;
164225 }
164226
164227 /*
164228 ** Increment the schema cookie of the main database opened by p->dbMain.
 
 
 
 
164229 */
164230 static void rbuIncrSchemaCookie(sqlite3rbu *p){
164231 if( p->rc==SQLITE_OK ){
 
164232 int iCookie = 1000000;
164233 sqlite3_stmt *pStmt;
164234
164235 p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
164236 "PRAGMA schema_version"
164237 );
164238 if( p->rc==SQLITE_OK ){
164239 /* Coverage: it may be that this sqlite3_step() cannot fail. There
164240 ** is already a transaction open, so the prepared statement cannot
@@ -164258,10 +166993,11 @@
164258 ** are determined by inspecting the rbu handle passed as the first argument.
164259 */
164260 static void rbuSaveState(sqlite3rbu *p, int eStage){
164261 if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
164262 sqlite3_stmt *pInsert = 0;
 
164263 int rc;
164264
164265 assert( p->zErrmsg==0 );
164266 rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
164267 sqlite3_mprintf(
@@ -164280,11 +167016,11 @@
164280 RBU_STATE_TBL, p->objiter.zTbl,
164281 RBU_STATE_IDX, p->objiter.zIdx,
164282 RBU_STATE_ROW, p->nStep,
164283 RBU_STATE_PROGRESS, p->nProgress,
164284 RBU_STATE_CKPT, p->iWalCksum,
164285 RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
164286 RBU_STATE_OALSZ, p->iOalSz,
164287 RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
164288 )
164289 );
164290 assert( pInsert==0 || rc==SQLITE_OK );
@@ -164295,26 +167031,121 @@
164295 }
164296 if( rc!=SQLITE_OK ) p->rc = rc;
164297 }
164298 }
164299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164300
164301 /*
164302 ** Step the RBU object.
164303 */
164304 SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
164305 if( p ){
164306 switch( p->eStage ){
164307 case RBU_STAGE_OAL: {
164308 RbuObjIter *pIter = &p->objiter;
 
 
 
 
 
 
 
 
 
164309 while( p->rc==SQLITE_OK && pIter->zTbl ){
164310
164311 if( pIter->bCleanup ){
164312 /* Clean up the rbu_tmp_xxx table for the previous table. It
164313 ** cannot be dropped as there are currently active SQL statements.
164314 ** But the contents can be deleted. */
164315 if( pIter->abIndexed ){
164316 rbuMPrintfExec(p, p->dbRbu,
164317 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
164318 );
164319 }
164320 }else{
@@ -164397,98 +167228,10 @@
164397 }else{
164398 return SQLITE_NOMEM;
164399 }
164400 }
164401
164402 /*
164403 ** Free an RbuState object allocated by rbuLoadState().
164404 */
164405 static void rbuFreeState(RbuState *p){
164406 if( p ){
164407 sqlite3_free(p->zTbl);
164408 sqlite3_free(p->zIdx);
164409 sqlite3_free(p);
164410 }
164411 }
164412
164413 /*
164414 ** Allocate an RbuState object and load the contents of the rbu_state
164415 ** table into it. Return a pointer to the new object. It is the
164416 ** responsibility of the caller to eventually free the object using
164417 ** sqlite3_free().
164418 **
164419 ** If an error occurs, leave an error code and message in the rbu handle
164420 ** and return NULL.
164421 */
164422 static RbuState *rbuLoadState(sqlite3rbu *p){
164423 RbuState *pRet = 0;
164424 sqlite3_stmt *pStmt = 0;
164425 int rc;
164426 int rc2;
164427
164428 pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
164429 if( pRet==0 ) return 0;
164430
164431 rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
164432 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
164433 );
164434 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
164435 switch( sqlite3_column_int(pStmt, 0) ){
164436 case RBU_STATE_STAGE:
164437 pRet->eStage = sqlite3_column_int(pStmt, 1);
164438 if( pRet->eStage!=RBU_STAGE_OAL
164439 && pRet->eStage!=RBU_STAGE_MOVE
164440 && pRet->eStage!=RBU_STAGE_CKPT
164441 ){
164442 p->rc = SQLITE_CORRUPT;
164443 }
164444 break;
164445
164446 case RBU_STATE_TBL:
164447 pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
164448 break;
164449
164450 case RBU_STATE_IDX:
164451 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
164452 break;
164453
164454 case RBU_STATE_ROW:
164455 pRet->nRow = sqlite3_column_int(pStmt, 1);
164456 break;
164457
164458 case RBU_STATE_PROGRESS:
164459 pRet->nProgress = sqlite3_column_int64(pStmt, 1);
164460 break;
164461
164462 case RBU_STATE_CKPT:
164463 pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
164464 break;
164465
164466 case RBU_STATE_COOKIE:
164467 pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
164468 break;
164469
164470 case RBU_STATE_OALSZ:
164471 pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
164472 break;
164473
164474 case RBU_STATE_PHASEONESTEP:
164475 pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
164476 break;
164477
164478 default:
164479 rc = SQLITE_CORRUPT;
164480 break;
164481 }
164482 }
164483 rc2 = sqlite3_finalize(pStmt);
164484 if( rc==SQLITE_OK ) rc = rc2;
164485
164486 p->rc = rc;
164487 return pRet;
164488 }
164489
164490 /*
164491 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
164492 ** otherwise. Either or both argument may be NULL. Two NULL values are
164493 ** considered equal, and NULL is considered distinct from all other values.
164494 */
@@ -164674,20 +167417,18 @@
164674 }
164675 }
164676 }
164677 }
164678
164679 /*
164680 ** Open and return a new RBU handle.
164681 */
164682 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
164683 const char *zTarget,
164684 const char *zRbu,
164685 const char *zState
164686 ){
164687 sqlite3rbu *p;
164688 size_t nTarget = strlen(zTarget);
164689 size_t nRbu = strlen(zRbu);
164690 size_t nState = zState ? strlen(zState) : 0;
164691 size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
164692
164693 p = (sqlite3rbu*)sqlite3_malloc64(nByte);
@@ -164696,26 +167437,28 @@
164696
164697 /* Create the custom VFS. */
164698 memset(p, 0, sizeof(sqlite3rbu));
164699 rbuCreateVfs(p);
164700
164701 /* Open the target database */
164702 if( p->rc==SQLITE_OK ){
164703 p->zTarget = (char*)&p[1];
164704 memcpy(p->zTarget, zTarget, nTarget+1);
164705 p->zRbu = &p->zTarget[nTarget+1];
 
 
 
 
164706 memcpy(p->zRbu, zRbu, nRbu+1);
 
164707 if( zState ){
164708 p->zState = &p->zRbu[nRbu+1];
164709 memcpy(p->zState, zState, nState+1);
164710 }
164711 rbuOpenDatabase(p);
164712 }
164713
164714 /* If it has not already been created, create the rbu_state table */
164715 rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
164716
164717 if( p->rc==SQLITE_OK ){
164718 pState = rbuLoadState(p);
164719 assert( pState || p->rc!=SQLITE_OK );
164720 if( p->rc==SQLITE_OK ){
164721
@@ -164741,31 +167484,43 @@
164741 p->eStage = RBU_STAGE_CKPT;
164742 p->nStep = 0;
164743 }
164744 }
164745
164746 if( p->rc==SQLITE_OK
164747 && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
164748 && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
164749 ){
164750 /* At this point (pTargetFd->iCookie) contains the value of the
164751 ** change-counter cookie (the thing that gets incremented when a
164752 ** transaction is committed in rollback mode) currently stored on
164753 ** page 1 of the database file. */
164754 p->rc = SQLITE_BUSY;
164755 p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
 
 
 
 
 
164756 }
164757
164758 if( p->rc==SQLITE_OK ){
164759 if( p->eStage==RBU_STAGE_OAL ){
164760 sqlite3 *db = p->dbMain;
 
 
 
 
 
164761
164762 /* Open transactions both databases. The *-oal file is opened or
164763 ** created at this point. */
164764 p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
 
 
164765 if( p->rc==SQLITE_OK ){
164766 p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
164767 }
164768
164769 /* Check if the main database is a zipvfs db. If it is, set the upper
164770 ** level pager to use "journal_mode=off". This prevents it from
164771 ** generating a large journal using a temp file. */
@@ -164806,10 +167561,32 @@
164806 }
164807
164808 return p;
164809 }
164810
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164811
164812 /*
164813 ** Return the database handle used by pRbu.
164814 */
164815 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
@@ -164826,11 +167603,11 @@
164826 ** then edit any error message string so as to remove all occurrences of
164827 ** the pattern "rbu_imp_[0-9]*".
164828 */
164829 static void rbuEditErrmsg(sqlite3rbu *p){
164830 if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
164831 int i;
164832 size_t nErrmsg = strlen(p->zErrmsg);
164833 for(i=0; i<(nErrmsg-8); i++){
164834 if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
164835 int nDel = 8;
164836 while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
@@ -164859,14 +167636,24 @@
164859 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
164860 }
164861
164862 /* Close any open statement handles. */
164863 rbuObjIterFinalize(&p->objiter);
 
 
 
 
 
 
 
 
 
 
164864
164865 /* Close the open database handle and VFS object. */
164866 sqlite3_close(p->dbMain);
164867 sqlite3_close(p->dbRbu);
 
164868 rbuDeleteVfs(p);
164869 sqlite3_free(p->aBuf);
164870 sqlite3_free(p->aFrame);
164871
164872 rbuEditErrmsg(p);
@@ -165063,10 +167850,26 @@
165063 return ((u32)aBuf[0] << 24)
165064 + ((u32)aBuf[1] << 16)
165065 + ((u32)aBuf[2] << 8)
165066 + ((u32)aBuf[3]);
165067 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165068
165069 /*
165070 ** Read data from an rbuVfs-file.
165071 */
165072 static int rbuVfsRead(
@@ -165089,10 +167892,39 @@
165089 ){
165090 rc = SQLITE_OK;
165091 memset(zBuf, 0, iAmt);
165092 }else{
165093 rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165094 }
165095 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
165096 /* These look like magic numbers. But they are stable, as they are part
165097 ** of the definition of the SQLite file format, which may not change. */
165098 u8 *pBuf = (u8*)zBuf;
@@ -165163,11 +167995,24 @@
165163 /*
165164 ** Return the current file-size of an rbuVfs-file.
165165 */
165166 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
165167 rbu_file *p = (rbu_file *)pFile;
165168 return p->pReal->pMethods->xFileSize(p->pReal, pSize);
 
 
 
 
 
 
 
 
 
 
 
 
 
165169 }
165170
165171 /*
165172 ** Lock an rbuVfs-file.
165173 */
@@ -165175,11 +168020,13 @@
165175 rbu_file *p = (rbu_file*)pFile;
165176 sqlite3rbu *pRbu = p->pRbu;
165177 int rc = SQLITE_OK;
165178
165179 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
165180 if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
 
 
165181 /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
165182 ** prevents it from checkpointing the database from sqlite3_close(). */
165183 rc = SQLITE_BUSY;
165184 }else{
165185 rc = p->pReal->pMethods->xLock(p->pReal, eLock);
@@ -165237,10 +168084,16 @@
165237 if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
165238 rc = SQLITE_OK;
165239 }
165240 }
165241 return rc;
 
 
 
 
 
 
165242 }
165243
165244 rc = xControl(p->pReal, op, pArg);
165245 if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
165246 rbu_vfs *pRbuVfs = p->pRbuVfs;
@@ -165400,10 +168253,37 @@
165400 sqlite3_mutex_enter(pRbuVfs->mutex);
165401 for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
165402 sqlite3_mutex_leave(pRbuVfs->mutex);
165403 return pDb;
165404 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165405
165406 /*
165407 ** Open an rbu file handle.
165408 */
165409 static int rbuVfsOpen(
@@ -165436,10 +168316,11 @@
165436 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
165437 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
165438 rbu_file *pFd = (rbu_file *)pFile;
165439 int rc = SQLITE_OK;
165440 const char *zOpen = zName;
 
165441
165442 memset(pFd, 0, sizeof(rbu_file));
165443 pFd->pReal = (sqlite3_file*)&pFd[1];
165444 pFd->pRbuVfs = pRbuVfs;
165445 pFd->openFlags = flags;
@@ -165448,40 +168329,31 @@
165448 /* A main database has just been opened. The following block sets
165449 ** (pFd->zWal) to point to a buffer owned by SQLite that contains
165450 ** the name of the *-wal file this db connection will use. SQLite
165451 ** happens to pass a pointer to this buffer when using xAccess()
165452 ** or xOpen() to operate on the *-wal file. */
165453 int n = (int)strlen(zName);
165454 const char *z = &zName[n];
165455 if( flags & SQLITE_OPEN_URI ){
165456 int odd = 0;
165457 while( 1 ){
165458 if( z[0]==0 ){
165459 odd = 1 - odd;
165460 if( odd && z[1]==0 ) break;
165461 }
165462 z++;
165463 }
165464 z += 2;
165465 }else{
165466 while( *z==0 ) z++;
165467 }
165468 z += (n + 8 + 1);
165469 pFd->zWal = z;
165470 }
165471 else if( flags & SQLITE_OPEN_WAL ){
165472 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
165473 if( pDb ){
165474 if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
165475 /* This call is to open a *-wal file. Intead, open the *-oal. This
165476 ** code ensures that the string passed to xOpen() is terminated by a
165477 ** pair of '\0' bytes in case the VFS attempts to extract a URI
165478 ** parameter from it. */
165479 size_t nCopy = strlen(zName);
165480 char *zCopy = sqlite3_malloc64(nCopy+2);
 
 
 
 
 
 
 
165481 if( zCopy ){
165482 memcpy(zCopy, zName, nCopy);
165483 zCopy[nCopy-3] = 'o';
165484 zCopy[nCopy] = '\0';
165485 zCopy[nCopy+1] = '\0';
165486 zOpen = (const char*)(pFd->zDel = zCopy);
165487 }else{
@@ -165491,13 +168363,22 @@
165491 }
165492 pDb->pWalFd = pFd;
165493 }
165494 }
165495 }
 
 
 
 
 
 
 
 
 
165496
165497 if( rc==SQLITE_OK ){
165498 rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
165499 }
165500 if( pFd->pReal->pMethods ){
165501 /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
165502 ** pointer and, if the file is a main database file, link it into the
165503 ** mutex protected linked list of all such files. */
@@ -166457,10 +169338,4654 @@
166457 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
166458 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
166459 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
166460
166461 /************** End of dbstat.c **********************************************/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166462 /************** Begin file json1.c *******************************************/
166463 /*
166464 ** 2015-08-12
166465 **
166466 ** The author disclaims copyright to this source code. In place of
@@ -168809,15 +176334,17 @@
168809 ** of the current query. Specifically, a query equivalent to:
168810 **
168811 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
168812 **
168813 ** with $p set to a phrase equivalent to the phrase iPhrase of the
168814 ** current query is executed. For each row visited, the callback function
168815 ** passed as the fourth argument is invoked. The context and API objects
168816 ** passed to the callback function may be used to access the properties of
168817 ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
168818 ** passed as the third argument to pUserData.
 
 
168819 **
168820 ** If the callback function returns any value other than SQLITE_OK, the
168821 ** query is abandoned and the xQueryPhrase function returns immediately.
168822 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
168823 ** Otherwise, the error code is propagated upwards.
@@ -174848,10 +182375,21 @@
174848 }
174849 if( rc==SQLITE_OK ){
174850 pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
174851 sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
174852 }
 
 
 
 
 
 
 
 
 
 
 
174853
174854 for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
174855 int tflags = 0;
174856 Fts5ExprTerm *p;
174857 for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
@@ -176196,15 +183734,15 @@
176196 assert( iCol>=p->iCol );
176197 if( iCol!=p->iCol ){
176198 if( pHash->eDetail==FTS5_DETAIL_FULL ){
176199 pPtr[p->nData++] = 0x01;
176200 p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
176201 p->iCol = iCol;
176202 p->iPos = 0;
176203 }else{
176204 bNew = 1;
176205 p->iCol = iPos = iCol;
176206 }
176207 }
176208
176209 /* Append the new position offset, if necessary */
176210 if( bNew ){
@@ -179623,11 +187161,11 @@
179623 while( *aiCol<iPrev ){
179624 aiCol++;
179625 if( aiCol==aiColEnd ) goto setoutputs_col_out;
179626 }
179627 if( *aiCol==iPrev ){
179628 *aOut++ = (iPrev - iPrevOut) + 2;
179629 iPrevOut = iPrev;
179630 }
179631 }
179632
179633 setoutputs_col_out:
@@ -185456,11 +192994,11 @@
185456 int nArg, /* Number of args */
185457 sqlite3_value **apUnused /* Function arguments */
185458 ){
185459 assert( nArg==0 );
185460 UNUSED_PARAM2(nArg, apUnused);
185461 sqlite3_result_text(pCtx, "fts5: 2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d", -1, SQLITE_TRANSIENT);
185462 }
185463
185464 static int fts5Init(sqlite3 *db){
185465 static const sqlite3_module fts5Mod = {
185466 /* iVersion */ 2,
185467
--- src/sqlite3.c
+++ src/sqlite3.c
@@ -1,8 +1,8 @@
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.13.0. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
@@ -37,10 +37,37 @@
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef _SQLITEINT_H_
41 #define _SQLITEINT_H_
42
43 /* Special Comments:
44 **
45 ** Some comments have special meaning to the tools that measure test
46 ** coverage:
47 **
48 ** NO_TEST - The branches on this line are not
49 ** measured by branch coverage. This is
50 ** used on lines of code that actually
51 ** implement parts of coverage testing.
52 **
53 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
54 ** and the correct answer is still obtained,
55 ** though perhaps more slowly.
56 **
57 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
58 ** and the correct answer is still obtained,
59 ** though perhaps more slowly.
60 **
61 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
62 ** that would be harmless and undetectable
63 ** if it did occur.
64 **
65 ** In all cases, the special comment must be enclosed in the usual
66 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67 ** asterisks and the comment text.
68 */
69
70 /*
71 ** Make sure that rand_s() is available on Windows systems with MSVC 2005
72 ** or higher.
73 */
@@ -334,13 +361,13 @@
361 **
362 ** See also: [sqlite3_libversion()],
363 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
364 ** [sqlite_version()] and [sqlite_source_id()].
365 */
366 #define SQLITE_VERSION "3.13.0"
367 #define SQLITE_VERSION_NUMBER 3013000
368 #define SQLITE_SOURCE_ID "2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2"
369
370 /*
371 ** CAPI3REF: Run-Time Library Version Numbers
372 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
373 **
@@ -2155,16 +2182,34 @@
2182 ** The second parameter is a pointer to an integer into which
2183 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2184 ** following this call. The second parameter may be a NULL pointer, in
2185 ** which case the new setting is not reported back. </dd>
2186 **
2187 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2188 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2189 ** interface independently of the [load_extension()] SQL function.
2190 ** The [sqlite3_enable_load_extension()] API enables or disables both the
2191 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2192 ** There should be two additional arguments.
2193 ** When the first argument to this interface is 1, then only the C-API is
2194 ** enabled and the SQL function remains disabled. If the first argment to
2195 ** this interface is 0, then both the C-API and the SQL function are disabled.
2196 ** If the first argument is -1, then no changes are made to state of either the
2197 ** C-API or the SQL function.
2198 ** The second parameter is a pointer to an integer into which
2199 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2200 ** is disabled or enabled following this call. The second parameter may
2201 ** be a NULL pointer, in which case the new setting is not reported back.
2202 ** </dd>
2203 **
2204 ** </dl>
2205 */
2206 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2207 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2208 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2209 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2210 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2211
2212
2213 /*
2214 ** CAPI3REF: Enable Or Disable Extended Result Codes
2215 ** METHOD: sqlite3
@@ -5410,11 +5455,11 @@
5455 ** METHOD: sqlite3
5456 **
5457 ** ^The sqlite3_update_hook() interface registers a callback function
5458 ** with the [database connection] identified by the first argument
5459 ** to be invoked whenever a row is updated, inserted or deleted in
5460 ** a [rowid table].
5461 ** ^Any callback set by a previous call to this function
5462 ** for the same database connection is overridden.
5463 **
5464 ** ^The second argument is a pointer to the function to invoke when a
5465 ** row is updated, inserted or deleted in a rowid table.
@@ -5449,12 +5494,12 @@
5494 ** ^The sqlite3_update_hook(D,C,P) function
5495 ** returns the P argument from the previous call
5496 ** on the same [database connection] D, or NULL for
5497 ** the first call on D.
5498 **
5499 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5500 ** and [sqlite3_preupdate_hook()] interfaces.
5501 */
5502 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5503 sqlite3*,
5504 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5505 void*
@@ -5697,12 +5742,21 @@
5742 ** fill *pzErrMsg with error message text stored in memory
5743 ** obtained from [sqlite3_malloc()]. The calling function
5744 ** should free this memory by calling [sqlite3_free()].
5745 **
5746 ** ^Extension loading must be enabled using
5747 ** [sqlite3_enable_load_extension()] or
5748 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5749 ** prior to calling this API,
5750 ** otherwise an error will be returned.
5751 **
5752 ** <b>Security warning:</b> It is recommended that the
5753 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5754 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5755 ** should be avoided. This will keep the SQL function [load_extension()]
5756 ** disabled and prevent SQL injections from giving attackers
5757 ** access to extension loading capabilities.
5758 **
5759 ** See also the [load_extension() SQL function].
5760 */
5761 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5762 sqlite3 *db, /* Load the extension into this database connection */
@@ -5722,10 +5776,21 @@
5776 **
5777 ** ^Extension loading is off by default.
5778 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5779 ** to turn extension loading on and call it with onoff==0 to turn
5780 ** it back off again.
5781 **
5782 ** ^This interface enables or disables both the C-API
5783 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5784 ** Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5785 ** to enable or disable only the C-API.
5786 **
5787 ** <b>Security warning:</b> It is recommended that extension loading
5788 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5789 ** rather than this interface, so the [load_extension()] SQL function
5790 ** remains disabled. This will prevent SQL injections from giving attackers
5791 ** access to extension loading capabilities.
5792 */
5793 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5794
5795 /*
5796 ** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7360,11 +7425,11 @@
7425 ** and database name of the source database, respectively.
7426 ** ^The source and destination [database connections] (parameters S and D)
7427 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7428 ** an error.
7429 **
7430 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7431 ** there is already a read or read-write transaction open on the
7432 ** destination database.
7433 **
7434 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7435 ** returned and an error code and error message are stored in the
@@ -8138,15 +8203,111 @@
8203 ** ^This function does not set the database handle error code or message
8204 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8205 */
8206 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
8207
8208 /*
8209 ** CAPI3REF: The pre-update hook.
8210 **
8211 ** ^These interfaces are only available if SQLite is compiled using the
8212 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8213 **
8214 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8215 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8216 ** on a [rowid table].
8217 ** ^At most one preupdate hook may be registered at a time on a single
8218 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8219 ** the previous setting.
8220 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8221 ** with a NULL pointer as the second parameter.
8222 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8223 ** the first parameter to callbacks.
8224 **
8225 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8226 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8227 ** tables.
8228 **
8229 ** ^The second parameter to the preupdate callback is a pointer to
8230 ** the [database connection] that registered the preupdate hook.
8231 ** ^The third parameter to the preupdate callback is one of the constants
8232 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to indentify the
8233 ** kind of update operation that is about to occur.
8234 ** ^(The fourth parameter to the preupdate callback is the name of the
8235 ** database within the database connection that is being modified. This
8236 ** will be "main" for the main database or "temp" for TEMP tables or
8237 ** the name given after the AS keyword in the [ATTACH] statement for attached
8238 ** databases.)^
8239 ** ^The fifth parameter to the preupdate callback is the name of the
8240 ** table that is being modified.
8241 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8242 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8243 ** undefined for SQLITE_INSERT changes.
8244 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
8245 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8246 ** undefined for SQLITE_DELETE changes.
8247 **
8248 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8249 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8250 ** provide additional information about a preupdate event. These routines
8251 ** may only be called from within a preupdate callback. Invoking any of
8252 ** these routines from outside of a preupdate callback or with a
8253 ** [database connection] pointer that is different from the one supplied
8254 ** to the preupdate callback results in undefined and probably undesirable
8255 ** behavior.
8256 **
8257 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8258 ** in the row that is being inserted, updated, or deleted.
8259 **
8260 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8261 ** a [protected sqlite3_value] that contains the value of the Nth column of
8262 ** the table row before it is updated. The N parameter must be between 0
8263 ** and one less than the number of columns or the behavior will be
8264 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8265 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8266 ** behavior is undefined. The [sqlite3_value] that P points to
8267 ** will be destroyed when the preupdate callback returns.
8268 **
8269 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8270 ** a [protected sqlite3_value] that contains the value of the Nth column of
8271 ** the table row after it is updated. The N parameter must be between 0
8272 ** and one less than the number of columns or the behavior will be
8273 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8274 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8275 ** behavior is undefined. The [sqlite3_value] that P points to
8276 ** will be destroyed when the preupdate callback returns.
8277 **
8278 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8279 ** callback was invoked as a result of a direct insert, update, or delete
8280 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8281 ** triggers; or 2 for changes resulting from triggers called by top-level
8282 ** triggers; and so forth.
8283 **
8284 ** See also: [sqlite3_update_hook()]
8285 */
8286 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8287 sqlite3 *db,
8288 void(*xPreUpdate)(
8289 void *pCtx, /* Copy of third arg to preupdate_hook() */
8290 sqlite3 *db, /* Database handle */
8291 int op, /* SQLITE_UPDATE, DELETE or INSERT */
8292 char const *zDb, /* Database name */
8293 char const *zName, /* Table name */
8294 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8295 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8296 ),
8297 void*
8298 );
8299 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8300 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8301 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8302 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8303
8304 /*
8305 ** CAPI3REF: Low-level system error code
8306 **
8307 ** ^Attempt to return the underlying operating system error code or error
8308 ** number that caused the most recent I/O error or failure to open a file.
8309 ** The return value is OS-dependent. For example, on unix systems, after
8310 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8311 ** called to get back the underlying "errno" that caused the problem, such
8312 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8313 */
@@ -8208,24 +8369,33 @@
8369
8370 /*
8371 ** CAPI3REF: Start a read transaction on an historical snapshot
8372 ** EXPERIMENTAL
8373 **
8374 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8375 ** read transaction for schema S of
8376 ** [database connection] D such that the read transaction
8377 ** refers to historical [snapshot] P, rather than the most
8378 ** recent change to the database.
8379 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8380 ** or an appropriate [error code] if it fails.
8381 **
8382 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8383 ** the first operation following the [BEGIN] that takes the schema S
8384 ** out of [autocommit mode].
8385 ** ^In other words, schema S must not currently be in
8386 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8387 ** database connection D must be out of [autocommit mode].
8388 ** ^A [snapshot] will fail to open if it has been overwritten by a
8389 ** [checkpoint].
8390 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8391 ** database connection D does not know that the database file for
8392 ** schema S is in [WAL mode]. A database connection might not know
8393 ** that the database file is in [WAL mode] if there has been no prior
8394 ** I/O on that database connection, or if the database entered [WAL mode]
8395 ** after the most recent I/O on the database connection.)^
8396 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8397 ** database connection in order to make it ready to use snapshots.)
8398 **
8399 ** The [sqlite3_snapshot_open()] interface is only available when the
8400 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8401 */
@@ -8246,10 +8416,37 @@
8416 ** The [sqlite3_snapshot_free()] interface is only available when the
8417 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8418 */
8419 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8420
8421 /*
8422 ** CAPI3REF: Compare the ages of two snapshot handles.
8423 ** EXPERIMENTAL
8424 **
8425 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8426 ** of two valid snapshot handles.
8427 **
8428 ** If the two snapshot handles are not associated with the same database
8429 ** file, the result of the comparison is undefined.
8430 **
8431 ** Additionally, the result of the comparison is only valid if both of the
8432 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8433 ** last time the wal file was deleted. The wal file is deleted when the
8434 ** database is changed back to rollback mode or when the number of database
8435 ** clients drops to zero. If either snapshot handle was obtained before the
8436 ** wal file was last deleted, the value returned by this function
8437 ** is undefined.
8438 **
8439 ** Otherwise, this API returns a negative value if P1 refers to an older
8440 ** snapshot than P2, zero if the two handles refer to the same database
8441 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8442 */
8443 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8444 sqlite3_snapshot *p1,
8445 sqlite3_snapshot *p2
8446 );
8447
8448 /*
8449 ** Undo the hack that converts floating point types to integer for
8450 ** builds on processors without floating point support.
8451 */
8452 #ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8259,10 +8456,11 @@
8456 #if 0
8457 } /* End of the 'extern "C"' block */
8458 #endif
8459 #endif /* _SQLITE3_H_ */
8460
8461 /******** Begin file sqlite3rtree.h *********/
8462 /*
8463 ** 2010 August 30
8464 **
8465 ** The author disclaims copyright to this source code. In place of
8466 ** a legal notice, here is a blessing:
@@ -8376,10 +8574,1291 @@
8574 } /* end of the 'extern "C"' block */
8575 #endif
8576
8577 #endif /* ifndef _SQLITE3RTREE_H_ */
8578
8579 /******** End of sqlite3rtree.h *********/
8580 /******** Begin file sqlite3session.h *********/
8581
8582 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8583 #define __SQLITESESSION_H_ 1
8584
8585 /*
8586 ** Make sure we can call this stuff from C++.
8587 */
8588 #if 0
8589 extern "C" {
8590 #endif
8591
8592
8593 /*
8594 ** CAPI3REF: Session Object Handle
8595 */
8596 typedef struct sqlite3_session sqlite3_session;
8597
8598 /*
8599 ** CAPI3REF: Changeset Iterator Handle
8600 */
8601 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8602
8603 /*
8604 ** CAPI3REF: Create A New Session Object
8605 **
8606 ** Create a new session object attached to database handle db. If successful,
8607 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8608 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8609 ** error code (e.g. SQLITE_NOMEM) is returned.
8610 **
8611 ** It is possible to create multiple session objects attached to a single
8612 ** database handle.
8613 **
8614 ** Session objects created using this function should be deleted using the
8615 ** [sqlite3session_delete()] function before the database handle that they
8616 ** are attached to is itself closed. If the database handle is closed before
8617 ** the session object is deleted, then the results of calling any session
8618 ** module function, including [sqlite3session_delete()] on the session object
8619 ** are undefined.
8620 **
8621 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8622 ** is not possible for an application to register a pre-update hook on a
8623 ** database handle that has one or more session objects attached. Nor is
8624 ** it possible to create a session object attached to a database handle for
8625 ** which a pre-update hook is already defined. The results of attempting
8626 ** either of these things are undefined.
8627 **
8628 ** The session object will be used to create changesets for tables in
8629 ** database zDb, where zDb is either "main", or "temp", or the name of an
8630 ** attached database. It is not an error if database zDb is not attached
8631 ** to the database when the session object is created.
8632 */
8633 int sqlite3session_create(
8634 sqlite3 *db, /* Database handle */
8635 const char *zDb, /* Name of db (e.g. "main") */
8636 sqlite3_session **ppSession /* OUT: New session object */
8637 );
8638
8639 /*
8640 ** CAPI3REF: Delete A Session Object
8641 **
8642 ** Delete a session object previously allocated using
8643 ** [sqlite3session_create()]. Once a session object has been deleted, the
8644 ** results of attempting to use pSession with any other session module
8645 ** function are undefined.
8646 **
8647 ** Session objects must be deleted before the database handle to which they
8648 ** are attached is closed. Refer to the documentation for
8649 ** [sqlite3session_create()] for details.
8650 */
8651 void sqlite3session_delete(sqlite3_session *pSession);
8652
8653
8654 /*
8655 ** CAPI3REF: Enable Or Disable A Session Object
8656 **
8657 ** Enable or disable the recording of changes by a session object. When
8658 ** enabled, a session object records changes made to the database. When
8659 ** disabled - it does not. A newly created session object is enabled.
8660 ** Refer to the documentation for [sqlite3session_changeset()] for further
8661 ** details regarding how enabling and disabling a session object affects
8662 ** the eventual changesets.
8663 **
8664 ** Passing zero to this function disables the session. Passing a value
8665 ** greater than zero enables it. Passing a value less than zero is a
8666 ** no-op, and may be used to query the current state of the session.
8667 **
8668 ** The return value indicates the final state of the session object: 0 if
8669 ** the session is disabled, or 1 if it is enabled.
8670 */
8671 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8672
8673 /*
8674 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8675 **
8676 ** Each change recorded by a session object is marked as either direct or
8677 ** indirect. A change is marked as indirect if either:
8678 **
8679 ** <ul>
8680 ** <li> The session object "indirect" flag is set when the change is
8681 ** made, or
8682 ** <li> The change is made by an SQL trigger or foreign key action
8683 ** instead of directly as a result of a users SQL statement.
8684 ** </ul>
8685 **
8686 ** If a single row is affected by more than one operation within a session,
8687 ** then the change is considered indirect if all operations meet the criteria
8688 ** for an indirect change above, or direct otherwise.
8689 **
8690 ** This function is used to set, clear or query the session object indirect
8691 ** flag. If the second argument passed to this function is zero, then the
8692 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8693 ** is set. Passing a value less than zero does not modify the current value
8694 ** of the indirect flag, and may be used to query the current state of the
8695 ** indirect flag for the specified session object.
8696 **
8697 ** The return value indicates the final state of the indirect flag: 0 if
8698 ** it is clear, or 1 if it is set.
8699 */
8700 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8701
8702 /*
8703 ** CAPI3REF: Attach A Table To A Session Object
8704 **
8705 ** If argument zTab is not NULL, then it is the name of a table to attach
8706 ** to the session object passed as the first argument. All subsequent changes
8707 ** made to the table while the session object is enabled will be recorded. See
8708 ** documentation for [sqlite3session_changeset()] for further details.
8709 **
8710 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8711 ** in the database. If additional tables are added to the database (by
8712 ** executing "CREATE TABLE" statements) after this call is made, changes for
8713 ** the new tables are also recorded.
8714 **
8715 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8716 ** defined as part of their CREATE TABLE statement. It does not matter if the
8717 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8718 ** KEY may consist of a single column, or may be a composite key.
8719 **
8720 ** It is not an error if the named table does not exist in the database. Nor
8721 ** is it an error if the named table does not have a PRIMARY KEY. However,
8722 ** no changes will be recorded in either of these scenarios.
8723 **
8724 ** Changes are not recorded for individual rows that have NULL values stored
8725 ** in one or more of their PRIMARY KEY columns.
8726 **
8727 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8728 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8729 */
8730 int sqlite3session_attach(
8731 sqlite3_session *pSession, /* Session object */
8732 const char *zTab /* Table name */
8733 );
8734
8735 /*
8736 ** CAPI3REF: Set a table filter on a Session Object.
8737 **
8738 ** The second argument (xFilter) is the "filter callback". For changes to rows
8739 ** in tables that are not attached to the Session oject, the filter is called
8740 ** to determine whether changes to the table's rows should be tracked or not.
8741 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8742 ** attached, xFilter will not be called again.
8743 */
8744 void sqlite3session_table_filter(
8745 sqlite3_session *pSession, /* Session object */
8746 int(*xFilter)(
8747 void *pCtx, /* Copy of third arg to _filter_table() */
8748 const char *zTab /* Table name */
8749 ),
8750 void *pCtx /* First argument passed to xFilter */
8751 );
8752
8753 /*
8754 ** CAPI3REF: Generate A Changeset From A Session Object
8755 **
8756 ** Obtain a changeset containing changes to the tables attached to the
8757 ** session object passed as the first argument. If successful,
8758 ** set *ppChangeset to point to a buffer containing the changeset
8759 ** and *pnChangeset to the size of the changeset in bytes before returning
8760 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8761 ** zero and return an SQLite error code.
8762 **
8763 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8764 ** each representing a change to a single row of an attached table. An INSERT
8765 ** change contains the values of each field of a new database row. A DELETE
8766 ** contains the original values of each field of a deleted database row. An
8767 ** UPDATE change contains the original values of each field of an updated
8768 ** database row along with the updated values for each updated non-primary-key
8769 ** column. It is not possible for an UPDATE change to represent a change that
8770 ** modifies the values of primary key columns. If such a change is made, it
8771 ** is represented in a changeset as a DELETE followed by an INSERT.
8772 **
8773 ** Changes are not recorded for rows that have NULL values stored in one or
8774 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8775 ** no corresponding change is present in the changesets returned by this
8776 ** function. If an existing row with one or more NULL values stored in
8777 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8778 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8779 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8780 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8781 ** DELETE change only.
8782 **
8783 ** The contents of a changeset may be traversed using an iterator created
8784 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8785 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8786 ** API.
8787 **
8788 ** Within a changeset generated by this function, all changes related to a
8789 ** single table are grouped together. In other words, when iterating through
8790 ** a changeset or when applying a changeset to a database, all changes related
8791 ** to a single table are processed before moving on to the next table. Tables
8792 ** are sorted in the same order in which they were attached (or auto-attached)
8793 ** to the sqlite3_session object. The order in which the changes related to
8794 ** a single table are stored is undefined.
8795 **
8796 ** Following a successful call to this function, it is the responsibility of
8797 ** the caller to eventually free the buffer that *ppChangeset points to using
8798 ** [sqlite3_free()].
8799 **
8800 ** <h3>Changeset Generation</h3>
8801 **
8802 ** Once a table has been attached to a session object, the session object
8803 ** records the primary key values of all new rows inserted into the table.
8804 ** It also records the original primary key and other column values of any
8805 ** deleted or updated rows. For each unique primary key value, data is only
8806 ** recorded once - the first time a row with said primary key is inserted,
8807 ** updated or deleted in the lifetime of the session.
8808 **
8809 ** There is one exception to the previous paragraph: when a row is inserted,
8810 ** updated or deleted, if one or more of its primary key columns contain a
8811 ** NULL value, no record of the change is made.
8812 **
8813 ** The session object therefore accumulates two types of records - those
8814 ** that consist of primary key values only (created when the user inserts
8815 ** a new record) and those that consist of the primary key values and the
8816 ** original values of other table columns (created when the users deletes
8817 ** or updates a record).
8818 **
8819 ** When this function is called, the requested changeset is created using
8820 ** both the accumulated records and the current contents of the database
8821 ** file. Specifically:
8822 **
8823 ** <ul>
8824 ** <li> For each record generated by an insert, the database is queried
8825 ** for a row with a matching primary key. If one is found, an INSERT
8826 ** change is added to the changeset. If no such row is found, no change
8827 ** is added to the changeset.
8828 **
8829 ** <li> For each record generated by an update or delete, the database is
8830 ** queried for a row with a matching primary key. If such a row is
8831 ** found and one or more of the non-primary key fields have been
8832 ** modified from their original values, an UPDATE change is added to
8833 ** the changeset. Or, if no such row is found in the table, a DELETE
8834 ** change is added to the changeset. If there is a row with a matching
8835 ** primary key in the database, but all fields contain their original
8836 ** values, no change is added to the changeset.
8837 ** </ul>
8838 **
8839 ** This means, amongst other things, that if a row is inserted and then later
8840 ** deleted while a session object is active, neither the insert nor the delete
8841 ** will be present in the changeset. Or if a row is deleted and then later a
8842 ** row with the same primary key values inserted while a session object is
8843 ** active, the resulting changeset will contain an UPDATE change instead of
8844 ** a DELETE and an INSERT.
8845 **
8846 ** When a session object is disabled (see the [sqlite3session_enable()] API),
8847 ** it does not accumulate records when rows are inserted, updated or deleted.
8848 ** This may appear to have some counter-intuitive effects if a single row
8849 ** is written to more than once during a session. For example, if a row
8850 ** is inserted while a session object is enabled, then later deleted while
8851 ** the same session object is disabled, no INSERT record will appear in the
8852 ** changeset, even though the delete took place while the session was disabled.
8853 ** Or, if one field of a row is updated while a session is disabled, and
8854 ** another field of the same row is updated while the session is enabled, the
8855 ** resulting changeset will contain an UPDATE change that updates both fields.
8856 */
8857 int sqlite3session_changeset(
8858 sqlite3_session *pSession, /* Session object */
8859 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
8860 void **ppChangeset /* OUT: Buffer containing changeset */
8861 );
8862
8863 /*
8864 ** CAPI3REF: Load The Difference Between Tables Into A Session
8865 **
8866 ** If it is not already attached to the session object passed as the first
8867 ** argument, this function attaches table zTbl in the same manner as the
8868 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
8869 ** does not have a primary key, this function is a no-op (but does not return
8870 ** an error).
8871 **
8872 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
8873 ** attached to the same database handle as the session object that contains
8874 ** a table compatible with the table attached to the session by this function.
8875 ** A table is considered compatible if it:
8876 **
8877 ** <ul>
8878 ** <li> Has the same name,
8879 ** <li> Has the same set of columns declared in the same order, and
8880 ** <li> Has the same PRIMARY KEY definition.
8881 ** </ul>
8882 **
8883 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
8884 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
8885 ** but no changes are added to the session object. As with other session
8886 ** APIs, tables without PRIMARY KEYs are simply ignored.
8887 **
8888 ** This function adds a set of changes to the session object that could be
8889 ** used to update the table in database zFrom (call this the "from-table")
8890 ** so that its content is the same as the table attached to the session
8891 ** object (call this the "to-table"). Specifically:
8892 **
8893 ** <ul>
8894 ** <li> For each row (primary key) that exists in the to-table but not in
8895 ** the from-table, an INSERT record is added to the session object.
8896 **
8897 ** <li> For each row (primary key) that exists in the to-table but not in
8898 ** the from-table, a DELETE record is added to the session object.
8899 **
8900 ** <li> For each row (primary key) that exists in both tables, but features
8901 ** different in each, an UPDATE record is added to the session.
8902 ** </ul>
8903 **
8904 ** To clarify, if this function is called and then a changeset constructed
8905 ** using [sqlite3session_changeset()], then after applying that changeset to
8906 ** database zFrom the contents of the two compatible tables would be
8907 ** identical.
8908 **
8909 ** It an error if database zFrom does not exist or does not contain the
8910 ** required compatible table.
8911 **
8912 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
8913 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
8914 ** may be set to point to a buffer containing an English language error
8915 ** message. It is the responsibility of the caller to free this buffer using
8916 ** sqlite3_free().
8917 */
8918 int sqlite3session_diff(
8919 sqlite3_session *pSession,
8920 const char *zFromDb,
8921 const char *zTbl,
8922 char **pzErrMsg
8923 );
8924
8925
8926 /*
8927 ** CAPI3REF: Generate A Patchset From A Session Object
8928 **
8929 ** The differences between a patchset and a changeset are that:
8930 **
8931 ** <ul>
8932 ** <li> DELETE records consist of the primary key fields only. The
8933 ** original values of other fields are omitted.
8934 ** <li> The original values of any modified fields are omitted from
8935 ** UPDATE records.
8936 ** </ul>
8937 **
8938 ** A patchset blob may be used with up to date versions of all
8939 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
8940 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
8941 ** attempting to use a patchset blob with old versions of the
8942 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
8943 **
8944 ** Because the non-primary key "old.*" fields are omitted, no
8945 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
8946 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
8947 ** in the same way as for changesets.
8948 **
8949 ** Changes within a patchset are ordered in the same way as for changesets
8950 ** generated by the sqlite3session_changeset() function (i.e. all changes for
8951 ** a single table are grouped together, tables appear in the order in which
8952 ** they were attached to the session object).
8953 */
8954 int sqlite3session_patchset(
8955 sqlite3_session *pSession, /* Session object */
8956 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
8957 void **ppPatchset /* OUT: Buffer containing changeset */
8958 );
8959
8960 /*
8961 ** CAPI3REF: Test if a changeset has recorded any changes.
8962 **
8963 ** Return non-zero if no changes to attached tables have been recorded by
8964 ** the session object passed as the first argument. Otherwise, if one or
8965 ** more changes have been recorded, return zero.
8966 **
8967 ** Even if this function returns zero, it is possible that calling
8968 ** [sqlite3session_changeset()] on the session handle may still return a
8969 ** changeset that contains no changes. This can happen when a row in
8970 ** an attached table is modified and then later on the original values
8971 ** are restored. However, if this function returns non-zero, then it is
8972 ** guaranteed that a call to sqlite3session_changeset() will return a
8973 ** changeset containing zero changes.
8974 */
8975 int sqlite3session_isempty(sqlite3_session *pSession);
8976
8977 /*
8978 ** CAPI3REF: Create An Iterator To Traverse A Changeset
8979 **
8980 ** Create an iterator used to iterate through the contents of a changeset.
8981 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
8982 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
8983 ** SQLite error code is returned.
8984 **
8985 ** The following functions can be used to advance and query a changeset
8986 ** iterator created by this function:
8987 **
8988 ** <ul>
8989 ** <li> [sqlite3changeset_next()]
8990 ** <li> [sqlite3changeset_op()]
8991 ** <li> [sqlite3changeset_new()]
8992 ** <li> [sqlite3changeset_old()]
8993 ** </ul>
8994 **
8995 ** It is the responsibility of the caller to eventually destroy the iterator
8996 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
8997 ** changeset (pChangeset) must remain valid until after the iterator is
8998 ** destroyed.
8999 **
9000 ** Assuming the changeset blob was created by one of the
9001 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9002 ** [sqlite3changeset_invert()] functions, all changes within the changeset
9003 ** that apply to a single table are grouped together. This means that when
9004 ** an application iterates through a changeset using an iterator created by
9005 ** this function, all changes that relate to a single table are visted
9006 ** consecutively. There is no chance that the iterator will visit a change
9007 ** the applies to table X, then one for table Y, and then later on visit
9008 ** another change for table X.
9009 */
9010 int sqlite3changeset_start(
9011 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9012 int nChangeset, /* Size of changeset blob in bytes */
9013 void *pChangeset /* Pointer to blob containing changeset */
9014 );
9015
9016
9017 /*
9018 ** CAPI3REF: Advance A Changeset Iterator
9019 **
9020 ** This function may only be used with iterators created by function
9021 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
9022 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9023 ** is returned and the call has no effect.
9024 **
9025 ** Immediately after an iterator is created by sqlite3changeset_start(), it
9026 ** does not point to any change in the changeset. Assuming the changeset
9027 ** is not empty, the first call to this function advances the iterator to
9028 ** point to the first change in the changeset. Each subsequent call advances
9029 ** the iterator to point to the next change in the changeset (if any). If
9030 ** no error occurs and the iterator points to a valid change after a call
9031 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9032 ** Otherwise, if all changes in the changeset have already been visited,
9033 ** SQLITE_DONE is returned.
9034 **
9035 ** If an error occurs, an SQLite error code is returned. Possible error
9036 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9037 ** SQLITE_NOMEM.
9038 */
9039 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9040
9041 /*
9042 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9043 **
9044 ** The pIter argument passed to this function may either be an iterator
9045 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9046 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9047 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9048 ** is not the case, this function returns [SQLITE_MISUSE].
9049 **
9050 ** If argument pzTab is not NULL, then *pzTab is set to point to a
9051 ** nul-terminated utf-8 encoded string containing the name of the table
9052 ** affected by the current change. The buffer remains valid until either
9053 ** sqlite3changeset_next() is called on the iterator or until the
9054 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9055 ** set to the number of columns in the table affected by the change. If
9056 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9057 ** is an indirect change, or false (0) otherwise. See the documentation for
9058 ** [sqlite3session_indirect()] for a description of direct and indirect
9059 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9060 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9061 ** type of change that the iterator currently points to.
9062 **
9063 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9064 ** SQLite error code is returned. The values of the output variables may not
9065 ** be trusted in this case.
9066 */
9067 int sqlite3changeset_op(
9068 sqlite3_changeset_iter *pIter, /* Iterator object */
9069 const char **pzTab, /* OUT: Pointer to table name */
9070 int *pnCol, /* OUT: Number of columns in table */
9071 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9072 int *pbIndirect /* OUT: True for an 'indirect' change */
9073 );
9074
9075 /*
9076 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
9077 **
9078 ** For each modified table, a changeset includes the following:
9079 **
9080 ** <ul>
9081 ** <li> The number of columns in the table, and
9082 ** <li> Which of those columns make up the tables PRIMARY KEY.
9083 ** </ul>
9084 **
9085 ** This function is used to find which columns comprise the PRIMARY KEY of
9086 ** the table modified by the change that iterator pIter currently points to.
9087 ** If successful, *pabPK is set to point to an array of nCol entries, where
9088 ** nCol is the number of columns in the table. Elements of *pabPK are set to
9089 ** 0x01 if the corresponding column is part of the tables primary key, or
9090 ** 0x00 if it is not.
9091 **
9092 ** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
9093 ** in the table.
9094 **
9095 ** If this function is called when the iterator does not point to a valid
9096 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9097 ** SQLITE_OK is returned and the output variables populated as described
9098 ** above.
9099 */
9100 int sqlite3changeset_pk(
9101 sqlite3_changeset_iter *pIter, /* Iterator object */
9102 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9103 int *pnCol /* OUT: Number of entries in output array */
9104 );
9105
9106 /*
9107 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9108 **
9109 ** The pIter argument passed to this function may either be an iterator
9110 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9111 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9112 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9113 ** Furthermore, it may only be called if the type of change that the iterator
9114 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9115 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9116 **
9117 ** Argument iVal must be greater than or equal to 0, and less than the number
9118 ** of columns in the table affected by the current change. Otherwise,
9119 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9120 **
9121 ** If successful, this function sets *ppValue to point to a protected
9122 ** sqlite3_value object containing the iVal'th value from the vector of
9123 ** original row values stored as part of the UPDATE or DELETE change and
9124 ** returns SQLITE_OK. The name of the function comes from the fact that this
9125 ** is similar to the "old.*" columns available to update or delete triggers.
9126 **
9127 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9128 ** is returned and *ppValue is set to NULL.
9129 */
9130 int sqlite3changeset_old(
9131 sqlite3_changeset_iter *pIter, /* Changeset iterator */
9132 int iVal, /* Column number */
9133 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9134 );
9135
9136 /*
9137 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9138 **
9139 ** The pIter argument passed to this function may either be an iterator
9140 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9141 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9142 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9143 ** Furthermore, it may only be called if the type of change that the iterator
9144 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9145 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9146 **
9147 ** Argument iVal must be greater than or equal to 0, and less than the number
9148 ** of columns in the table affected by the current change. Otherwise,
9149 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9150 **
9151 ** If successful, this function sets *ppValue to point to a protected
9152 ** sqlite3_value object containing the iVal'th value from the vector of
9153 ** new row values stored as part of the UPDATE or INSERT change and
9154 ** returns SQLITE_OK. If the change is an UPDATE and does not include
9155 ** a new value for the requested column, *ppValue is set to NULL and
9156 ** SQLITE_OK returned. The name of the function comes from the fact that
9157 ** this is similar to the "new.*" columns available to update or delete
9158 ** triggers.
9159 **
9160 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9161 ** is returned and *ppValue is set to NULL.
9162 */
9163 int sqlite3changeset_new(
9164 sqlite3_changeset_iter *pIter, /* Changeset iterator */
9165 int iVal, /* Column number */
9166 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9167 );
9168
9169 /*
9170 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9171 **
9172 ** This function should only be used with iterator objects passed to a
9173 ** conflict-handler callback by [sqlite3changeset_apply()] with either
9174 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9175 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9176 ** is set to NULL.
9177 **
9178 ** Argument iVal must be greater than or equal to 0, and less than the number
9179 ** of columns in the table affected by the current change. Otherwise,
9180 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9181 **
9182 ** If successful, this function sets *ppValue to point to a protected
9183 ** sqlite3_value object containing the iVal'th value from the
9184 ** "conflicting row" associated with the current conflict-handler callback
9185 ** and returns SQLITE_OK.
9186 **
9187 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9188 ** is returned and *ppValue is set to NULL.
9189 */
9190 int sqlite3changeset_conflict(
9191 sqlite3_changeset_iter *pIter, /* Changeset iterator */
9192 int iVal, /* Column number */
9193 sqlite3_value **ppValue /* OUT: Value from conflicting row */
9194 );
9195
9196 /*
9197 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9198 **
9199 ** This function may only be called with an iterator passed to an
9200 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9201 ** it sets the output variable to the total number of known foreign key
9202 ** violations in the destination database and returns SQLITE_OK.
9203 **
9204 ** In all other cases this function returns SQLITE_MISUSE.
9205 */
9206 int sqlite3changeset_fk_conflicts(
9207 sqlite3_changeset_iter *pIter, /* Changeset iterator */
9208 int *pnOut /* OUT: Number of FK violations */
9209 );
9210
9211
9212 /*
9213 ** CAPI3REF: Finalize A Changeset Iterator
9214 **
9215 ** This function is used to finalize an iterator allocated with
9216 ** [sqlite3changeset_start()].
9217 **
9218 ** This function should only be called on iterators created using the
9219 ** [sqlite3changeset_start()] function. If an application calls this
9220 ** function with an iterator passed to a conflict-handler by
9221 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9222 ** call has no effect.
9223 **
9224 ** If an error was encountered within a call to an sqlite3changeset_xxx()
9225 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9226 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9227 ** to that error is returned by this function. Otherwise, SQLITE_OK is
9228 ** returned. This is to allow the following pattern (pseudo-code):
9229 **
9230 ** sqlite3changeset_start();
9231 ** while( SQLITE_ROW==sqlite3changeset_next() ){
9232 ** // Do something with change.
9233 ** }
9234 ** rc = sqlite3changeset_finalize();
9235 ** if( rc!=SQLITE_OK ){
9236 ** // An error has occurred
9237 ** }
9238 */
9239 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9240
9241 /*
9242 ** CAPI3REF: Invert A Changeset
9243 **
9244 ** This function is used to "invert" a changeset object. Applying an inverted
9245 ** changeset to a database reverses the effects of applying the uninverted
9246 ** changeset. Specifically:
9247 **
9248 ** <ul>
9249 ** <li> Each DELETE change is changed to an INSERT, and
9250 ** <li> Each INSERT change is changed to a DELETE, and
9251 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9252 ** </ul>
9253 **
9254 ** This function does not change the order in which changes appear within
9255 ** the changeset. It merely reverses the sense of each individual change.
9256 **
9257 ** If successful, a pointer to a buffer containing the inverted changeset
9258 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9259 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9260 ** zeroed and an SQLite error code returned.
9261 **
9262 ** It is the responsibility of the caller to eventually call sqlite3_free()
9263 ** on the *ppOut pointer to free the buffer allocation following a successful
9264 ** call to this function.
9265 **
9266 ** WARNING/TODO: This function currently assumes that the input is a valid
9267 ** changeset. If it is not, the results are undefined.
9268 */
9269 int sqlite3changeset_invert(
9270 int nIn, const void *pIn, /* Input changeset */
9271 int *pnOut, void **ppOut /* OUT: Inverse of input */
9272 );
9273
9274 /*
9275 ** CAPI3REF: Concatenate Two Changeset Objects
9276 **
9277 ** This function is used to concatenate two changesets, A and B, into a
9278 ** single changeset. The result is a changeset equivalent to applying
9279 ** changeset A followed by changeset B.
9280 **
9281 ** This function combines the two input changesets using an
9282 ** sqlite3_changegroup object. Calling it produces similar results as the
9283 ** following code fragment:
9284 **
9285 ** sqlite3_changegroup *pGrp;
9286 ** rc = sqlite3_changegroup_new(&pGrp);
9287 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9288 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9289 ** if( rc==SQLITE_OK ){
9290 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9291 ** }else{
9292 ** *ppOut = 0;
9293 ** *pnOut = 0;
9294 ** }
9295 **
9296 ** Refer to the sqlite3_changegroup documentation below for details.
9297 */
9298 int sqlite3changeset_concat(
9299 int nA, /* Number of bytes in buffer pA */
9300 void *pA, /* Pointer to buffer containing changeset A */
9301 int nB, /* Number of bytes in buffer pB */
9302 void *pB, /* Pointer to buffer containing changeset B */
9303 int *pnOut, /* OUT: Number of bytes in output changeset */
9304 void **ppOut /* OUT: Buffer containing output changeset */
9305 );
9306
9307
9308 /*
9309 ** Changegroup handle.
9310 */
9311 typedef struct sqlite3_changegroup sqlite3_changegroup;
9312
9313 /*
9314 ** CAPI3REF: Combine two or more changesets into a single changeset.
9315 **
9316 ** An sqlite3_changegroup object is used to combine two or more changesets
9317 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9318 ** object may combine changesets or patchsets, but not both. The output is
9319 ** always in the same format as the input.
9320 **
9321 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9322 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9323 ** should eventually free the returned object using a call to
9324 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9325 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9326 **
9327 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9328 **
9329 ** <ul>
9330 ** <li> It is created using a call to sqlite3changegroup_new().
9331 **
9332 ** <li> Zero or more changesets (or patchsets) are added to the object
9333 ** by calling sqlite3changegroup_add().
9334 **
9335 ** <li> The result of combining all input changesets together is obtained
9336 ** by the application via a call to sqlite3changegroup_output().
9337 **
9338 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9339 ** </ul>
9340 **
9341 ** Any number of calls to add() and output() may be made between the calls to
9342 ** new() and delete(), and in any order.
9343 **
9344 ** As well as the regular sqlite3changegroup_add() and
9345 ** sqlite3changegroup_output() functions, also available are the streaming
9346 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9347 */
9348 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9349
9350 /*
9351 ** Add all changes within the changeset (or patchset) in buffer pData (size
9352 ** nData bytes) to the changegroup.
9353 **
9354 ** If the buffer contains a patchset, then all prior calls to this function
9355 ** on the same changegroup object must also have specified patchsets. Or, if
9356 ** the buffer contains a changeset, so must have the earlier calls to this
9357 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9358 ** to the changegroup.
9359 **
9360 ** Rows within the changeset and changegroup are identified by the values in
9361 ** their PRIMARY KEY columns. A change in the changeset is considered to
9362 ** apply to the same row as a change already present in the changegroup if
9363 ** the two rows have the same primary key.
9364 **
9365 ** Changes to rows that that do not already appear in the changegroup are
9366 ** simply copied into it. Or, if both the new changeset and the changegroup
9367 ** contain changes that apply to a single row, the final contents of the
9368 ** changegroup depends on the type of each change, as follows:
9369 **
9370 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9371 ** <tr><th style="white-space:pre">Existing Change </th>
9372 ** <th style="white-space:pre">New Change </th>
9373 ** <th>Output Change
9374 ** <tr><td>INSERT <td>INSERT <td>
9375 ** The new change is ignored. This case does not occur if the new
9376 ** changeset was recorded immediately after the changesets already
9377 ** added to the changegroup.
9378 ** <tr><td>INSERT <td>UPDATE <td>
9379 ** The INSERT change remains in the changegroup. The values in the
9380 ** INSERT change are modified as if the row was inserted by the
9381 ** existing change and then updated according to the new change.
9382 ** <tr><td>INSERT <td>DELETE <td>
9383 ** The existing INSERT is removed from the changegroup. The DELETE is
9384 ** not added.
9385 ** <tr><td>UPDATE <td>INSERT <td>
9386 ** The new change is ignored. This case does not occur if the new
9387 ** changeset was recorded immediately after the changesets already
9388 ** added to the changegroup.
9389 ** <tr><td>UPDATE <td>UPDATE <td>
9390 ** The existing UPDATE remains within the changegroup. It is amended
9391 ** so that the accompanying values are as if the row was updated once
9392 ** by the existing change and then again by the new change.
9393 ** <tr><td>UPDATE <td>DELETE <td>
9394 ** The existing UPDATE is replaced by the new DELETE within the
9395 ** changegroup.
9396 ** <tr><td>DELETE <td>INSERT <td>
9397 ** If one or more of the column values in the row inserted by the
9398 ** new change differ from those in the row deleted by the existing
9399 ** change, the existing DELETE is replaced by an UPDATE within the
9400 ** changegroup. Otherwise, if the inserted row is exactly the same
9401 ** as the deleted row, the existing DELETE is simply discarded.
9402 ** <tr><td>DELETE <td>UPDATE <td>
9403 ** The new change is ignored. This case does not occur if the new
9404 ** changeset was recorded immediately after the changesets already
9405 ** added to the changegroup.
9406 ** <tr><td>DELETE <td>DELETE <td>
9407 ** The new change is ignored. This case does not occur if the new
9408 ** changeset was recorded immediately after the changesets already
9409 ** added to the changegroup.
9410 ** </table>
9411 **
9412 ** If the new changeset contains changes to a table that is already present
9413 ** in the changegroup, then the number of columns and the position of the
9414 ** primary key columns for the table must be consistent. If this is not the
9415 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9416 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9417 ** returned. Or, if an out-of-memory condition occurs during processing, this
9418 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9419 ** final contents of the changegroup is undefined.
9420 **
9421 ** If no error occurs, SQLITE_OK is returned.
9422 */
9423 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9424
9425 /*
9426 ** Obtain a buffer containing a changeset (or patchset) representing the
9427 ** current contents of the changegroup. If the inputs to the changegroup
9428 ** were themselves changesets, the output is a changeset. Or, if the
9429 ** inputs were patchsets, the output is also a patchset.
9430 **
9431 ** As with the output of the sqlite3session_changeset() and
9432 ** sqlite3session_patchset() functions, all changes related to a single
9433 ** table are grouped together in the output of this function. Tables appear
9434 ** in the same order as for the very first changeset added to the changegroup.
9435 ** If the second or subsequent changesets added to the changegroup contain
9436 ** changes for tables that do not appear in the first changeset, they are
9437 ** appended onto the end of the output changeset, again in the order in
9438 ** which they are first encountered.
9439 **
9440 ** If an error occurs, an SQLite error code is returned and the output
9441 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9442 ** is returned and the output variables are set to the size of and a
9443 ** pointer to the output buffer, respectively. In this case it is the
9444 ** responsibility of the caller to eventually free the buffer using a
9445 ** call to sqlite3_free().
9446 */
9447 int sqlite3changegroup_output(
9448 sqlite3_changegroup*,
9449 int *pnData, /* OUT: Size of output buffer in bytes */
9450 void **ppData /* OUT: Pointer to output buffer */
9451 );
9452
9453 /*
9454 ** Delete a changegroup object.
9455 */
9456 void sqlite3changegroup_delete(sqlite3_changegroup*);
9457
9458 /*
9459 ** CAPI3REF: Apply A Changeset To A Database
9460 **
9461 ** Apply a changeset to a database. This function attempts to update the
9462 ** "main" database attached to handle db with the changes found in the
9463 ** changeset passed via the second and third arguments.
9464 **
9465 ** The fourth argument (xFilter) passed to this function is the "filter
9466 ** callback". If it is not NULL, then for each table affected by at least one
9467 ** change in the changeset, the filter callback is invoked with
9468 ** the table name as the second argument, and a copy of the context pointer
9469 ** passed as the sixth argument to this function as the first. If the "filter
9470 ** callback" returns zero, then no attempt is made to apply any changes to
9471 ** the table. Otherwise, if the return value is non-zero or the xFilter
9472 ** argument to this function is NULL, all changes related to the table are
9473 ** attempted.
9474 **
9475 ** For each table that is not excluded by the filter callback, this function
9476 ** tests that the target database contains a compatible table. A table is
9477 ** considered compatible if all of the following are true:
9478 **
9479 ** <ul>
9480 ** <li> The table has the same name as the name recorded in the
9481 ** changeset, and
9482 ** <li> The table has the same number of columns as recorded in the
9483 ** changeset, and
9484 ** <li> The table has primary key columns in the same position as
9485 ** recorded in the changeset.
9486 ** </ul>
9487 **
9488 ** If there is no compatible table, it is not an error, but none of the
9489 ** changes associated with the table are applied. A warning message is issued
9490 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9491 ** one such warning is issued for each table in the changeset.
9492 **
9493 ** For each change for which there is a compatible table, an attempt is made
9494 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9495 ** change. If a change cannot be applied cleanly, the conflict handler
9496 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9497 ** invoked. A description of exactly when the conflict handler is invoked for
9498 ** each type of change is below.
9499 **
9500 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9501 ** of passing anything other than a valid function pointer as the xConflict
9502 ** argument are undefined.
9503 **
9504 ** Each time the conflict handler function is invoked, it must return one
9505 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9506 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9507 ** if the second argument passed to the conflict handler is either
9508 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9509 ** returns an illegal value, any changes already made are rolled back and
9510 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9511 ** actions are taken by sqlite3changeset_apply() depending on the value
9512 ** returned by each invocation of the conflict-handler function. Refer to
9513 ** the documentation for the three
9514 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9515 **
9516 ** <dl>
9517 ** <dt>DELETE Changes<dd>
9518 ** For each DELETE change, this function checks if the target database
9519 ** contains a row with the same primary key value (or values) as the
9520 ** original row values stored in the changeset. If it does, and the values
9521 ** stored in all non-primary key columns also match the values stored in
9522 ** the changeset the row is deleted from the target database.
9523 **
9524 ** If a row with matching primary key values is found, but one or more of
9525 ** the non-primary key fields contains a value different from the original
9526 ** row value stored in the changeset, the conflict-handler function is
9527 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9528 **
9529 ** If no row with matching primary key values is found in the database,
9530 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9531 ** passed as the second argument.
9532 **
9533 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9534 ** (which can only happen if a foreign key constraint is violated), the
9535 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9536 ** passed as the second argument. This includes the case where the DELETE
9537 ** operation is attempted because an earlier call to the conflict handler
9538 ** function returned [SQLITE_CHANGESET_REPLACE].
9539 **
9540 ** <dt>INSERT Changes<dd>
9541 ** For each INSERT change, an attempt is made to insert the new row into
9542 ** the database.
9543 **
9544 ** If the attempt to insert the row fails because the database already
9545 ** contains a row with the same primary key values, the conflict handler
9546 ** function is invoked with the second argument set to
9547 ** [SQLITE_CHANGESET_CONFLICT].
9548 **
9549 ** If the attempt to insert the row fails because of some other constraint
9550 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9551 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9552 ** This includes the case where the INSERT operation is re-attempted because
9553 ** an earlier call to the conflict handler function returned
9554 ** [SQLITE_CHANGESET_REPLACE].
9555 **
9556 ** <dt>UPDATE Changes<dd>
9557 ** For each UPDATE change, this function checks if the target database
9558 ** contains a row with the same primary key value (or values) as the
9559 ** original row values stored in the changeset. If it does, and the values
9560 ** stored in all non-primary key columns also match the values stored in
9561 ** the changeset the row is updated within the target database.
9562 **
9563 ** If a row with matching primary key values is found, but one or more of
9564 ** the non-primary key fields contains a value different from an original
9565 ** row value stored in the changeset, the conflict-handler function is
9566 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9567 ** UPDATE changes only contain values for non-primary key fields that are
9568 ** to be modified, only those fields need to match the original values to
9569 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9570 **
9571 ** If no row with matching primary key values is found in the database,
9572 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9573 ** passed as the second argument.
9574 **
9575 ** If the UPDATE operation is attempted, but SQLite returns
9576 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9577 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9578 ** This includes the case where the UPDATE operation is attempted after
9579 ** an earlier call to the conflict handler function returned
9580 ** [SQLITE_CHANGESET_REPLACE].
9581 ** </dl>
9582 **
9583 ** It is safe to execute SQL statements, including those that write to the
9584 ** table that the callback related to, from within the xConflict callback.
9585 ** This can be used to further customize the applications conflict
9586 ** resolution strategy.
9587 **
9588 ** All changes made by this function are enclosed in a savepoint transaction.
9589 ** If any other error (aside from a constraint failure when attempting to
9590 ** write to the target database) occurs, then the savepoint transaction is
9591 ** rolled back, restoring the target database to its original state, and an
9592 ** SQLite error code returned.
9593 */
9594 int sqlite3changeset_apply(
9595 sqlite3 *db, /* Apply change to "main" db of this handle */
9596 int nChangeset, /* Size of changeset in bytes */
9597 void *pChangeset, /* Changeset blob */
9598 int(*xFilter)(
9599 void *pCtx, /* Copy of sixth arg to _apply() */
9600 const char *zTab /* Table name */
9601 ),
9602 int(*xConflict)(
9603 void *pCtx, /* Copy of sixth arg to _apply() */
9604 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9605 sqlite3_changeset_iter *p /* Handle describing change and conflict */
9606 ),
9607 void *pCtx /* First argument passed to xConflict */
9608 );
9609
9610 /*
9611 ** CAPI3REF: Constants Passed To The Conflict Handler
9612 **
9613 ** Values that may be passed as the second argument to a conflict-handler.
9614 **
9615 ** <dl>
9616 ** <dt>SQLITE_CHANGESET_DATA<dd>
9617 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9618 ** when processing a DELETE or UPDATE change if a row with the required
9619 ** PRIMARY KEY fields is present in the database, but one or more other
9620 ** (non primary-key) fields modified by the update do not contain the
9621 ** expected "before" values.
9622 **
9623 ** The conflicting row, in this case, is the database row with the matching
9624 ** primary key.
9625 **
9626 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9627 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9628 ** argument when processing a DELETE or UPDATE change if a row with the
9629 ** required PRIMARY KEY fields is not present in the database.
9630 **
9631 ** There is no conflicting row in this case. The results of invoking the
9632 ** sqlite3changeset_conflict() API are undefined.
9633 **
9634 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9635 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9636 ** handler while processing an INSERT change if the operation would result
9637 ** in duplicate primary key values.
9638 **
9639 ** The conflicting row in this case is the database row with the matching
9640 ** primary key.
9641 **
9642 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9643 ** If foreign key handling is enabled, and applying a changeset leaves the
9644 ** database in a state containing foreign key violations, the conflict
9645 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9646 ** exactly once before the changeset is committed. If the conflict handler
9647 ** returns CHANGESET_OMIT, the changes, including those that caused the
9648 ** foreign key constraint violation, are committed. Or, if it returns
9649 ** CHANGESET_ABORT, the changeset is rolled back.
9650 **
9651 ** No current or conflicting row information is provided. The only function
9652 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9653 ** is sqlite3changeset_fk_conflicts().
9654 **
9655 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9656 ** If any other constraint violation occurs while applying a change (i.e.
9657 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9658 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9659 **
9660 ** There is no conflicting row in this case. The results of invoking the
9661 ** sqlite3changeset_conflict() API are undefined.
9662 **
9663 ** </dl>
9664 */
9665 #define SQLITE_CHANGESET_DATA 1
9666 #define SQLITE_CHANGESET_NOTFOUND 2
9667 #define SQLITE_CHANGESET_CONFLICT 3
9668 #define SQLITE_CHANGESET_CONSTRAINT 4
9669 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9670
9671 /*
9672 ** CAPI3REF: Constants Returned By The Conflict Handler
9673 **
9674 ** A conflict handler callback must return one of the following three values.
9675 **
9676 ** <dl>
9677 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9678 ** If a conflict handler returns this value no special action is taken. The
9679 ** change that caused the conflict is not applied. The session module
9680 ** continues to the next change in the changeset.
9681 **
9682 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9683 ** This value may only be returned if the second argument to the conflict
9684 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9685 ** is not the case, any changes applied so far are rolled back and the
9686 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9687 **
9688 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9689 ** handler, then the conflicting row is either updated or deleted, depending
9690 ** on the type of change.
9691 **
9692 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9693 ** handler, then the conflicting row is removed from the database and a
9694 ** second attempt to apply the change is made. If this second attempt fails,
9695 ** the original row is restored to the database before continuing.
9696 **
9697 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9698 ** If this value is returned, any changes applied so far are rolled back
9699 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9700 ** </dl>
9701 */
9702 #define SQLITE_CHANGESET_OMIT 0
9703 #define SQLITE_CHANGESET_REPLACE 1
9704 #define SQLITE_CHANGESET_ABORT 2
9705
9706 /*
9707 ** CAPI3REF: Streaming Versions of API functions.
9708 **
9709 ** The six streaming API xxx_strm() functions serve similar purposes to the
9710 ** corresponding non-streaming API functions:
9711 **
9712 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9713 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9714 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9715 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9716 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9717 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9718 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9719 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9720 ** </table>
9721 **
9722 ** Non-streaming functions that accept changesets (or patchsets) as input
9723 ** require that the entire changeset be stored in a single buffer in memory.
9724 ** Similarly, those that return a changeset or patchset do so by returning
9725 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9726 ** Normally this is convenient. However, if an application running in a
9727 ** low-memory environment is required to handle very large changesets, the
9728 ** large contiguous memory allocations required can become onerous.
9729 **
9730 ** In order to avoid this problem, instead of a single large buffer, input
9731 ** is passed to a streaming API functions by way of a callback function that
9732 ** the sessions module invokes to incrementally request input data as it is
9733 ** required. In all cases, a pair of API function parameters such as
9734 **
9735 ** <pre>
9736 ** &nbsp; int nChangeset,
9737 ** &nbsp; void *pChangeset,
9738 ** </pre>
9739 **
9740 ** Is replaced by:
9741 **
9742 ** <pre>
9743 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9744 ** &nbsp; void *pIn,
9745 ** </pre>
9746 **
9747 ** Each time the xInput callback is invoked by the sessions module, the first
9748 ** argument passed is a copy of the supplied pIn context pointer. The second
9749 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9750 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9751 ** into the buffer and set (*pnData) to the actual number of bytes copied
9752 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9753 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9754 ** error code should be returned. In all cases, if an xInput callback returns
9755 ** an error, all processing is abandoned and the streaming API function
9756 ** returns a copy of the error code to the caller.
9757 **
9758 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9759 ** invoked by the sessions module at any point during the lifetime of the
9760 ** iterator. If such an xInput callback returns an error, the iterator enters
9761 ** an error state, whereby all subsequent calls to iterator functions
9762 ** immediately fail with the same error code as returned by xInput.
9763 **
9764 ** Similarly, streaming API functions that return changesets (or patchsets)
9765 ** return them in chunks by way of a callback function instead of via a
9766 ** pointer to a single large buffer. In this case, a pair of parameters such
9767 ** as:
9768 **
9769 ** <pre>
9770 ** &nbsp; int *pnChangeset,
9771 ** &nbsp; void **ppChangeset,
9772 ** </pre>
9773 **
9774 ** Is replaced by:
9775 **
9776 ** <pre>
9777 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9778 ** &nbsp; void *pOut
9779 ** </pre>
9780 **
9781 ** The xOutput callback is invoked zero or more times to return data to
9782 ** the application. The first parameter passed to each call is a copy of the
9783 ** pOut pointer supplied by the application. The second parameter, pData,
9784 ** points to a buffer nData bytes in size containing the chunk of output
9785 ** data being returned. If the xOutput callback successfully processes the
9786 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9787 ** it should return some other SQLite error code. In this case processing
9788 ** is immediately abandoned and the streaming API function returns a copy
9789 ** of the xOutput error code to the application.
9790 **
9791 ** The sessions module never invokes an xOutput callback with the third
9792 ** parameter set to a value less than or equal to zero. Other than this,
9793 ** no guarantees are made as to the size of the chunks of data returned.
9794 */
9795 int sqlite3changeset_apply_strm(
9796 sqlite3 *db, /* Apply change to "main" db of this handle */
9797 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9798 void *pIn, /* First arg for xInput */
9799 int(*xFilter)(
9800 void *pCtx, /* Copy of sixth arg to _apply() */
9801 const char *zTab /* Table name */
9802 ),
9803 int(*xConflict)(
9804 void *pCtx, /* Copy of sixth arg to _apply() */
9805 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9806 sqlite3_changeset_iter *p /* Handle describing change and conflict */
9807 ),
9808 void *pCtx /* First argument passed to xConflict */
9809 );
9810 int sqlite3changeset_concat_strm(
9811 int (*xInputA)(void *pIn, void *pData, int *pnData),
9812 void *pInA,
9813 int (*xInputB)(void *pIn, void *pData, int *pnData),
9814 void *pInB,
9815 int (*xOutput)(void *pOut, const void *pData, int nData),
9816 void *pOut
9817 );
9818 int sqlite3changeset_invert_strm(
9819 int (*xInput)(void *pIn, void *pData, int *pnData),
9820 void *pIn,
9821 int (*xOutput)(void *pOut, const void *pData, int nData),
9822 void *pOut
9823 );
9824 int sqlite3changeset_start_strm(
9825 sqlite3_changeset_iter **pp,
9826 int (*xInput)(void *pIn, void *pData, int *pnData),
9827 void *pIn
9828 );
9829 int sqlite3session_changeset_strm(
9830 sqlite3_session *pSession,
9831 int (*xOutput)(void *pOut, const void *pData, int nData),
9832 void *pOut
9833 );
9834 int sqlite3session_patchset_strm(
9835 sqlite3_session *pSession,
9836 int (*xOutput)(void *pOut, const void *pData, int nData),
9837 void *pOut
9838 );
9839 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
9840 int (*xInput)(void *pIn, void *pData, int *pnData),
9841 void *pIn
9842 );
9843 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
9844 int (*xOutput)(void *pOut, const void *pData, int nData),
9845 void *pOut
9846 );
9847
9848
9849 /*
9850 ** Make sure we can call this stuff from C++.
9851 */
9852 #if 0
9853 }
9854 #endif
9855
9856 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
9857
9858 /******** End of sqlite3session.h *********/
9859 /******** Begin file fts5.h *********/
9860 /*
9861 ** 2014 May 31
9862 **
9863 ** The author disclaims copyright to this source code. In place of
9864 ** a legal notice, here is a blessing:
@@ -8520,15 +9999,17 @@
9999 ** of the current query. Specifically, a query equivalent to:
10000 **
10001 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10002 **
10003 ** with $p set to a phrase equivalent to the phrase iPhrase of the
10004 ** current query is executed. Any column filter that applies to
10005 ** phrase iPhrase of the current query is included in $p. For each
10006 ** row visited, the callback function passed as the fourth argument
10007 ** is invoked. The context and API objects passed to the callback
10008 ** function may be used to access the properties of each matched row.
10009 ** Invoking Api.xUserData() returns a copy of the pointer passed as
10010 ** the third argument to pUserData.
10011 **
10012 ** If the callback function returns any value other than SQLITE_OK, the
10013 ** query is abandoned and the xQueryPhrase function returns immediately.
10014 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10015 ** Otherwise, the error code is propagated upwards.
@@ -8954,10 +10435,11 @@
10435 #endif
10436
10437 #endif /* _FTS5_H */
10438
10439
10440 /******** End of fts5.h *********/
10441
10442 /************** End of sqlite3.h *********************************************/
10443 /************** Continuing where we left off in sqliteInt.h ******************/
10444
10445 /*
@@ -9435,11 +10917,11 @@
10917 **
10918 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
10919 ** be true and false so that the unreachable code they specify will
10920 ** not be counted as untested code.
10921 */
10922 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10923 # define ALWAYS(X) (1)
10924 # define NEVER(X) (0)
10925 #elif !defined(NDEBUG)
10926 # define ALWAYS(X) ((X)?1:(assert(0),0))
10927 # define NEVER(X) ((X)?(assert(0),1):0)
@@ -9640,80 +11122,80 @@
11122 #define TK_LP 22
11123 #define TK_RP 23
11124 #define TK_AS 24
11125 #define TK_WITHOUT 25
11126 #define TK_COMMA 26
11127 #define TK_OR 27
11128 #define TK_AND 28
11129 #define TK_IS 29
11130 #define TK_MATCH 30
11131 #define TK_LIKE_KW 31
11132 #define TK_BETWEEN 32
11133 #define TK_IN 33
11134 #define TK_ISNULL 34
11135 #define TK_NOTNULL 35
11136 #define TK_NE 36
11137 #define TK_EQ 37
11138 #define TK_GT 38
11139 #define TK_LE 39
11140 #define TK_LT 40
11141 #define TK_GE 41
11142 #define TK_ESCAPE 42
11143 #define TK_BITAND 43
11144 #define TK_BITOR 44
11145 #define TK_LSHIFT 45
11146 #define TK_RSHIFT 46
11147 #define TK_PLUS 47
11148 #define TK_MINUS 48
11149 #define TK_STAR 49
11150 #define TK_SLASH 50
11151 #define TK_REM 51
11152 #define TK_CONCAT 52
11153 #define TK_COLLATE 53
11154 #define TK_BITNOT 54
11155 #define TK_ID 55
11156 #define TK_INDEXED 56
11157 #define TK_ABORT 57
11158 #define TK_ACTION 58
11159 #define TK_AFTER 59
11160 #define TK_ANALYZE 60
11161 #define TK_ASC 61
11162 #define TK_ATTACH 62
11163 #define TK_BEFORE 63
11164 #define TK_BY 64
11165 #define TK_CASCADE 65
11166 #define TK_CAST 66
11167 #define TK_COLUMNKW 67
11168 #define TK_CONFLICT 68
11169 #define TK_DATABASE 69
11170 #define TK_DESC 70
11171 #define TK_DETACH 71
11172 #define TK_EACH 72
11173 #define TK_FAIL 73
11174 #define TK_FOR 74
11175 #define TK_IGNORE 75
11176 #define TK_INITIALLY 76
11177 #define TK_INSTEAD 77
11178 #define TK_NO 78
11179 #define TK_KEY 79
11180 #define TK_OF 80
11181 #define TK_OFFSET 81
11182 #define TK_PRAGMA 82
11183 #define TK_RAISE 83
11184 #define TK_RECURSIVE 84
11185 #define TK_REPLACE 85
11186 #define TK_RESTRICT 86
11187 #define TK_ROW 87
11188 #define TK_TRIGGER 88
11189 #define TK_VACUUM 89
11190 #define TK_VIEW 90
11191 #define TK_VIRTUAL 91
11192 #define TK_WITH 92
11193 #define TK_REINDEX 93
11194 #define TK_RENAME 94
11195 #define TK_CTIME_KW 95
11196 #define TK_ANY 96
11197 #define TK_STRING 97
11198 #define TK_JOIN_KW 98
11199 #define TK_CONSTRAINT 99
11200 #define TK_DEFAULT 100
11201 #define TK_NULL 101
@@ -10311,10 +11793,11 @@
11793 typedef struct Lookaside Lookaside;
11794 typedef struct LookasideSlot LookasideSlot;
11795 typedef struct Module Module;
11796 typedef struct NameContext NameContext;
11797 typedef struct Parse Parse;
11798 typedef struct PreUpdate PreUpdate;
11799 typedef struct PrintfArguments PrintfArguments;
11800 typedef struct RowSet RowSet;
11801 typedef struct Savepoint Savepoint;
11802 typedef struct Select Select;
11803 typedef struct SQLiteThread SQLiteThread;
@@ -10723,11 +12206,11 @@
12206 ** as an instance of the following structure:
12207 */
12208 struct VdbeOp {
12209 u8 opcode; /* What operation to perform */
12210 signed char p4type; /* One of the P4_xxx constants for p4 */
12211 u8 notUsed1;
12212 u8 p5; /* Fifth parameter is an unsigned character */
12213 int p1; /* First operand */
12214 int p2; /* Second parameter (often the jump destination) */
12215 int p3; /* The third parameter */
12216 union p4union { /* fourth parameter */
@@ -10742,10 +12225,11 @@
12225 Mem *pMem; /* Used when p4type is P4_MEM */
12226 VTable *pVtab; /* Used when p4type is P4_VTAB */
12227 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
12228 int *ai; /* Used when p4type is P4_INTARRAY */
12229 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12230 Table *pTab; /* Used when p4type is P4_TABLE */
12231 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12232 Expr *pExpr; /* Used when p4type is P4_EXPR */
12233 #endif
12234 int (*xAdvance)(BtCursor *, int *);
12235 } p4;
@@ -10806,11 +12290,12 @@
12290 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
12291 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
12292 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12293 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
12294 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12295 #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12296 #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
12297
12298 /* Error message codes for OP_Halt */
12299 #define P5_ConstraintNotNull 1
12300 #define P5_ConstraintUnique 2
12301 #define P5_ConstraintCheck 3
@@ -10864,157 +12349,156 @@
12349 #define OP_Vacuum 10
12350 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
12351 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
12352 #define OP_Goto 13
12353 #define OP_Gosub 14
12354 #define OP_InitCoroutine 15
12355 #define OP_Yield 16
12356 #define OP_MustBeInt 17
12357 #define OP_Jump 18
12358 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
12359 #define OP_Once 20
12360 #define OP_If 21
12361 #define OP_IfNot 22
12362 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12363 #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12364 #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12365 #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12366 #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12367 #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12368 #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12369 #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12370 #define OP_Found 31 /* synopsis: key=r[P3@P4] */
12371 #define OP_NotExists 32 /* synopsis: intkey=r[P3] */
12372 #define OP_Last 33
12373 #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12374 #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12375 #define OP_Ne 36 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
12376 #define OP_Eq 37 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
12377 #define OP_Gt 38 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
12378 #define OP_Le 39 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
12379 #define OP_Lt 40 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
12380 #define OP_Ge 41 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
12381 #define OP_SorterSort 42
12382 #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12383 #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12384 #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12385 #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12386 #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12387 #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12388 #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12389 #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12390 #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12391 #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12392 #define OP_Sort 53
12393 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12394 #define OP_Rewind 55
12395 #define OP_IdxLE 56 /* synopsis: key=r[P3@P4] */
12396 #define OP_IdxGT 57 /* synopsis: key=r[P3@P4] */
12397 #define OP_IdxLT 58 /* synopsis: key=r[P3@P4] */
12398 #define OP_IdxGE 59 /* synopsis: key=r[P3@P4] */
12399 #define OP_RowSetRead 60 /* synopsis: r[P3]=rowset(P1) */
12400 #define OP_RowSetTest 61 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12401 #define OP_Program 62
12402 #define OP_FkIfZero 63 /* synopsis: if fkctr[P1]==0 goto P2 */
12403 #define OP_IfPos 64 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12404 #define OP_IfNotZero 65 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12405 #define OP_DecrJumpZero 66 /* synopsis: if (--r[P1])==0 goto P2 */
12406 #define OP_IncrVacuum 67
12407 #define OP_VNext 68
12408 #define OP_Init 69 /* synopsis: Start at P2 */
12409 #define OP_Return 70
12410 #define OP_EndCoroutine 71
12411 #define OP_HaltIfNull 72 /* synopsis: if r[P3]=null halt */
12412 #define OP_Halt 73
12413 #define OP_Integer 74 /* synopsis: r[P2]=P1 */
12414 #define OP_Int64 75 /* synopsis: r[P2]=P4 */
12415 #define OP_String 76 /* synopsis: r[P2]='P4' (len=P1) */
12416 #define OP_Null 77 /* synopsis: r[P2..P3]=NULL */
12417 #define OP_SoftNull 78 /* synopsis: r[P1]=NULL */
12418 #define OP_Blob 79 /* synopsis: r[P2]=P4 (len=P1) */
12419 #define OP_Variable 80 /* synopsis: r[P2]=parameter(P1,P4) */
12420 #define OP_Move 81 /* synopsis: r[P2@P3]=r[P1@P3] */
12421 #define OP_Copy 82 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12422 #define OP_SCopy 83 /* synopsis: r[P2]=r[P1] */
12423 #define OP_IntCopy 84 /* synopsis: r[P2]=r[P1] */
12424 #define OP_ResultRow 85 /* synopsis: output=r[P1@P2] */
12425 #define OP_CollSeq 86
12426 #define OP_Function0 87 /* synopsis: r[P3]=func(r[P2@P5]) */
12427 #define OP_Function 88 /* synopsis: r[P3]=func(r[P2@P5]) */
12428 #define OP_AddImm 89 /* synopsis: r[P1]=r[P1]+P2 */
12429 #define OP_RealAffinity 90
12430 #define OP_Cast 91 /* synopsis: affinity(r[P1]) */
12431 #define OP_Permutation 92
12432 #define OP_Compare 93 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12433 #define OP_Column 94 /* synopsis: r[P3]=PX */
12434 #define OP_Affinity 95 /* synopsis: affinity(r[P1@P2]) */
12435 #define OP_MakeRecord 96 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
12436 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
12437 #define OP_Count 98 /* synopsis: r[P2]=count() */
12438 #define OP_ReadCookie 99
12439 #define OP_SetCookie 100
12440 #define OP_ReopenIdx 101 /* synopsis: root=P2 iDb=P3 */
12441 #define OP_OpenRead 102 /* synopsis: root=P2 iDb=P3 */
12442 #define OP_OpenWrite 103 /* synopsis: root=P2 iDb=P3 */
12443 #define OP_OpenAutoindex 104 /* synopsis: nColumn=P2 */
12444 #define OP_OpenEphemeral 105 /* synopsis: nColumn=P2 */
12445 #define OP_SorterOpen 106
12446 #define OP_SequenceTest 107 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12447 #define OP_OpenPseudo 108 /* synopsis: P3 columns in r[P2] */
12448 #define OP_Close 109
12449 #define OP_ColumnsUsed 110
12450 #define OP_Sequence 111 /* synopsis: r[P2]=cursor[P1].ctr++ */
12451 #define OP_NewRowid 112 /* synopsis: r[P2]=rowid */
12452 #define OP_Insert 113 /* synopsis: intkey=r[P3] data=r[P2] */
12453 #define OP_InsertInt 114 /* synopsis: intkey=P3 data=r[P2] */
12454 #define OP_Delete 115
12455 #define OP_ResetCount 116
12456 #define OP_SorterCompare 117 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12457 #define OP_SorterData 118 /* synopsis: r[P2]=data */
12458 #define OP_RowKey 119 /* synopsis: r[P2]=key */
12459 #define OP_RowData 120 /* synopsis: r[P2]=data */
12460 #define OP_Rowid 121 /* synopsis: r[P2]=rowid */
12461 #define OP_NullRow 122
12462 #define OP_SorterInsert 123
12463 #define OP_IdxInsert 124 /* synopsis: key=r[P2] */
12464 #define OP_IdxDelete 125 /* synopsis: key=r[P2@P3] */
12465 #define OP_Seek 126 /* synopsis: Move P3 to P1.rowid */
12466 #define OP_IdxRowid 127 /* synopsis: r[P2]=rowid */
12467 #define OP_Destroy 128
12468 #define OP_Clear 129
12469 #define OP_ResetSorter 130
12470 #define OP_CreateIndex 131 /* synopsis: r[P2]=root iDb=P1 */
12471 #define OP_CreateTable 132 /* synopsis: r[P2]=root iDb=P1 */
12472 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
12473 #define OP_ParseSchema 134
12474 #define OP_LoadAnalysis 135
12475 #define OP_DropTable 136
12476 #define OP_DropIndex 137
12477 #define OP_DropTrigger 138
12478 #define OP_IntegrityCk 139
12479 #define OP_RowSetAdd 140 /* synopsis: rowset(P1)=r[P2] */
12480 #define OP_Param 141
12481 #define OP_FkCounter 142 /* synopsis: fkctr[P1]+=P2 */
12482 #define OP_MemMax 143 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12483 #define OP_OffsetLimit 144 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12484 #define OP_AggStep0 145 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12485 #define OP_AggStep 146 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12486 #define OP_AggFinal 147 /* synopsis: accum=r[P1] N=P2 */
12487 #define OP_Expire 148
12488 #define OP_TableLock 149 /* synopsis: iDb=P1 root=P2 write=P3 */
12489 #define OP_VBegin 150
12490 #define OP_VCreate 151
12491 #define OP_VDestroy 152
12492 #define OP_VOpen 153
12493 #define OP_VColumn 154 /* synopsis: r[P3]=vcolumn(P2) */
12494 #define OP_VRename 155
12495 #define OP_Pagecount 156
12496 #define OP_MaxPgcnt 157
12497 #define OP_CursorHint 158
12498 #define OP_Noop 159
12499 #define OP_Explain 160
 
12500
12501 /* Properties such as "out2" or "jump" that are specified in
12502 ** comments following the "case" for each opcode in the vdbe.c
12503 ** are encoded into bitvectors as follows:
12504 */
@@ -11024,30 +12508,38 @@
12508 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
12509 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
12510 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
12511 #define OPFLG_INITIALIZER {\
12512 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12513 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12514 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12515 /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12516 /* 32 */ 0x09, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12517 /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12518 /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12519 /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01,\
12520 /* 64 */ 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02, 0x02,\
12521 /* 72 */ 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10,\
12522 /* 80 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12523 /* 88 */ 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
12524 /* 96 */ 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
12525 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
12526 /* 112 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12527 /* 120 */ 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
12528 /* 128 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
12529 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
12530 /* 144 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12531 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12532 /* 160 */ 0x00,}
12533
12534 /* The sqlite3P2Values() routine is able to run faster if it knows
12535 ** the value of the largest JUMP opcode. The smaller the maximum
12536 ** JUMP opcode the better, so the mkopcodeh.tcl script that
12537 ** generated this include file strives to group all JUMP opcodes
12538 ** together near the beginning of the list.
12539 */
12540 #define SQLITE_MX_JUMP_OPCODE 69 /* Maximum JUMP opcode */
12541
12542 /************** End of opcodes.h *********************************************/
12543 /************** Continuing where we left off in vdbe.h ***********************/
12544
12545 /*
@@ -11266,11 +12758,15 @@
12758 #define PAGER_LOCKINGMODE_QUERY -1
12759 #define PAGER_LOCKINGMODE_NORMAL 0
12760 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
12761
12762 /*
12763 ** Numeric constants that encode the journalmode.
12764 **
12765 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12766 ** are exposed in the API via the "PRAGMA journal_mode" command and
12767 ** therefore cannot be changed without a compatibility break.
12768 */
12769 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
12770 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
12771 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
12772 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
@@ -11284,10 +12780,15 @@
12780 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
12781 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
12782
12783 /*
12784 ** Flags for sqlite3PagerSetFlags()
12785 **
12786 ** Value constraints (enforced via assert()):
12787 ** PAGER_FULLFSYNC == SQLITE_FullFSync
12788 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12789 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
12790 */
12791 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
12792 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
12793 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
12794 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
@@ -11453,11 +12954,11 @@
12954 */
12955 struct PgHdr {
12956 sqlite3_pcache_page *pPage; /* Pcache object page handle */
12957 void *pData; /* Page data */
12958 void *pExtra; /* Extra content */
12959 PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
12960 Pager *pPager; /* The pager this page is part of */
12961 Pgno pgno; /* Page number for this page */
12962 #ifdef SQLITE_CHECK_PAGES
12963 u32 pageHash; /* Hash of page content */
12964 #endif
@@ -11478,15 +12979,14 @@
12979 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
12980 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
12981 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
12982 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
12983 ** writing this page to the database */
12984 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
12985 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
 
12986
12987 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
12988
12989 /* Initialize and shutdown the page cache subsystem */
12990 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
12991 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
12992
@@ -11526,10 +13026,11 @@
13026
13027 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
13028 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
13029 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
13030 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13031 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13032
13033 /* Change a page number. Used by incr-vacuum. */
13034 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13035
13036 /* Remove all pages with pgno>x. Reset the cache if x==0 */
@@ -11563,10 +13064,15 @@
13064 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
13065 ** library is built.
13066 */
13067 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13068 #endif
13069
13070 #if defined(SQLITE_DEBUG)
13071 /* Check invariants on a PgHdr object */
13072 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13073 #endif
13074
13075 /* Set and get the suggested cache-size for the specified pager-cache.
13076 **
13077 ** If no global maximum is configured, then the system attempts to limit
13078 ** the total number of pages cached by purgeable pager-caches to the sum
@@ -11599,10 +13105,13 @@
13105 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13106
13107 /* Return the header size */
13108 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13109 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13110
13111 /* Number of dirty pages as a percentage of the configured cache size */
13112 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13113
13114 #endif /* _PCACHE_H_ */
13115
13116 /************** End of pcache.h **********************************************/
13117 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -11829,11 +13338,11 @@
13338 SQLITE_PRIVATE int sqlite3OsInit(void);
13339
13340 /*
13341 ** Functions for accessing sqlite3_file methods
13342 */
13343 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13344 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13345 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13346 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13347 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13348 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
@@ -11874,11 +13383,11 @@
13383 /*
13384 ** Convenience functions for opening and closing files using
13385 ** sqlite3_malloc() to obtain space for the file-handle structure.
13386 */
13387 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13388 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13389
13390 #endif /* _SQLITE_OS_H_ */
13391
13392 /************** End of os.h **************************************************/
13393 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -12206,10 +13715,17 @@
13715 int (*xCommitCallback)(void*); /* Invoked at every commit. */
13716 void *pRollbackArg; /* Argument to xRollbackCallback() */
13717 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13718 void *pUpdateArg;
13719 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13720 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13721 void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13722 void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13723 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13724 );
13725 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13726 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13727 #ifndef SQLITE_OMIT_WAL
13728 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13729 void *pWalArg;
13730 #endif
13731 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
@@ -12276,10 +13792,15 @@
13792 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
13793 #define ENC(db) ((db)->enc)
13794
13795 /*
13796 ** Possible values for the sqlite3.flags.
13797 **
13798 ** Value constraints (enforced via assert()):
13799 ** SQLITE_FullFSync == PAGER_FULLFSYNC
13800 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
13801 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
13802 */
13803 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
13804 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
13805 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
13806 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
@@ -12303,17 +13824,18 @@
13824 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
13825 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
13826 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
13827 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
13828 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
13829 #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
13830 #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
13831 #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
13832 #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
13833 #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
13834 #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
13835 #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
13836 #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
13837
13838
13839 /*
13840 ** Bits of the sqlite3.dbOptFlags field that are used by the
13841 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
@@ -12410,10 +13932,17 @@
13932 /*
13933 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
13934 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
13935 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
13936 ** are assert() statements in the code to verify this.
13937 **
13938 ** Value constraints (enforced via assert()):
13939 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
13940 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
13941 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
13942 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
13943 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
13944 */
13945 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
13946 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
13947 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
13948 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
@@ -13409,10 +14938,13 @@
14938
14939
14940 /*
14941 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
14942 ** and the WhereInfo.wctrlFlags member.
14943 **
14944 ** Value constraints (enforced via assert()):
14945 ** WHERE_USE_LIMIT == SF_FixedLimit
14946 */
14947 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
14948 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
14949 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
14950 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
@@ -13426,10 +14958,11 @@
14958 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
14959 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
14960 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
14961 #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
14962 #define WHERE_USE_LIMIT 0x4000 /* There is a constant LIMIT clause */
14963 #define WHERE_SEEK_TABLE 0x8000 /* Do not defer seeks on main table */
14964
14965 /* Allowed return values from sqlite3WhereIsDistinct()
14966 */
14967 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
14968 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
@@ -13469,20 +15002,22 @@
15002 };
15003
15004 /*
15005 ** Allowed values for the NameContext, ncFlags field.
15006 **
15007 ** Value constraints (all checked via assert()):
15008 ** NC_HasAgg == SF_HasAgg
15009 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15010 **
15011 */
15012 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
15013 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
15014 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
15015 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
15016 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
15017 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15018 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
15019 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
15020
15021 /*
15022 ** An instance of the following structure contains all information
15023 ** needed to generate code for a single SELECT statement.
@@ -13526,28 +15061,34 @@
15061 };
15062
15063 /*
15064 ** Allowed values for Select.selFlags. The "SF" prefix stands for
15065 ** "Select Flag".
15066 **
15067 ** Value constraints (all checked via assert())
15068 ** SF_HasAgg == NC_HasAgg
15069 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15070 ** SF_FixedLimit == WHERE_USE_LIMIT
15071 */
15072 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
15073 #define SF_All 0x00002 /* Includes the ALL keyword */
15074 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
15075 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15076 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
15077 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15078 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15079 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15080 #define SF_Compound 0x00100 /* Part of a compound query */
15081 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
15082 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15083 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
15084 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
15085 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
15086 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
15087 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15088 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15089 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
15090
15091
15092 /*
15093 ** The results of a SELECT can be distributed in several ways, as defined
15094 ** by one of the following macros. The "SRT" prefix means "SELECT Result
@@ -13740,10 +15281,11 @@
15281 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
15282 u8 mayAbort; /* True if statement may throw an ABORT exception */
15283 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
15284 u8 okConstFactor; /* OK to factor out constants */
15285 u8 disableLookaside; /* Number of times lookaside has been disabled */
15286 u8 nColCache; /* Number of entries in aColCache[] */
15287 int aTempReg[8]; /* Holding area for temporary registers */
15288 int nRangeReg; /* Size of the temporary register block */
15289 int iRangeReg; /* First register in temporary register block */
15290 int nErr; /* Number of errors seen */
15291 int nTab; /* Number of previously allocated VDBE cursors */
@@ -13853,18 +15395,30 @@
15395 Parse *pParse; /* The Parse structure */
15396 };
15397
15398 /*
15399 ** Bitfield flags for P5 value in various opcodes.
15400 **
15401 ** Value constraints (enforced via assert()):
15402 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15403 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15404 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
15405 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15406 ** OPFLAG_FORDELETE == BTREE_FORDELETE
15407 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15408 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
15409 */
15410 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
15411 /* Also used in P2 (not P5) of OP_Delete */
15412 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
15413 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
15414 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
15415 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
15416 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15417 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15418 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15419 #endif
15420 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
15421 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
15422 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
15423 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
15424 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
@@ -14224,18 +15778,20 @@
15778 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
15779 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
15780 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
15781 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
15782 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
15783 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
15784 #else
15785 # define sqlite3Toupper(x) toupper((unsigned char)(x))
15786 # define sqlite3Isspace(x) isspace((unsigned char)(x))
15787 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
15788 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
15789 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
15790 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
15791 # define sqlite3Tolower(x) tolower((unsigned char)(x))
15792 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
15793 #endif
15794 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15795 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
15796 #endif
15797
@@ -14355,11 +15911,11 @@
15911 #endif
15912
15913
15914 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
15915 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
15916 SQLITE_PRIVATE void sqlite3Dequote(char*);
15917 SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
15918 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
15919 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
15920 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
15921 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
@@ -14372,10 +15928,11 @@
15928 #endif
15929 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
15930 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
15931 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
15932 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
15933 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
15934 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
15935 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
15936 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
15937 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
15938 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
@@ -15167,10 +16724,11 @@
16724 ** isdigit() 0x04
16725 ** isalnum() 0x06
16726 ** isxdigit() 0x08
16727 ** toupper() 0x20
16728 ** SQLite identifier character 0x40
16729 ** Quote character 0x80
16730 **
16731 ** Bit 0x20 is set if the mapped character requires translation to upper
16732 ** case. i.e. if the character is a lower-case ASCII character.
16733 ** If x is a lower-case ASCII character, then its upper-case equivalent
16734 ** is (x - 0x20). Therefore toupper() can be implemented as:
@@ -15192,20 +16750,20 @@
16750 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
16751 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
16752 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
16753 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
16754 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
16755 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
16756 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
16757 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
16758 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
16759
16760 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
16761 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
16762 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
16763 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
16764 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
16765 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
16766 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
16767 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
16768
16769 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
@@ -16271,10 +17829,29 @@
17829 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
17830 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
17831 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
17832 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
17833
17834 /*
17835 ** Structure used to store the context required by the
17836 ** sqlite3_preupdate_*() API functions.
17837 */
17838 struct PreUpdate {
17839 Vdbe *v;
17840 VdbeCursor *pCsr; /* Cursor to read old values from */
17841 int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
17842 u8 *aRecord; /* old.* database record */
17843 KeyInfo keyinfo;
17844 UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
17845 UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
17846 int iNewReg; /* Register for new.* values */
17847 i64 iKey1; /* First key value passed to hook */
17848 i64 iKey2; /* Second key value passed to hook */
17849 int iPKey; /* If not negative index of IPK column */
17850 Mem *aNew; /* Array of new.* values */
17851 };
17852
17853 /*
17854 ** Function prototypes
17855 */
17856 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
17857 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
@@ -16330,10 +17907,13 @@
17907 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17908 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
17909 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17910 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17911 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17912 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
17913 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
17914 #endif
17915 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
17916
17917 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
17918 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
17919 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
@@ -16767,10 +18347,19 @@
18347 /* #include <assert.h> */
18348 #include <time.h>
18349
18350 #ifndef SQLITE_OMIT_DATETIME_FUNCS
18351
18352 /*
18353 ** The MSVC CRT on Windows CE may not have a localtime() function.
18354 ** So declare a substitute. The substitute function itself is
18355 ** defined in "os_win.c".
18356 */
18357 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18358 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18359 struct tm *__cdecl localtime(const time_t *);
18360 #endif
18361
18362 /*
18363 ** A structure for holding a single date and time.
18364 */
18365 typedef struct DateTime DateTime;
@@ -17135,10 +18724,11 @@
18724 p->validYMD = 0;
18725 p->validHMS = 0;
18726 p->validTZ = 0;
18727 }
18728
18729 #ifndef SQLITE_OMIT_LOCALTIME
18730 /*
18731 ** On recent Windows platforms, the localtime_s() function is available
18732 ** as part of the "Secure CRT". It is essentially equivalent to
18733 ** localtime_r() available under most POSIX platforms, except that the
18734 ** order of the parameters is reversed.
@@ -17153,11 +18743,10 @@
18743 && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
18744 #undef HAVE_LOCALTIME_S
18745 #define HAVE_LOCALTIME_S 1
18746 #endif
18747
 
18748 /*
18749 ** The following routine implements the rough equivalent of localtime_r()
18750 ** using whatever operating-system specific localtime facility that
18751 ** is available. This routine returns 0 on success and
18752 ** non-zero on any kind of error.
@@ -17957,17 +19546,15 @@
19546 ** The following routines are convenience wrappers around methods
19547 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
19548 ** of this would be completely automatic if SQLite were coded using
19549 ** C++ instead of plain old C.
19550 */
19551 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
 
19552 if( pId->pMethods ){
19553 pId->pMethods->xClose(pId);
19554 pId->pMethods = 0;
19555 }
 
19556 }
19557 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19558 DO_OS_MALLOC_TEST(id);
19559 return id->pMethods->xRead(id, pBuf, amt, offset);
19560 }
@@ -18181,16 +19768,14 @@
19768 }else{
19769 rc = SQLITE_NOMEM_BKPT;
19770 }
19771 return rc;
19772 }
19773 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
 
19774 assert( pFile );
19775 sqlite3OsClose(pFile);
19776 sqlite3_free(pFile);
 
19777 }
19778
19779 /*
19780 ** This function is a wrapper around the OS specific implementation of
19781 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
@@ -22866,30 +24451,30 @@
24451
24452 /*
24453 ** Conversion types fall into various categories as defined by the
24454 ** following enumeration.
24455 */
24456 #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24457 #define etFLOAT 1 /* Floating point. %f */
24458 #define etEXP 2 /* Exponentional notation. %e and %E */
24459 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24460 #define etSIZE 4 /* Return number of characters processed so far. %n */
24461 #define etSTRING 5 /* Strings. %s */
24462 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24463 #define etPERCENT 7 /* Percent symbol. %% */
24464 #define etCHARX 8 /* Characters. %c */
24465 /* The rest are extensions, not normally found in printf() */
24466 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24467 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24468 NULL pointers replaced by SQL NULL. %Q */
24469 #define etTOKEN 11 /* a pointer to a Token structure */
24470 #define etSRCLIST 12 /* a pointer to a SrcList */
24471 #define etPOINTER 13 /* The %p conversion */
24472 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24473 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24474
24475 #define etINVALID 16 /* Any unrecognized conversion type */
24476
24477
24478 /*
24479 ** An "etByte" is an 8-bit unsigned value.
24480 */
@@ -23040,11 +24625,11 @@
24625 etByte flag_altform2; /* True if "!" flag is present */
24626 etByte flag_zeropad; /* True if field width constant starts with zero */
24627 etByte flag_long; /* True if "l" flag is present */
24628 etByte flag_longlong; /* True if the "ll" flag is present */
24629 etByte done; /* Loop termination flag */
24630 etByte xtype = etINVALID; /* Conversion paradigm */
24631 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
24632 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
24633 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
24634 sqlite_uint64 longvalue; /* Value for integer types */
24635 LONGDOUBLE_TYPE realvalue; /* Value for real types */
@@ -25631,22 +27216,17 @@
27216 **
27217 ** 2002-Feb-14: This routine is extended to remove MS-Access style
27218 ** brackets from around identifiers. For example: "[a-b-c]" becomes
27219 ** "a-b-c".
27220 */
27221 SQLITE_PRIVATE void sqlite3Dequote(char *z){
27222 char quote;
27223 int i, j;
27224 if( z==0 ) return;
27225 quote = z[0];
27226 if( !sqlite3Isquote(quote) ) return;
27227 if( quote=='[' ) quote = ']';
 
 
 
 
 
27228 for(i=1, j=0;; i++){
27229 assert( z[i] );
27230 if( z[i]==quote ){
27231 if( z[i+1]==quote ){
27232 z[j++] = quote;
@@ -25657,11 +27237,10 @@
27237 }else{
27238 z[j++] = z[i];
27239 }
27240 }
27241 z[j] = 0;
 
27242 }
27243
27244 /*
27245 ** Generate a Token object from a string
27246 */
@@ -25750,11 +27329,11 @@
27329 int esign = 1; /* sign of exponent */
27330 int e = 0; /* exponent */
27331 int eValid = 1; /* True exponent is either not used or is well-formed */
27332 double result;
27333 int nDigits = 0;
27334 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27335
27336 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27337 *pResult = 0.0; /* Default return value, in case of an error */
27338
27339 if( enc==SQLITE_UTF8 ){
@@ -25763,11 +27342,11 @@
27342 int i;
27343 incr = 2;
27344 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27345 for(i=3-enc; i<length && z[i]==0; i+=2){}
27346 nonNum = i<length;
27347 zEnd = &z[i^1];
27348 z += (enc&1);
27349 }
27350
27351 /* skip leading spaces */
27352 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
@@ -25779,13 +27358,10 @@
27358 z+=incr;
27359 }else if( *z=='+' ){
27360 z+=incr;
27361 }
27362
 
 
 
27363 /* copy max significant digits to significand */
27364 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27365 s = s*10 + (*z - '0');
27366 z+=incr, nDigits++;
27367 }
@@ -25798,24 +27374,30 @@
27374 /* if decimal point is present */
27375 if( *z=='.' ){
27376 z+=incr;
27377 /* copy digits from after decimal to significand
27378 ** (decrease exponent by d to shift decimal right) */
27379 while( z<zEnd && sqlite3Isdigit(*z) ){
27380 if( s<((LARGEST_INT64-9)/10) ){
27381 s = s*10 + (*z - '0');
27382 d--;
27383 }
27384 z+=incr, nDigits++;
27385 }
 
 
27386 }
27387 if( z>=zEnd ) goto do_atof_calc;
27388
27389 /* if exponent is present */
27390 if( *z=='e' || *z=='E' ){
27391 z+=incr;
27392 eValid = 0;
27393
27394 /* This branch is needed to avoid a (harmless) buffer overread. The
27395 ** special comment alerts the mutation tester that the correct answer
27396 ** is obtained even if the branch is omitted */
27397 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27398
27399 /* get sign of exponent */
27400 if( *z=='-' ){
27401 esign = -1;
27402 z+=incr;
27403 }else if( *z=='+' ){
@@ -25828,13 +27410,11 @@
27410 eValid = 1;
27411 }
27412 }
27413
27414 /* skip trailing spaces */
27415 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
 
 
27416
27417 do_atof_calc:
27418 /* adjust exponent by d, and update sign */
27419 e = (e*esign) + d;
27420 if( e<0 ) {
@@ -25842,45 +27422,55 @@
27422 e *= -1;
27423 } else {
27424 esign = 1;
27425 }
27426
27427 if( s==0 ) {
27428 /* In the IEEE 754 standard, zero is signed. */
27429 result = sign<0 ? -(double)0 : (double)0;
 
 
27430 } else {
27431 /* Attempt to reduce exponent.
27432 **
27433 ** Branches that are not required for the correct answer but which only
27434 ** help to obtain the correct answer faster are marked with special
27435 ** comments, as a hint to the mutation tester.
27436 */
27437 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27438 if( esign>0 ){
27439 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27440 s *= 10;
27441 }else{
27442 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27443 s /= 10;
27444 }
27445 e--;
27446 }
27447
27448 /* adjust the sign of significand */
27449 s = sign<0 ? -s : s;
27450
27451 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27452 result = (double)s;
27453 }else{
27454 LONGDOUBLE_TYPE scale = 1.0;
27455 /* attempt to handle extremely small/large numbers better */
27456 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27457 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27458 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27459 if( esign<0 ){
27460 result = s / scale;
27461 result /= 1.0e+308;
27462 }else{
27463 result = s * scale;
27464 result *= 1.0e+308;
27465 }
27466 }else{ assert( e>=342 );
27467 if( esign<0 ){
27468 result = 0.0*s;
27469 }else{
27470 result = 1e308*1e308*s; /* Infinity */
27471 }
27472 }
27473 }else{
27474 /* 1.0e+22 is the largest power of 10 than can be
27475 ** represented exactly. */
27476 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
@@ -25889,20 +27479,18 @@
27479 result = s / scale;
27480 }else{
27481 result = s * scale;
27482 }
27483 }
 
 
27484 }
27485 }
27486
27487 /* store the result */
27488 *pResult = result;
27489
27490 /* return true if number and no extra non-whitespace chracters after */
27491 return z==zEnd && nDigits>0 && eValid && nonNum==0;
27492 #else
27493 return !sqlite3Atoi64(z, pResult, length, enc);
27494 #endif /* SQLITE_OMIT_FLOATING_POINT */
27495 }
27496
@@ -25960,11 +27548,11 @@
27548 int incr;
27549 u64 u = 0;
27550 int neg = 0; /* assume positive */
27551 int i;
27552 int c = 0;
27553 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27554 const char *zStart;
27555 const char *zEnd = zNum + length;
27556 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27557 if( enc==SQLITE_UTF8 ){
27558 incr = 1;
@@ -25971,11 +27559,11 @@
27559 }else{
27560 incr = 2;
27561 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27562 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27563 nonNum = i<length;
27564 zEnd = &zNum[i^1];
27565 zNum += (enc&1);
27566 }
27567 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27568 if( zNum<zEnd ){
27569 if( *zNum=='-' ){
@@ -25998,12 +27586,15 @@
27586 *pNum = (i64)u;
27587 }
27588 testcase( i==18 );
27589 testcase( i==19 );
27590 testcase( i==20 );
27591 if( &zNum[i]<zEnd /* Extra bytes at the end */
27592 || (i==0 && zStart==zNum) /* No digits */
27593 || i>19*incr /* Too many digits */
27594 || nonNum /* UTF16 with high-order bytes non-zero */
27595 ){
27596 /* zNum is empty or contains non-numeric text or is longer
27597 ** than 19 digits (thus guaranteeing that it is too large) */
27598 return 1;
27599 }else if( i<19*incr ){
27600 /* Less than 19 digits, so we know that it fits in 64 bits */
@@ -26041,11 +27632,10 @@
27632 */
27633 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27634 #ifndef SQLITE_OMIT_HEX_INTEGER
27635 if( z[0]=='0'
27636 && (z[1]=='x' || z[1]=='X')
 
27637 ){
27638 u64 u = 0;
27639 int i, k;
27640 for(i=2; z[i]=='0'; i++){}
27641 for(k=i; sqlite3Isxdigit(z[k]); k++){
@@ -26803,11 +28393,11 @@
28393 LogEst y = 40;
28394 if( x<8 ){
28395 if( x<2 ) return 0;
28396 while( x<8 ){ y -= 10; x <<= 1; }
28397 }else{
28398 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
28399 while( x>15 ){ y += 10; x >>= 1; }
28400 }
28401 return a[x&7] + y - 10;
28402 }
28403
@@ -26837,11 +28427,10 @@
28427 ** Note that this routine is only used when one or more of various
28428 ** non-standard compile-time options is enabled.
28429 */
28430 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28431 u64 n;
 
28432 n = x%10;
28433 x /= 10;
28434 if( n>=5 ) n -= 2;
28435 else if( n>=1 ) n -= 1;
28436 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
@@ -26913,11 +28502,11 @@
28502 ** The hashing function.
28503 */
28504 static unsigned int strHash(const char *z){
28505 unsigned int h = 0;
28506 unsigned char c;
28507 while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
28508 h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
28509 }
28510 return h;
28511 }
28512
@@ -27006,11 +28595,11 @@
28595 ){
28596 HashElem *elem; /* Used to loop thru the element list */
28597 int count; /* Number of elements left to test */
28598 unsigned int h; /* The computed hash */
28599
28600 if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
28601 struct _ht *pEntry;
28602 h = strHash(pKey) % pH->htsize;
28603 pEntry = &pH->ht[h];
28604 elem = pEntry->chain;
28605 count = pEntry->count;
@@ -27153,157 +28742,156 @@
28742 /* 10 */ "Vacuum" OpHelp(""),
28743 /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
28744 /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
28745 /* 13 */ "Goto" OpHelp(""),
28746 /* 14 */ "Gosub" OpHelp(""),
28747 /* 15 */ "InitCoroutine" OpHelp(""),
28748 /* 16 */ "Yield" OpHelp(""),
28749 /* 17 */ "MustBeInt" OpHelp(""),
28750 /* 18 */ "Jump" OpHelp(""),
28751 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
28752 /* 20 */ "Once" OpHelp(""),
28753 /* 21 */ "If" OpHelp(""),
28754 /* 22 */ "IfNot" OpHelp(""),
28755 /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
28756 /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
28757 /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
28758 /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
28759 /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
28760 /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
28761 /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
28762 /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
28763 /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
28764 /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
28765 /* 33 */ "Last" OpHelp(""),
28766 /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
28767 /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
28768 /* 36 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
28769 /* 37 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
28770 /* 38 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
28771 /* 39 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
28772 /* 40 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
28773 /* 41 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
28774 /* 42 */ "SorterSort" OpHelp(""),
28775 /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
28776 /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
28777 /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
28778 /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
28779 /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
28780 /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
28781 /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
28782 /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
28783 /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
28784 /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
28785 /* 53 */ "Sort" OpHelp(""),
28786 /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
28787 /* 55 */ "Rewind" OpHelp(""),
28788 /* 56 */ "IdxLE" OpHelp("key=r[P3@P4]"),
28789 /* 57 */ "IdxGT" OpHelp("key=r[P3@P4]"),
28790 /* 58 */ "IdxLT" OpHelp("key=r[P3@P4]"),
28791 /* 59 */ "IdxGE" OpHelp("key=r[P3@P4]"),
28792 /* 60 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
28793 /* 61 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
28794 /* 62 */ "Program" OpHelp(""),
28795 /* 63 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
28796 /* 64 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
28797 /* 65 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
28798 /* 66 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
28799 /* 67 */ "IncrVacuum" OpHelp(""),
28800 /* 68 */ "VNext" OpHelp(""),
28801 /* 69 */ "Init" OpHelp("Start at P2"),
28802 /* 70 */ "Return" OpHelp(""),
28803 /* 71 */ "EndCoroutine" OpHelp(""),
28804 /* 72 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
28805 /* 73 */ "Halt" OpHelp(""),
28806 /* 74 */ "Integer" OpHelp("r[P2]=P1"),
28807 /* 75 */ "Int64" OpHelp("r[P2]=P4"),
28808 /* 76 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
28809 /* 77 */ "Null" OpHelp("r[P2..P3]=NULL"),
28810 /* 78 */ "SoftNull" OpHelp("r[P1]=NULL"),
28811 /* 79 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
28812 /* 80 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
28813 /* 81 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
28814 /* 82 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
28815 /* 83 */ "SCopy" OpHelp("r[P2]=r[P1]"),
28816 /* 84 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
28817 /* 85 */ "ResultRow" OpHelp("output=r[P1@P2]"),
28818 /* 86 */ "CollSeq" OpHelp(""),
28819 /* 87 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
28820 /* 88 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
28821 /* 89 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
28822 /* 90 */ "RealAffinity" OpHelp(""),
28823 /* 91 */ "Cast" OpHelp("affinity(r[P1])"),
28824 /* 92 */ "Permutation" OpHelp(""),
28825 /* 93 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
28826 /* 94 */ "Column" OpHelp("r[P3]=PX"),
28827 /* 95 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
28828 /* 96 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
28829 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
28830 /* 98 */ "Count" OpHelp("r[P2]=count()"),
28831 /* 99 */ "ReadCookie" OpHelp(""),
28832 /* 100 */ "SetCookie" OpHelp(""),
28833 /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
28834 /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
28835 /* 103 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
28836 /* 104 */ "OpenAutoindex" OpHelp("nColumn=P2"),
28837 /* 105 */ "OpenEphemeral" OpHelp("nColumn=P2"),
28838 /* 106 */ "SorterOpen" OpHelp(""),
28839 /* 107 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
28840 /* 108 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
28841 /* 109 */ "Close" OpHelp(""),
28842 /* 110 */ "ColumnsUsed" OpHelp(""),
28843 /* 111 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
28844 /* 112 */ "NewRowid" OpHelp("r[P2]=rowid"),
28845 /* 113 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
28846 /* 114 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
28847 /* 115 */ "Delete" OpHelp(""),
28848 /* 116 */ "ResetCount" OpHelp(""),
28849 /* 117 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
28850 /* 118 */ "SorterData" OpHelp("r[P2]=data"),
28851 /* 119 */ "RowKey" OpHelp("r[P2]=key"),
28852 /* 120 */ "RowData" OpHelp("r[P2]=data"),
28853 /* 121 */ "Rowid" OpHelp("r[P2]=rowid"),
28854 /* 122 */ "NullRow" OpHelp(""),
28855 /* 123 */ "SorterInsert" OpHelp(""),
28856 /* 124 */ "IdxInsert" OpHelp("key=r[P2]"),
28857 /* 125 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
28858 /* 126 */ "Seek" OpHelp("Move P3 to P1.rowid"),
28859 /* 127 */ "IdxRowid" OpHelp("r[P2]=rowid"),
28860 /* 128 */ "Destroy" OpHelp(""),
28861 /* 129 */ "Clear" OpHelp(""),
28862 /* 130 */ "ResetSorter" OpHelp(""),
28863 /* 131 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
28864 /* 132 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
28865 /* 133 */ "Real" OpHelp("r[P2]=P4"),
28866 /* 134 */ "ParseSchema" OpHelp(""),
28867 /* 135 */ "LoadAnalysis" OpHelp(""),
28868 /* 136 */ "DropTable" OpHelp(""),
28869 /* 137 */ "DropIndex" OpHelp(""),
28870 /* 138 */ "DropTrigger" OpHelp(""),
28871 /* 139 */ "IntegrityCk" OpHelp(""),
28872 /* 140 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
28873 /* 141 */ "Param" OpHelp(""),
28874 /* 142 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
28875 /* 143 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
28876 /* 144 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
28877 /* 145 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
28878 /* 146 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
28879 /* 147 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
28880 /* 148 */ "Expire" OpHelp(""),
28881 /* 149 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
28882 /* 150 */ "VBegin" OpHelp(""),
28883 /* 151 */ "VCreate" OpHelp(""),
28884 /* 152 */ "VDestroy" OpHelp(""),
28885 /* 153 */ "VOpen" OpHelp(""),
28886 /* 154 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
28887 /* 155 */ "VRename" OpHelp(""),
28888 /* 156 */ "Pagecount" OpHelp(""),
28889 /* 157 */ "MaxPgcnt" OpHelp(""),
28890 /* 158 */ "CursorHint" OpHelp(""),
28891 /* 159 */ "Noop" OpHelp(""),
28892 /* 160 */ "Explain" OpHelp(""),
 
28893 };
28894 return azName[i];
28895 }
28896 #endif
28897
@@ -27912,11 +29500,11 @@
29500 #if defined(USE_PREAD64)
29501 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
29502 #else
29503 { "pread64", (sqlite3_syscall_ptr)0, 0 },
29504 #endif
29505 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29506
29507 { "write", (sqlite3_syscall_ptr)write, 0 },
29508 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29509
29510 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
@@ -27930,11 +29518,11 @@
29518 #if defined(USE_PREAD64)
29519 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
29520 #else
29521 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
29522 #endif
29523 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
29524 aSyscall[13].pCurrent)
29525
29526 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
29527 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29528
@@ -29009,20 +30597,26 @@
30597 static int unixLock(sqlite3_file *id, int eFileLock){
30598 /* The following describes the implementation of the various locks and
30599 ** lock transitions in terms of the POSIX advisory shared and exclusive
30600 ** lock primitives (called read-locks and write-locks below, to avoid
30601 ** confusion with SQLite lock names). The algorithms are complicated
30602 ** slightly in order to be compatible with Windows95 systems simultaneously
30603 ** accessing the same database file, in case that is ever required.
30604 **
30605 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30606 ** byte', each single bytes at well known offsets, and the 'shared byte
30607 ** range', a range of 510 bytes at a well known offset.
30608 **
30609 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30610 ** byte'. If this is successful, 'shared byte range' is read-locked
30611 ** and the lock on the 'pending byte' released. (Legacy note: When
30612 ** SQLite was first developed, Windows95 systems were still very common,
30613 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30614 ** single randomly selected by from the 'shared byte range' is locked.
30615 ** Windows95 is now pretty much extinct, but this work-around for the
30616 ** lack of shared-locks on Windows95 lives on, for backwards
30617 ** compatibility.)
30618 **
30619 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30620 ** A RESERVED lock is implemented by grabbing a write-lock on the
30621 ** 'reserved byte'.
30622 **
@@ -29037,15 +30631,10 @@
30631 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30632 ** implemented by obtaining a write-lock on the entire 'shared byte
30633 ** range'. Since all other locks require a read-lock on one of the bytes
30634 ** within this range, this ensures that no other locks are held on the
30635 ** database.
 
 
 
 
 
30636 */
30637 int rc = SQLITE_OK;
30638 unixFile *pFile = (unixFile*)id;
30639 unixInodeInfo *pInode;
30640 struct flock lock;
@@ -31794,14 +33383,16 @@
33383 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33384 #endif
33385 pShmNode->h = -1;
33386 pDbFd->pInode->pShmNode = pShmNode;
33387 pShmNode->pInode = pDbFd->pInode;
33388 if( sqlite3GlobalConfig.bCoreMutex ){
33389 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33390 if( pShmNode->mutex==0 ){
33391 rc = SQLITE_NOMEM_BKPT;
33392 goto shm_open_err;
33393 }
33394 }
33395
33396 if( pInode->bProcessLock==0 ){
33397 int openFlags = O_RDWR | O_CREAT;
33398 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
@@ -32916,24 +34507,28 @@
34507 "/var/tmp",
34508 "/usr/tmp",
34509 "/tmp",
34510 "."
34511 };
34512 unsigned int i = 0;
34513 struct stat buf;
34514 const char *zDir = sqlite3_temp_directory;
34515
34516 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34517 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34518 while(1){
34519 if( zDir!=0
34520 && osStat(zDir, &buf)==0
34521 && S_ISDIR(buf.st_mode)
34522 && osAccess(zDir, 03)==0
34523 ){
34524 return zDir;
34525 }
34526 if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34527 zDir = azDirs[i++];
34528 }
34529 return 0;
34530 }
34531
34532 /*
34533 ** Create a temporary file name in zBuf. zBuf must be allocated
34534 ** by the calling process and must be big enough to hold at least
@@ -32945,13 +34540,15 @@
34540
34541 /* It's odd to simulate an io-error here, but really this is just
34542 ** using the io-error infrastructure to test that SQLite handles this
34543 ** function failing.
34544 */
34545 zBuf[0] = 0;
34546 SimulateIOError( return SQLITE_IOERR );
34547
34548 zDir = unixTempFileDir();
34549 if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34550 do{
34551 u64 r;
34552 sqlite3_randomness(sizeof(r), &r);
34553 assert( nBuf>2 );
34554 zBuf[nBuf-2] = 0;
@@ -36549,12 +38146,12 @@
38146 */
38147 SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
38148 int rc;
38149 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38150 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
38151 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38152 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
38153 sqlite3_mutex_enter(pMaster);
38154 sqlite3_mutex_enter(pMem);
38155 winMemAssertMagic();
38156 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38157 /*
@@ -36595,10 +38192,16 @@
38192 SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38193 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38194 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38195 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38196 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38197 #ifdef SQLITE_ENABLE_API_ARMOR
38198 if( !zBuf ){
38199 (void)SQLITE_MISUSE_BKPT;
38200 return;
38201 }
38202 #endif
38203 #if defined(SQLITE_WIN32_HAS_ANSI)
38204 if( nMin>0 ){
38205 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38206 memcpy(zDbgBuf, zBuf, nMin);
38207 osOutputDebugStringA(zDbgBuf);
@@ -36920,151 +38523,248 @@
38523 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38524 }
38525 #endif /* SQLITE_WIN32_MALLOC */
38526
38527 /*
38528 ** Convert a UTF-8 string to Microsoft Unicode.
38529 **
38530 ** Space to hold the returned string is obtained from sqlite3_malloc().
38531 */
38532 static LPWSTR winUtf8ToUnicode(const char *zText){
38533 int nChar;
38534 LPWSTR zWideText;
38535
38536 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38537 if( nChar==0 ){
38538 return 0;
38539 }
38540 zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38541 if( zWideText==0 ){
38542 return 0;
38543 }
38544 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38545 nChar);
38546 if( nChar==0 ){
38547 sqlite3_free(zWideText);
38548 zWideText = 0;
38549 }
38550 return zWideText;
38551 }
38552
38553 /*
38554 ** Convert a Microsoft Unicode string to UTF-8.
38555 **
38556 ** Space to hold the returned string is obtained from sqlite3_malloc().
38557 */
38558 static char *winUnicodeToUtf8(LPCWSTR zWideText){
38559 int nByte;
38560 char *zText;
38561
38562 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38563 if( nByte == 0 ){
38564 return 0;
38565 }
38566 zText = sqlite3MallocZero( nByte );
38567 if( zText==0 ){
38568 return 0;
38569 }
38570 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38571 0, 0);
38572 if( nByte == 0 ){
38573 sqlite3_free(zText);
38574 zText = 0;
38575 }
38576 return zText;
38577 }
38578
38579 /*
38580 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38581 ** code page.
38582 **
38583 ** Space to hold the returned string is obtained from sqlite3_malloc().
 
38584 */
38585 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38586 int nByte;
38587 LPWSTR zMbcsText;
38588 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38589
38590 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38591 0)*sizeof(WCHAR);
38592 if( nByte==0 ){
38593 return 0;
38594 }
38595 zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38596 if( zMbcsText==0 ){
38597 return 0;
38598 }
38599 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38600 nByte);
38601 if( nByte==0 ){
38602 sqlite3_free(zMbcsText);
38603 zMbcsText = 0;
38604 }
38605 return zMbcsText;
38606 }
38607
38608 /*
38609 ** Convert a Microsoft Unicode string to a multi-byte character string,
38610 ** using the ANSI or OEM code page.
38611 **
38612 ** Space to hold the returned string is obtained from sqlite3_malloc().
38613 */
38614 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38615 int nByte;
38616 char *zText;
38617 int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38618
38619 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38620 if( nByte == 0 ){
38621 return 0;
38622 }
38623 zText = sqlite3MallocZero( nByte );
38624 if( zText==0 ){
38625 return 0;
38626 }
38627 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38628 nByte, 0, 0);
38629 if( nByte == 0 ){
38630 sqlite3_free(zText);
38631 zText = 0;
38632 }
38633 return zText;
38634 }
38635
38636 /*
38637 ** Convert a multi-byte character string to UTF-8.
38638 **
38639 ** Space to hold the returned string is obtained from sqlite3_malloc().
38640 */
38641 static char *winMbcsToUtf8(const char *zText, int useAnsi){
38642 char *zTextUtf8;
38643 LPWSTR zTmpWide;
38644
38645 zTmpWide = winMbcsToUnicode(zText, useAnsi);
38646 if( zTmpWide==0 ){
38647 return 0;
38648 }
38649 zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38650 sqlite3_free(zTmpWide);
38651 return zTextUtf8;
38652 }
38653
38654 /*
38655 ** Convert a UTF-8 string to a multi-byte character string.
38656 **
38657 ** Space to hold the returned string is obtained from sqlite3_malloc().
38658 */
38659 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38660 char *zTextMbcs;
38661 LPWSTR zTmpWide;
38662
38663 zTmpWide = winUtf8ToUnicode(zText);
38664 if( zTmpWide==0 ){
38665 return 0;
38666 }
38667 zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38668 sqlite3_free(zTmpWide);
38669 return zTextMbcs;
38670 }
38671
38672 /*
38673 ** This is a public wrapper for the winUtf8ToUnicode() function.
38674 */
38675 SQLITE_API LPWSTR SQLITE_STDCALL sqlite3_win32_utf8_to_unicode(const char *zText){
38676 #ifdef SQLITE_ENABLE_API_ARMOR
38677 if( !zText ){
38678 (void)SQLITE_MISUSE_BKPT;
38679 return 0;
38680 }
38681 #endif
38682 #ifndef SQLITE_OMIT_AUTOINIT
38683 if( sqlite3_initialize() ) return 0;
38684 #endif
38685 return winUtf8ToUnicode(zText);
38686 }
38687
38688 /*
38689 ** This is a public wrapper for the winUnicodeToUtf8() function.
38690 */
38691 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
38692 #ifdef SQLITE_ENABLE_API_ARMOR
38693 if( !zWideText ){
38694 (void)SQLITE_MISUSE_BKPT;
38695 return 0;
38696 }
38697 #endif
38698 #ifndef SQLITE_OMIT_AUTOINIT
38699 if( sqlite3_initialize() ) return 0;
38700 #endif
38701 return winUnicodeToUtf8(zWideText);
38702 }
38703
38704 /*
38705 ** This is a public wrapper for the winMbcsToUtf8() function.
38706 */
38707 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zText){
38708 #ifdef SQLITE_ENABLE_API_ARMOR
38709 if( !zText ){
38710 (void)SQLITE_MISUSE_BKPT;
38711 return 0;
38712 }
38713 #endif
38714 #ifndef SQLITE_OMIT_AUTOINIT
38715 if( sqlite3_initialize() ) return 0;
38716 #endif
38717 return winMbcsToUtf8(zText, osAreFileApisANSI());
38718 }
38719
38720 /*
38721 ** This is a public wrapper for the winMbcsToUtf8() function.
38722 */
38723 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
38724 #ifdef SQLITE_ENABLE_API_ARMOR
38725 if( !zText ){
38726 (void)SQLITE_MISUSE_BKPT;
38727 return 0;
38728 }
38729 #endif
38730 #ifndef SQLITE_OMIT_AUTOINIT
38731 if( sqlite3_initialize() ) return 0;
38732 #endif
38733 return winMbcsToUtf8(zText, useAnsi);
38734 }
38735
38736 /*
38737 ** This is a public wrapper for the winUtf8ToMbcs() function.
38738 */
38739 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zText){
38740 #ifdef SQLITE_ENABLE_API_ARMOR
38741 if( !zText ){
38742 (void)SQLITE_MISUSE_BKPT;
38743 return 0;
38744 }
38745 #endif
38746 #ifndef SQLITE_OMIT_AUTOINIT
38747 if( sqlite3_initialize() ) return 0;
38748 #endif
38749 return winUtf8ToMbcs(zText, osAreFileApisANSI());
38750 }
38751
38752 /*
38753 ** This is a public wrapper for the winUtf8ToMbcs() function.
38754 */
38755 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
38756 #ifdef SQLITE_ENABLE_API_ARMOR
38757 if( !zText ){
38758 (void)SQLITE_MISUSE_BKPT;
38759 return 0;
38760 }
38761 #endif
38762 #ifndef SQLITE_OMIT_AUTOINIT
38763 if( sqlite3_initialize() ) return 0;
38764 #endif
38765 return winUtf8ToMbcs(zText, useAnsi);
38766 }
38767
38768 /*
38769 ** This function sets the data directory or the temporary directory based on
38770 ** the provided arguments. The type argument must be 1 in order to set the
@@ -37162,11 +38862,11 @@
38862 0,
38863 0);
38864 if( dwLen > 0 ){
38865 /* allocate a buffer and convert to UTF8 */
38866 sqlite3BeginBenignMalloc();
38867 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
38868 sqlite3EndBenignMalloc();
38869 /* free the system buffer allocated by FormatMessage */
38870 osLocalFree(zTemp);
38871 }
38872 }
@@ -37304,20 +39004,21 @@
39004 winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39005 );
39006 }
39007 }
39008
39009 /*
39010 ** This #if does not rely on the SQLITE_OS_WINCE define because the
39011 ** corresponding section in "date.c" cannot use it.
39012 */
39013 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39014 (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39015 /*
39016 ** The MSVC CRT on Windows CE may not have a localtime() function.
39017 ** So define a substitute.
39018 */
39019 /* # include <time.h> */
39020 struct tm *__cdecl localtime(const time_t *t)
39021 {
39022 static struct tm y;
39023 FILETIME uTm, lTm;
39024 SYSTEMTIME pTm;
@@ -37337,10 +39038,14 @@
39038 y.tm_sec = pTm.wSecond;
39039 return &y;
39040 }
39041 #endif
39042
39043 #if SQLITE_OS_WINCE
39044 /*************************************************************************
39045 ** This section contains code for WinCE only.
39046 */
39047 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39048
39049 /*
39050 ** Acquire a lock on the handle h
39051 */
@@ -38350,13 +40055,12 @@
40055 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40056 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
40057 ** the PENDING_LOCK byte is temporary.
40058 */
40059 newLocktype = pFile->locktype;
40060 if( pFile->locktype==NO_LOCK
40061 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
 
40062 ){
40063 int cnt = 3;
40064 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40065 PENDING_BYTE, 0, 1, 0))==0 ){
40066 /* Try 3 times to get the pending lock. This is needed to work
@@ -38946,14 +40650,16 @@
40650 pNew = 0;
40651 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
40652 pShmNode->pNext = winShmNodeList;
40653 winShmNodeList = pShmNode;
40654
40655 if( sqlite3GlobalConfig.bCoreMutex ){
40656 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
40657 if( pShmNode->mutex==0 ){
40658 rc = SQLITE_IOERR_NOMEM_BKPT;
40659 goto shm_open_err;
40660 }
40661 }
40662
40663 rc = winOpen(pDbFd->pVfs,
40664 pShmNode->zFilename, /* Name of the file (UTF-8) */
40665 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
@@ -39607,11 +41313,11 @@
41313 if( osIsNT() ){
41314 zConverted = winUnicodeToUtf8(zFilename);
41315 }
41316 #ifdef SQLITE_WIN32_HAS_ANSI
41317 else{
41318 zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41319 }
41320 #endif
41321 /* caller will handle out of memory */
41322 return zConverted;
41323 }
@@ -39628,11 +41334,11 @@
41334 if( osIsNT() ){
41335 zConverted = winUtf8ToUnicode(zFilename);
41336 }
41337 #ifdef SQLITE_WIN32_HAS_ANSI
41338 else{
41339 zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41340 }
41341 #endif
41342 /* caller will handle out of memory */
41343 return zConverted;
41344 }
@@ -39829,11 +41535,11 @@
41535 sqlite3_free(zBuf);
41536 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41537 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41538 "winGetTempname3", 0);
41539 }
41540 zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41541 if( zUtf8 ){
41542 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41543 sqlite3_free(zUtf8);
41544 }else{
41545 sqlite3_free(zBuf);
@@ -40607,11 +42313,11 @@
42313 sqlite3_free(zTemp);
42314 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42315 "winFullPathname4", zRelative);
42316 }
42317 sqlite3_free(zConverted);
42318 zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42319 sqlite3_free(zTemp);
42320 }
42321 #endif
42322 if( zOut ){
42323 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
@@ -41413,11 +43119,33 @@
43119 ** This file implements that page cache.
43120 */
43121 /* #include "sqliteInt.h" */
43122
43123 /*
43124 ** A complete page cache is an instance of this structure. Every
43125 ** entry in the cache holds a single page of the database file. The
43126 ** btree layer only operates on the cached copy of the database pages.
43127 **
43128 ** A page cache entry is "clean" if it exactly matches what is currently
43129 ** on disk. A page is "dirty" if it has been modified and needs to be
43130 ** persisted to disk.
43131 **
43132 ** pDirty, pDirtyTail, pSynced:
43133 ** All dirty pages are linked into the doubly linked list using
43134 ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43135 ** such that p was added to the list more recently than p->pDirtyNext.
43136 ** PCache.pDirty points to the first (newest) element in the list and
43137 ** pDirtyTail to the last (oldest).
43138 **
43139 ** The PCache.pSynced variable is used to optimize searching for a dirty
43140 ** page to eject from the cache mid-transaction. It is better to eject
43141 ** a page that does not require a journal sync than one that does.
43142 ** Therefore, pSynced is maintained to that it *almost* always points
43143 ** to either the oldest page in the pDirty/pDirtyTail list that has a
43144 ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43145 ** (so that the right page to eject can be found by following pDirtyPrev
43146 ** pointers).
43147 */
43148 struct PCache {
43149 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
43150 PgHdr *pSynced; /* Last synced page in dirty page list */
43151 int nRefSum; /* Sum of ref counts over all pages */
@@ -41429,10 +43157,99 @@
43157 u8 eCreate; /* eCreate value for for xFetch() */
43158 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
43159 void *pStress; /* Argument to xStress */
43160 sqlite3_pcache *pCache; /* Pluggable cache module */
43161 };
43162
43163 /********************************** Test and Debug Logic **********************/
43164 /*
43165 ** Debug tracing macros. Enable by by changing the "0" to "1" and
43166 ** recompiling.
43167 **
43168 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43169 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43170 ** is displayed for many operations, resulting in a lot of output.
43171 */
43172 #if defined(SQLITE_DEBUG) && 0
43173 int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
43174 int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
43175 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43176 void pcacheDump(PCache *pCache){
43177 int N;
43178 int i, j;
43179 sqlite3_pcache_page *pLower;
43180 PgHdr *pPg;
43181 unsigned char *a;
43182
43183 if( sqlite3PcacheTrace<2 ) return;
43184 if( pCache->pCache==0 ) return;
43185 N = sqlite3PcachePagecount(pCache);
43186 if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43187 for(i=1; i<=N; i++){
43188 pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43189 if( pLower==0 ) continue;
43190 pPg = (PgHdr*)pLower->pExtra;
43191 printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43192 a = (unsigned char *)pLower->pBuf;
43193 for(j=0; j<12; j++) printf("%02x", a[j]);
43194 printf("\n");
43195 if( pPg->pPage==0 ){
43196 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43197 }
43198 }
43199 }
43200 #else
43201 # define pcacheTrace(X)
43202 # define pcacheDump(X)
43203 #endif
43204
43205 /*
43206 ** Check invariants on a PgHdr entry. Return true if everything is OK.
43207 ** Return false if any invariant is violated.
43208 **
43209 ** This routine is for use inside of assert() statements only. For
43210 ** example:
43211 **
43212 ** assert( sqlite3PcachePageSanity(pPg) );
43213 */
43214 #if SQLITE_DEBUG
43215 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43216 PCache *pCache;
43217 assert( pPg!=0 );
43218 assert( pPg->pgno>0 ); /* Page number is 1 or more */
43219 pCache = pPg->pCache;
43220 assert( pCache!=0 ); /* Every page has an associated PCache */
43221 if( pPg->flags & PGHDR_CLEAN ){
43222 assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43223 assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
43224 assert( pCache->pDirtyTail!=pPg );
43225 }
43226 /* WRITEABLE pages must also be DIRTY */
43227 if( pPg->flags & PGHDR_WRITEABLE ){
43228 assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
43229 }
43230 /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
43231 ** for example, when using the sqlite3PagerDontWrite() optimization:
43232 ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43233 ** (2) Page X moved to freelist, WRITEABLE is cleared
43234 ** (3) Page X reused, WRITEABLE is set again
43235 ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43236 ** in step 3, and page might be written into the database without first
43237 ** syncing the rollback journal, which might cause corruption on a power
43238 ** loss.
43239 **
43240 ** Another example is when the database page size is smaller than the
43241 ** disk sector size. When any page of a sector is journalled, all pages
43242 ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43243 ** in case they are later modified, since all pages in the same sector
43244 ** must be journalled and synced before any of those pages can be safely
43245 ** written.
43246 */
43247 return 1;
43248 }
43249 #endif /* SQLITE_DEBUG */
43250
43251
43252 /********************************** Linked List Management ********************/
43253
43254 /* Allowed values for second argument to pcacheManageDirtyList() */
43255 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
@@ -41446,21 +43263,20 @@
43263 ** the dirty list. Doing both moves pPage to the front of the dirty list.
43264 */
43265 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43266 PCache *p = pPage->pCache;
43267
43268 pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43269 addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43270 pPage->pgno));
43271 if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43272 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43273 assert( pPage->pDirtyPrev || pPage==p->pDirty );
43274
43275 /* Update the PCache1.pSynced variable if necessary. */
43276 if( p->pSynced==pPage ){
43277 p->pSynced = pPage->pDirtyPrev;
 
 
 
 
43278 }
43279
43280 if( pPage->pDirtyNext ){
43281 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43282 }else{
@@ -41468,14 +43284,19 @@
43284 p->pDirtyTail = pPage->pDirtyPrev;
43285 }
43286 if( pPage->pDirtyPrev ){
43287 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43288 }else{
43289 /* If there are now no dirty pages in the cache, set eCreate to 2.
43290 ** This is an optimization that allows sqlite3PcacheFetch() to skip
43291 ** searching for a dirty page to eject from the cache when it might
43292 ** otherwise have to. */
43293 assert( pPage==p->pDirty );
43294 p->pDirty = pPage->pDirtyNext;
43295 assert( p->bPurgeable || p->eCreate==2 );
43296 if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
43297 assert( p->bPurgeable==0 || p->eCreate==1 );
43298 p->eCreate = 2;
43299 }
43300 }
43301 pPage->pDirtyNext = 0;
43302 pPage->pDirtyPrev = 0;
@@ -41493,23 +43314,34 @@
43314 assert( p->eCreate==2 );
43315 p->eCreate = 1;
43316 }
43317 }
43318 p->pDirty = pPage;
43319
43320 /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43321 ** pSynced to point to it. Checking the NEED_SYNC flag is an
43322 ** optimization, as if pSynced points to a page with the NEED_SYNC
43323 ** flag set sqlite3PcacheFetchStress() searches through all newer
43324 ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
43325 if( !p->pSynced
43326 && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
43327 ){
43328 p->pSynced = pPage;
43329 }
43330 }
43331 pcacheDump(p);
43332 }
43333
43334 /*
43335 ** Wrapper around the pluggable caches xUnpin method. If the cache is
43336 ** being used for an in-memory database, this function is a no-op.
43337 */
43338 static void pcacheUnpin(PgHdr *p){
43339 if( p->pCache->bPurgeable ){
43340 pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43341 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43342 pcacheDump(p->pCache);
43343 }
43344 }
43345
43346 /*
43347 ** Compute the number of pages of cache requested. p->szCache is the
@@ -41575,10 +43407,11 @@
43407 p->eCreate = 2;
43408 p->xStress = xStress;
43409 p->pStress = pStress;
43410 p->szCache = 100;
43411 p->szSpill = 1;
43412 pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43413 return sqlite3PcacheSetPageSize(p, szPage);
43414 }
43415
43416 /*
43417 ** Change the page size for PCache object. The caller must ensure that there
@@ -41597,10 +43430,11 @@
43430 if( pCache->pCache ){
43431 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43432 }
43433 pCache->pCache = pNew;
43434 pCache->szPage = szPage;
43435 pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43436 }
43437 return SQLITE_OK;
43438 }
43439
43440 /*
@@ -41631,15 +43465,17 @@
43465 PCache *pCache, /* Obtain the page from this cache */
43466 Pgno pgno, /* Page number to obtain */
43467 int createFlag /* If true, create page if it does not exist already */
43468 ){
43469 int eCreate;
43470 sqlite3_pcache_page *pRes;
43471
43472 assert( pCache!=0 );
43473 assert( pCache->pCache!=0 );
43474 assert( createFlag==3 || createFlag==0 );
43475 assert( pgno>0 );
43476 assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43477
43478 /* eCreate defines what to do if the page does not exist.
43479 ** 0 Do not allocate a new page. (createFlag==0)
43480 ** 1 Allocate a new page if doing so is inexpensive.
43481 ** (createFlag==1 AND bPurgeable AND pDirty)
@@ -41648,16 +43484,19 @@
43484 */
43485 eCreate = createFlag & pCache->eCreate;
43486 assert( eCreate==0 || eCreate==1 || eCreate==2 );
43487 assert( createFlag==0 || pCache->eCreate==eCreate );
43488 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43489 pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43490 pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43491 createFlag?" create":"",pRes));
43492 return pRes;
43493 }
43494
43495 /*
43496 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
43497 ** page because no clean pages are available for reuse and the cache
43498 ** size limit has been reached, then this routine can be invoked to
43499 ** try harder to allocate a page. This routine might invoke the stress
43500 ** callback to spill dirty pages to the journal. It will then try to
43501 ** allocate the new page and will only fail to allocate a new page on
43502 ** an OOM error.
@@ -41675,11 +43514,15 @@
43514 if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
43515 /* Find a dirty page to write-out and recycle. First try to find a
43516 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
43517 ** cleared), but if that is not possible settle for any other
43518 ** unreferenced dirty page.
43519 **
43520 ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43521 ** flag is currently referenced, then the following may leave pSynced
43522 ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43523 ** cleared). This is Ok, as pSynced is just an optimization. */
43524 for(pPg=pCache->pSynced;
43525 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
43526 pPg=pPg->pDirtyPrev
43527 );
43528 pCache->pSynced = pPg;
@@ -41693,11 +43536,13 @@
43536 "spill page %d making room for %d - cache used: %d/%d",
43537 pPg->pgno, pgno,
43538 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
43539 numberOfCachePages(pCache));
43540 #endif
43541 pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
43542 rc = pCache->xStress(pCache->pStress, pPg);
43543 pcacheDump(pCache);
43544 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
43545 return rc;
43546 }
43547 }
43548 }
@@ -41753,10 +43598,11 @@
43598 if( !pPgHdr->pPage ){
43599 return pcacheFetchFinishWithInit(pCache, pgno, pPage);
43600 }
43601 pCache->nRefSum++;
43602 pPgHdr->nRef++;
43603 assert( sqlite3PcachePageSanity(pPgHdr) );
43604 return pPgHdr;
43605 }
43606
43607 /*
43608 ** Decrement the reference count on a page. If the page is clean and the
@@ -41766,12 +43612,15 @@
43612 assert( p->nRef>0 );
43613 p->pCache->nRefSum--;
43614 if( (--p->nRef)==0 ){
43615 if( p->flags&PGHDR_CLEAN ){
43616 pcacheUnpin(p);
43617 }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
43618 /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
43619 ** then page p is already at the head of the dirty list and the
43620 ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
43621 ** tag above. */
43622 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
43623 }
43624 }
43625 }
43626
@@ -41778,10 +43627,11 @@
43627 /*
43628 ** Increase the reference count of a supplied page by 1.
43629 */
43630 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
43631 assert(p->nRef>0);
43632 assert( sqlite3PcachePageSanity(p) );
43633 p->nRef++;
43634 p->pCache->nRefSum++;
43635 }
43636
43637 /*
@@ -41789,10 +43639,11 @@
43639 ** page. This function deletes that reference, so after it returns the
43640 ** page pointed to by p is invalid.
43641 */
43642 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
43643 assert( p->nRef==1 );
43644 assert( sqlite3PcachePageSanity(p) );
43645 if( p->flags&PGHDR_DIRTY ){
43646 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
43647 }
43648 p->pCache->nRefSum--;
43649 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
@@ -41802,30 +43653,36 @@
43653 ** Make sure the page is marked as dirty. If it isn't dirty already,
43654 ** make it so.
43655 */
43656 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
43657 assert( p->nRef>0 );
43658 assert( sqlite3PcachePageSanity(p) );
43659 if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
43660 p->flags &= ~PGHDR_DONT_WRITE;
43661 if( p->flags & PGHDR_CLEAN ){
43662 p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
43663 pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
43664 assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
43665 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
43666 }
43667 assert( sqlite3PcachePageSanity(p) );
43668 }
43669 }
43670
43671 /*
43672 ** Make sure the page is marked as clean. If it isn't clean already,
43673 ** make it so.
43674 */
43675 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
43676 assert( sqlite3PcachePageSanity(p) );
43677 if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
43678 assert( (p->flags & PGHDR_CLEAN)==0 );
43679 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
43680 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
43681 p->flags |= PGHDR_CLEAN;
43682 pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
43683 assert( sqlite3PcachePageSanity(p) );
43684 if( p->nRef==0 ){
43685 pcacheUnpin(p);
43686 }
43687 }
43688 }
@@ -41833,14 +43690,27 @@
43690 /*
43691 ** Make every page in the cache clean.
43692 */
43693 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
43694 PgHdr *p;
43695 pcacheTrace(("%p.CLEAN-ALL\n",pCache));
43696 while( (p = pCache->pDirty)!=0 ){
43697 sqlite3PcacheMakeClean(p);
43698 }
43699 }
43700
43701 /*
43702 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
43703 */
43704 SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
43705 PgHdr *p;
43706 pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
43707 for(p=pCache->pDirty; p; p=p->pDirtyNext){
43708 p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
43709 }
43710 pCache->pSynced = pCache->pDirtyTail;
43711 }
43712
43713 /*
43714 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
43715 */
43716 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
@@ -41856,10 +43726,12 @@
43726 */
43727 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
43728 PCache *pCache = p->pCache;
43729 assert( p->nRef>0 );
43730 assert( newPgno>0 );
43731 assert( sqlite3PcachePageSanity(p) );
43732 pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
43733 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
43734 p->pgno = newPgno;
43735 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
43736 pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
43737 }
@@ -41876,18 +43748,19 @@
43748 */
43749 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
43750 if( pCache->pCache ){
43751 PgHdr *p;
43752 PgHdr *pNext;
43753 pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
43754 for(p=pCache->pDirty; p; p=pNext){
43755 pNext = p->pDirtyNext;
43756 /* This routine never gets call with a positive pgno except right
43757 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
43758 ** it must be that pgno==0.
43759 */
43760 assert( p->pgno>0 );
43761 if( p->pgno>pgno ){
43762 assert( p->flags&PGHDR_DIRTY );
43763 sqlite3PcacheMakeClean(p);
43764 }
43765 }
43766 if( pgno==0 && pCache->nRefSum ){
@@ -41906,10 +43779,11 @@
43779 /*
43780 ** Close a cache.
43781 */
43782 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
43783 assert( pCache->pCache!=0 );
43784 pcacheTrace(("%p.CLOSE\n",pCache));
43785 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43786 }
43787
43788 /*
43789 ** Discard the contents of the cache.
@@ -42074,10 +43948,21 @@
43948 ** Return the size of the header added by this middleware layer
43949 ** in the page-cache hierarchy.
43950 */
43951 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
43952
43953 /*
43954 ** Return the number of dirty pages currently in the cache, as a percentage
43955 ** of the configured cache size.
43956 */
43957 SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
43958 PgHdr *pDirty;
43959 int nDirty = 0;
43960 int nCache = numberOfCachePages(pCache);
43961 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
43962 return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
43963 }
43964
43965 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
43966 /*
43967 ** For all dirty pages currently in the cache, invoke the specified
43968 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
@@ -42783,12 +44668,12 @@
44668 pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
44669 #endif
44670
44671 #if SQLITE_THREADSAFE
44672 if( sqlite3GlobalConfig.bCoreMutex ){
44673 pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
44674 pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
44675 }
44676 #endif
44677 if( pcache1.separateCache
44678 && sqlite3GlobalConfig.nPage!=0
44679 && sqlite3GlobalConfig.pPage==0
@@ -43390,12 +45275,13 @@
45275 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
45276 ** The cost of a TEST using the same batch number is O(logN). The cost
45277 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
45278 ** primitives are constant time. The cost of DESTROY is O(N).
45279 **
45280 ** TEST and SMALLEST may not be used by the same RowSet. This used to
45281 ** be possible, but the feature was not used, so it was removed in order
45282 ** to simplify the code.
45283 */
45284 /* #include "sqliteInt.h" */
45285
45286
45287 /*
@@ -43512,11 +45398,13 @@
45398 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45399 ** routine returns NULL.
45400 */
45401 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
45402 assert( p!=0 );
45403 if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
45404 /* We could allocate a fresh RowSetEntry each time one is needed, but it
45405 ** is more efficient to pull a preallocated entry from the pool */
45406 struct RowSetChunk *pNew;
45407 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45408 if( pNew==0 ){
45409 return 0;
45410 }
@@ -43546,11 +45434,13 @@
45434 if( pEntry==0 ) return;
45435 pEntry->v = rowid;
45436 pEntry->pRight = 0;
45437 pLast = p->pLast;
45438 if( pLast ){
45439 if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
45440 /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45441 ** where possible */
45442 p->rsFlags &= ~ROWSET_SORTED;
45443 }
45444 pLast->pRight = pEntry;
45445 }else{
45446 p->pEntry = pEntry;
@@ -43668,27 +45558,33 @@
45558 struct RowSetEntry **ppList,
45559 int iDepth
45560 ){
45561 struct RowSetEntry *p; /* Root of the new tree */
45562 struct RowSetEntry *pLeft; /* Left subtree */
45563 if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45564 /* Prevent unnecessary deep recursion when we run out of entries */
45565 return 0;
45566 }
45567 if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
45568 /* This branch causes a *balanced* tree to be generated. A valid tree
45569 ** is still generated without this branch, but the tree is wildly
45570 ** unbalanced and inefficient. */
45571 pLeft = rowSetNDeepTree(ppList, iDepth-1);
45572 p = *ppList;
45573 if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
45574 /* It is safe to always return here, but the resulting tree
45575 ** would be unbalanced */
45576 return pLeft;
45577 }
45578 p->pLeft = pLeft;
45579 *ppList = p->pRight;
45580 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45581 }else{
45582 p = *ppList;
45583 *ppList = p->pRight;
45584 p->pLeft = p->pRight = 0;
45585 }
 
 
 
 
 
 
 
 
 
45586 return p;
45587 }
45588
45589 /*
45590 ** Convert a sorted list of elements into a binary tree. Make the tree
@@ -43711,63 +45607,41 @@
45607 p->pRight = rowSetNDeepTree(&pList, iDepth);
45608 }
45609 return p;
45610 }
45611
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45612 /*
45613 ** Extract the smallest element from the RowSet.
45614 ** Write the element into *pRowid. Return 1 on success. Return
45615 ** 0 if the RowSet is already empty.
45616 **
45617 ** After this routine has been called, the sqlite3RowSetInsert()
45618 ** routine may not be called again.
45619 **
45620 ** This routine may not be called after sqlite3RowSetTest() has
45621 ** been used. Older versions of RowSet allowed that, but as the
45622 ** capability was not used by the code generator, it was removed
45623 ** for code economy.
45624 */
45625 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
45626 assert( p!=0 );
45627 assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
45628
45629 /* Merge the forest into a single sorted list on first call */
45630 if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45631 if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45632 p->pEntry = rowSetEntrySort(p->pEntry);
45633 }
45634 p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
45635 }
45636
45637 /* Return the next entry on the list */
45638 if( p->pEntry ){
45639 *pRowid = p->pEntry->v;
45640 p->pEntry = p->pEntry->pRight;
45641 if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
45642 /* Free memory immediately, rather than waiting on sqlite3_finalize() */
45643 sqlite3RowSetClear(p);
45644 }
45645 return 1;
45646 }else{
45647 return 0;
@@ -43786,17 +45660,19 @@
45660 struct RowSetEntry *p, *pTree;
45661
45662 /* This routine is never called after sqlite3RowSetNext() */
45663 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
45664
45665 /* Sort entries into the forest on the first test of a new batch.
45666 ** To save unnecessary work, only do this when the batch number changes.
45667 */
45668 if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
45669 p = pRowSet->pEntry;
45670 if( p ){
45671 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
45672 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45673 /* Only sort the current set of entiries if they need it */
45674 p = rowSetEntrySort(p);
45675 }
45676 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
45677 ppPrevTree = &pTree->pRight;
45678 if( pTree->pLeft==0 ){
@@ -44866,10 +46742,11 @@
46742 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
46743 ** is therefore not possible for an in-memory pager to enter the ERROR
46744 ** state.
46745 */
46746 if( MEMDB ){
46747 assert( !isOpen(p->fd) );
46748 assert( p->noSync );
46749 assert( p->journalMode==PAGER_JOURNALMODE_OFF
46750 || p->journalMode==PAGER_JOURNALMODE_MEMORY
46751 );
46752 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
@@ -44952,11 +46829,11 @@
46829 /* There must be at least one outstanding reference to the pager if
46830 ** in ERROR state. Otherwise the pager should have already dropped
46831 ** back to OPEN state.
46832 */
46833 assert( pPager->errCode!=SQLITE_OK );
46834 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
46835 break;
46836 }
46837
46838 return 1;
46839 }
@@ -45164,10 +47041,12 @@
47041 }
47042 }
47043
47044 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47045 }
47046 #else
47047 # define jrnlBufferSize(x) 0
47048 #endif
47049
47050 /*
47051 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47052 ** on the cache using a hash function. This is used for testing
@@ -45812,17 +47691,21 @@
47691 /* If Pager.errCode is set, the contents of the pager cache cannot be
47692 ** trusted. Now that there are no outstanding references to the pager,
47693 ** it can safely move back to PAGER_OPEN state. This happens in both
47694 ** normal and exclusive-locking mode.
47695 */
47696 assert( pPager->errCode==SQLITE_OK || !MEMDB );
47697 if( pPager->errCode ){
47698 if( pPager->tempFile==0 ){
47699 pager_reset(pPager);
47700 pPager->changeCountDone = 0;
47701 pPager->eState = PAGER_OPEN;
47702 }else{
47703 pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
47704 }
47705 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
47706 pPager->errCode = SQLITE_OK;
47707 }
47708
47709 pPager->journalOff = 0;
47710 pPager->journalHdr = 0;
47711 pPager->setMaster = 0;
@@ -45861,10 +47744,33 @@
47744 }
47745 return rc;
47746 }
47747
47748 static int pager_truncate(Pager *pPager, Pgno nPage);
47749
47750 /*
47751 ** The write transaction open on pPager is being committed (bCommit==1)
47752 ** or rolled back (bCommit==0).
47753 **
47754 ** Return TRUE if and only if all dirty pages should be flushed to disk.
47755 **
47756 ** Rules:
47757 **
47758 ** * For non-TEMP databases, always sync to disk. This is necessary
47759 ** for transactions to be durable.
47760 **
47761 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
47762 ** file has been created already (via a spill on pagerStress()) and
47763 ** when the number of dirty pages in memory exceeds 25% of the total
47764 ** cache size.
47765 */
47766 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
47767 if( pPager->tempFile==0 ) return 1;
47768 if( !bCommit ) return 0;
47769 if( !isOpen(pPager->fd) ) return 0;
47770 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
47771 }
47772
47773 /*
47774 ** This routine ends a transaction. A transaction is usually ended by
47775 ** either a COMMIT or a ROLLBACK operation. This routine may be called
47776 ** after rollback of a hot-journal, or if an error occurs while opening
@@ -45965,11 +47871,11 @@
47871 }
47872 pPager->journalOff = 0;
47873 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47874 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
47875 ){
47876 rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
47877 pPager->journalOff = 0;
47878 }else{
47879 /* This branch may be executed with Pager.journalMode==MEMORY if
47880 ** a hot-journal was just rolled back. In this case the journal
47881 ** file should be closed and deleted. If this connection writes to
@@ -46000,12 +47906,18 @@
47906 #endif
47907
47908 sqlite3BitvecDestroy(pPager->pInJournal);
47909 pPager->pInJournal = 0;
47910 pPager->nRec = 0;
47911 if( rc==SQLITE_OK ){
47912 if( pagerFlushOnCommit(pPager, bCommit) ){
47913 sqlite3PcacheCleanAll(pPager->pPCache);
47914 }else{
47915 sqlite3PcacheClearWritable(pPager->pPCache);
47916 }
47917 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
47918 }
47919
47920 if( pagerUseWal(pPager) ){
47921 /* Drop the WAL write-lock, if any. Also, if the connection was in
47922 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
47923 ** lock held on the database file.
@@ -46285,11 +48197,11 @@
48197 pPg = 0;
48198 }else{
48199 pPg = sqlite3PagerLookup(pPager, pgno);
48200 }
48201 assert( pPg || !MEMDB );
48202 assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48203 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48204 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48205 (isMainJrnl?"main-journal":"sub-journal")
48206 ));
48207 if( isMainJrnl ){
@@ -46335,11 +48247,10 @@
48247 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48248 rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48249 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48250 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48251 if( rc!=SQLITE_OK ) return rc;
 
48252 sqlite3PcacheMakeDirty(pPg);
48253 }
48254 if( pPg ){
48255 /* No page should ever be explicitly rolled back that is in use, except
48256 ** for page 1 which is held in use in order to keep the lock on the
@@ -46349,33 +48260,14 @@
48260 */
48261 void *pData;
48262 pData = pPg->pData;
48263 memcpy(pData, (u8*)aData, pPager->pageSize);
48264 pPager->xReiniter(pPg);
48265 /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
48266 ** that call was dangerous and had no detectable benefit since the cache
48267 ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48268 ** has been removed. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48269 pager_set_pagehash(pPg);
48270
48271 /* If this was page 1, then restore the value of Pager.dbFileVers.
48272 ** Do this before any decoding. */
48273 if( pgno==1 ){
@@ -47162,25 +49054,24 @@
49054 ** available from the WAL sub-system if the log file is empty or
49055 ** contains no valid committed transactions.
49056 */
49057 assert( pPager->eState==PAGER_OPEN );
49058 assert( pPager->eLock>=SHARED_LOCK );
49059 assert( isOpen(pPager->fd) );
49060 assert( pPager->tempFile==0 );
49061 nPage = sqlite3WalDbsize(pPager->pWal);
49062
49063 /* If the number of pages in the database is not available from the
49064 ** WAL sub-system, determine the page counte based on the size of
49065 ** the database file. If the size of the database file is not an
49066 ** integer multiple of the page-size, round up the result.
49067 */
49068 if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49069 i64 n = 0; /* Size of db file in bytes */
49070 int rc = sqlite3OsFileSize(pPager->fd, &n);
49071 if( rc!=SQLITE_OK ){
49072 return rc;
 
 
 
49073 }
49074 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49075 }
49076
49077 /* If the current number of pages in the file is greater than the
@@ -48252,12 +50143,13 @@
50143 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50144 int rc = SQLITE_OK; /* Return code */
50145
50146 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50147 assert( !pagerUseWal(pPager) );
50148 assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50149 assert( pPager->eLock==EXCLUSIVE_LOCK );
50150 assert( isOpen(pPager->fd) || pList->pDirty==0 );
50151
50152 /* If the file is a temp-file has not yet been opened, open it now. It
50153 ** is not possible for rc to be other than SQLITE_OK if this branch
50154 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50155 */
@@ -48921,10 +50813,11 @@
50813 */
50814 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
50815 if( rc==SQLITE_OK && !locked ){
50816 Pgno nPage; /* Number of pages in database file */
50817
50818 assert( pPager->tempFile==0 );
50819 rc = pagerPagecount(pPager, &nPage);
50820 if( rc==SQLITE_OK ){
50821 /* If the database is zero pages in size, that means that either (1) the
50822 ** journal is a remnant from a prior database with the same name where
50823 ** the database file but not the journal was deleted, or (2) the initial
@@ -49013,21 +50906,21 @@
50906 int rc = SQLITE_OK; /* Return code */
50907
50908 /* This routine is only called from b-tree and only when there are no
50909 ** outstanding pages. This implies that the pager state should either
50910 ** be OPEN or READER. READER is only possible if the pager is or was in
50911 ** exclusive access mode. */
 
50912 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
50913 assert( assert_pager_state(pPager) );
50914 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
50915 assert( pPager->errCode==SQLITE_OK );
50916
50917 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
50918 int bHotJournal = 1; /* True if there exists a hot journal-file */
50919
50920 assert( !MEMDB );
50921 assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
50922
50923 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
50924 if( rc!=SQLITE_OK ){
50925 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
50926 goto failed;
@@ -49109,11 +51002,11 @@
51002 */
51003 if( isOpen(pPager->jfd) ){
51004 assert( rc==SQLITE_OK );
51005 rc = pagerSyncHotJournal(pPager);
51006 if( rc==SQLITE_OK ){
51007 rc = pager_playback(pPager, !pPager->tempFile);
51008 pPager->eState = PAGER_OPEN;
51009 }
51010 }else if( !pPager->exclusiveMode ){
51011 pagerUnlockDb(pPager, SHARED_LOCK);
51012 }
@@ -49205,11 +51098,11 @@
51098 if( pagerUseWal(pPager) ){
51099 assert( rc==SQLITE_OK );
51100 rc = pagerBeginReadTransaction(pPager);
51101 }
51102
51103 if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51104 rc = pagerPagecount(pPager, &pPager->dbSize);
51105 }
51106
51107 failed:
51108 if( rc!=SQLITE_OK ){
@@ -49338,11 +51231,11 @@
51231 rc = sqlite3OsFetch(pPager->fd,
51232 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51233 );
51234
51235 if( rc==SQLITE_OK && pData ){
51236 if( pPager->eState>PAGER_READER || pPager->tempFile ){
51237 pPg = sqlite3PagerLookup(pPager, pgno);
51238 }
51239 if( pPg==0 ){
51240 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51241 }else{
@@ -49405,11 +51298,12 @@
51298 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51299 rc = SQLITE_CORRUPT_BKPT;
51300 goto pager_acquire_err;
51301 }
51302
51303 assert( !isOpen(pPager->fd) || !MEMDB );
51304 if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51305 if( pgno>pPager->mxPgno ){
51306 rc = SQLITE_FULL;
51307 goto pager_acquire_err;
51308 }
51309 if( noContent ){
@@ -49547,28 +51441,28 @@
51441 /* Open the journal file if it is not already open. */
51442 if( !isOpen(pPager->jfd) ){
51443 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51444 sqlite3MemJournalOpen(pPager->jfd);
51445 }else{
51446 int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51447 int nSpill;
 
 
 
 
51448
51449 if( pPager->tempFile ){
51450 flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51451 nSpill = sqlite3Config.nStmtSpill;
51452 }else{
51453 flags |= SQLITE_OPEN_MAIN_JOURNAL;
51454 nSpill = jrnlBufferSize(pPager);
51455 }
51456
51457 /* Verify that the database still has the same name as it did when
51458 ** it was originally opened. */
51459 rc = databaseIsUnmoved(pPager);
51460 if( rc==SQLITE_OK ){
51461 rc = sqlite3JournalOpen (
51462 pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
 
51463 );
 
 
 
51464 }
51465 }
51466 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51467 }
51468
@@ -49935,10 +51829,11 @@
51829 return pPager->errCode;
51830 }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
51831 if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
51832 return SQLITE_OK;
51833 }else if( pPager->sectorSize > (u32)pPager->pageSize ){
51834 assert( pPager->tempFile==0 );
51835 return pagerWriteLargeSector(pPg);
51836 }else{
51837 return pager_write(pPg);
51838 }
51839 }
@@ -49965,18 +51860,25 @@
51860 ** on the given page is unused. The pager marks the page as clean so
51861 ** that it does not get written to disk.
51862 **
51863 ** Tests show that this optimization can quadruple the speed of large
51864 ** DELETE operations.
51865 **
51866 ** This optimization cannot be used with a temp-file, as the page may
51867 ** have been dirty at the start of the transaction. In that case, if
51868 ** memory pressure forces page pPg out of the cache, the data does need
51869 ** to be written out to disk so that it may be read back in if the
51870 ** current transaction is rolled back.
51871 */
51872 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
51873 Pager *pPager = pPg->pPager;
51874 if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
51875 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
51876 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
51877 pPg->flags |= PGHDR_DONT_WRITE;
51878 pPg->flags &= ~PGHDR_WRITEABLE;
51879 testcase( pPg->flags & PGHDR_NEED_SYNC );
51880 pager_set_pagehash(pPg);
51881 }
51882 }
51883
51884 /*
@@ -50166,22 +52068,26 @@
52068 );
52069 assert( assert_pager_state(pPager) );
52070
52071 /* If a prior error occurred, report that error again. */
52072 if( NEVER(pPager->errCode) ) return pPager->errCode;
52073
52074 /* Provide the ability to easily simulate an I/O error during testing */
52075 if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52076
52077 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52078 pPager->zFilename, zMaster, pPager->dbSize));
52079
52080 /* If no database changes have been made, return early. */
52081 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52082
52083 assert( MEMDB==0 || pPager->tempFile );
52084 assert( isOpen(pPager->fd) || pPager->tempFile );
52085 if( 0==pagerFlushOnCommit(pPager, 1) ){
52086 /* If this is an in-memory db, or no pages have been written to, or this
52087 ** function has already been called, it is mostly a no-op. However, any
52088 ** backup in progress needs to be restarted. */
 
52089 sqlite3BackupRestart(pPager->pBackup);
52090 }else{
52091 if( pagerUseWal(pPager) ){
52092 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52093 PgHdr *pPageOne = 0;
@@ -50516,14 +52422,14 @@
52422 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52423 }
52424 }
52425
52426 /*
52427 ** Return true if this is an in-memory or temp-file backed pager.
52428 */
52429 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
52430 return pPager->tempFile;
52431 }
52432
52433 /*
52434 ** Check that there are at least nSavepoint savepoints open. If there are
52435 ** currently less than nSavepoints open, then open one or more savepoints
@@ -50799,11 +52705,12 @@
52705 assert( assert_pager_state(pPager) );
52706
52707 /* In order to be able to rollback, an in-memory database must journal
52708 ** the page we are moving from.
52709 */
52710 assert( pPager->tempFile || !MEMDB );
52711 if( pPager->tempFile ){
52712 rc = sqlite3PagerWrite(pPg);
52713 if( rc ) return rc;
52714 }
52715
52716 /* If the page being moved is dirty and has not been saved by the latest
@@ -50856,11 +52763,11 @@
52763 pPg->flags &= ~PGHDR_NEED_SYNC;
52764 pPgOld = sqlite3PagerLookup(pPager, pgno);
52765 assert( !pPgOld || pPgOld->nRef==1 );
52766 if( pPgOld ){
52767 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
52768 if( pPager->tempFile ){
52769 /* Do not discard pages from an in-memory database since we might
52770 ** need to rollback later. Just move the page out of the way. */
52771 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
52772 }else{
52773 sqlite3PcacheDrop(pPgOld);
@@ -50873,12 +52780,11 @@
52780
52781 /* For an in-memory database, make sure the original page continues
52782 ** to exist, in case the transaction needs to roll back. Use pPgOld
52783 ** as the original page since it has already been allocated.
52784 */
52785 if( pPager->tempFile && pPgOld ){
 
52786 sqlite3PcacheMove(pPgOld, origPgno);
52787 sqlite3PagerUnrefNotNull(pPgOld);
52788 }
52789
52790 if( needSyncPgno ){
@@ -51126,11 +53032,12 @@
53032 #ifndef SQLITE_OMIT_VACUUM
53033 /*
53034 ** Unless this is an in-memory or temporary database, clear the pager cache.
53035 */
53036 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
53037 assert( MEMDB==0 || pPager->tempFile );
53038 if( pPager->tempFile==0 ) pager_reset(pPager);
53039 }
53040 #endif
53041
53042 #ifndef SQLITE_OMIT_WAL
53043 /*
@@ -51305,10 +53212,11 @@
53212 if( rc==SQLITE_OK ){
53213 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53214 pPager->pageSize, (u8*)pPager->pTmpSpace);
53215 pPager->pWal = 0;
53216 pagerFixMaplimit(pPager);
53217 if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53218 }
53219 }
53220 return rc;
53221 }
53222
@@ -54760,10 +56668,27 @@
56668 /* Try to open on pSnapshot when the next read-transaction starts
56669 */
56670 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
56671 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
56672 }
56673
56674 /*
56675 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
56676 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
56677 */
56678 SQLITE_API int SQLITE_STDCALL sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
56679 WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
56680 WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
56681
56682 /* aSalt[0] is a copy of the value stored in the wal file header. It
56683 ** is incremented each time the wal file is restarted. */
56684 if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
56685 if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
56686 if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
56687 if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
56688 return 0;
56689 }
56690 #endif /* SQLITE_ENABLE_SNAPSHOT */
56691
56692 #ifdef SQLITE_ENABLE_ZIPVFS
56693 /*
56694 ** If the argument is not NULL, it points to a Wal object that holds a
@@ -57475,15 +59400,15 @@
59400 flagByte &= ~PTF_LEAF;
59401 pPage->childPtrSize = 4-4*pPage->leaf;
59402 pPage->xCellSize = cellSizePtr;
59403 pBt = pPage->pBt;
59404 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59405 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59406 ** interior table b-tree page. */
59407 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59408 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59409 ** leaf table b-tree page. */
59410 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59411 pPage->intKey = 1;
59412 if( pPage->leaf ){
59413 pPage->intKeyLeaf = 1;
59414 pPage->xParseCell = btreeParseCellPtr;
@@ -57493,15 +59418,15 @@
59418 pPage->xParseCell = btreeParseCellPtrNoPayload;
59419 }
59420 pPage->maxLocal = pBt->maxLeaf;
59421 pPage->minLocal = pBt->minLeaf;
59422 }else if( flagByte==PTF_ZERODATA ){
59423 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59424 ** interior index b-tree page. */
59425 assert( (PTF_ZERODATA)==2 );
59426 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59427 ** leaf index b-tree page. */
59428 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59429 pPage->intKey = 0;
59430 pPage->intKeyLeaf = 0;
59431 pPage->xParseCell = btreeParseCellPtrIndex;
59432 pPage->maxLocal = pBt->maxLocal;
@@ -62344,12 +64269,12 @@
64269 for(i=iFirst; i<iEnd; i++){
64270 int sz, rc;
64271 u8 *pSlot;
64272 sz = cachedCellSize(pCArray, i);
64273 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64274 if( (pData - pBegin)<sz ) return 1;
64275 pData -= sz;
 
64276 pSlot = pData;
64277 }
64278 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64279 ** database. But they might for a corrupt database. Hence use memmove()
64280 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
@@ -62507,11 +64432,11 @@
64432
64433 #ifdef SQLITE_DEBUG
64434 for(i=0; i<nNew && !CORRUPT_DB; i++){
64435 u8 *pCell = pCArray->apCell[i+iNew];
64436 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64437 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64438 pCell = &pTmp[pCell - aData];
64439 }
64440 assert( 0==memcmp(pCell, &aData[iOff],
64441 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64442 }
@@ -63938,10 +65863,32 @@
65863
65864 iCellDepth = pCur->iPage;
65865 iCellIdx = pCur->aiIdx[iCellDepth];
65866 pPage = pCur->apPage[iCellDepth];
65867 pCell = findCell(pPage, iCellIdx);
65868
65869 /* If the bPreserve flag is set to true, then the cursor position must
65870 ** be preserved following this delete operation. If the current delete
65871 ** will cause a b-tree rebalance, then this is done by saving the cursor
65872 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
65873 ** returning.
65874 **
65875 ** Or, if the current delete will not cause a rebalance, then the cursor
65876 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
65877 ** before or after the deleted entry. In this case set bSkipnext to true. */
65878 if( bPreserve ){
65879 if( !pPage->leaf
65880 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
65881 ){
65882 /* A b-tree rebalance will be required after deleting this entry.
65883 ** Save the cursor key. */
65884 rc = saveCursorKey(pCur);
65885 if( rc ) return rc;
65886 }else{
65887 bSkipnext = 1;
65888 }
65889 }
65890
65891 /* If the page containing the entry to delete is not a leaf page, move
65892 ** the cursor to the largest entry in the tree that is smaller than
65893 ** the entry being deleted. This cell will replace the cell being deleted
65894 ** from the internal node. The 'previous' entry is used for this instead
@@ -63965,32 +65912,10 @@
65912 ** invalidate any incrblob cursors open on the row being deleted. */
65913 if( pCur->pKeyInfo==0 ){
65914 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
65915 }
65916
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65917 /* Make the page containing the entry to be deleted writable. Then free any
65918 ** overflow pages associated with the entry and finally remove the cell
65919 ** itself from within the page. */
65920 rc = sqlite3PagerWrite(pPage->pDbPage);
65921 if( rc ) return rc;
@@ -67111,14 +69036,10 @@
69036 ** freed before the copy is made.
69037 */
69038 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69039 int rc = SQLITE_OK;
69040
 
 
 
 
69041 assert( (pFrom->flags & MEM_RowSet)==0 );
69042 if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
69043 memcpy(pTo, pFrom, MEMCELLSIZE);
69044 pTo->flags &= ~MEM_Dyn;
69045 if( pTo->flags&(MEM_Str|MEM_Blob) ){
@@ -68102,10 +70023,11 @@
70023 ** Swap all content between two VDBE structures.
70024 */
70025 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
70026 Vdbe tmp, *pTmp;
70027 char *zTmp;
70028 assert( pA->db==pB->db );
70029 tmp = *pA;
70030 *pA = *pB;
70031 *pB = tmp;
70032 pTmp = pA->pNext;
70033 pA->pNext = pB->pNext;
@@ -68568,77 +70490,88 @@
70490 ** indicate what the prepared statement actually does.
70491 **
70492 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
70493 **
70494 ** (5) Reclaim the memory allocated for storing labels.
70495 **
70496 ** This routine will only function correctly if the mkopcodeh.tcl generator
70497 ** script numbers the opcodes correctly. Changes to this routine must be
70498 ** coordinated with changes to mkopcodeh.tcl.
70499 */
70500 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
 
70501 int nMaxArgs = *pMaxFuncArgs;
70502 Op *pOp;
70503 Parse *pParse = p->pParse;
70504 int *aLabel = pParse->aLabel;
70505 p->readOnly = 1;
70506 p->bIsReader = 0;
70507 pOp = &p->aOp[p->nOp-1];
70508 while(1){
70509
70510 /* Only JUMP opcodes and the short list of special opcodes in the switch
70511 ** below need to be considered. The mkopcodeh.tcl generator script groups
70512 ** all these opcodes together near the front of the opcode list. Skip
70513 ** any opcode that does not need processing by virtual of the fact that
70514 ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70515 */
70516 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70517 /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70518 ** cases from this switch! */
70519 switch( pOp->opcode ){
70520 case OP_Transaction: {
70521 if( pOp->p2!=0 ) p->readOnly = 0;
70522 /* fall thru */
70523 }
70524 case OP_AutoCommit:
70525 case OP_Savepoint: {
70526 p->bIsReader = 1;
70527 break;
70528 }
70529 #ifndef SQLITE_OMIT_WAL
70530 case OP_Checkpoint:
70531 #endif
70532 case OP_Vacuum:
70533 case OP_JournalMode: {
70534 p->readOnly = 0;
70535 p->bIsReader = 1;
70536 break;
70537 }
70538 #ifndef SQLITE_OMIT_VIRTUALTABLE
70539 case OP_VUpdate: {
70540 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70541 break;
70542 }
70543 case OP_VFilter: {
70544 int n;
70545 assert( (pOp - p->aOp) >= 3 );
70546 assert( pOp[-1].opcode==OP_Integer );
70547 n = pOp[-1].p1;
70548 if( n>nMaxArgs ) nMaxArgs = n;
70549 break;
70550 }
70551 #endif
70552 case OP_Next:
70553 case OP_NextIfOpen:
70554 case OP_SorterNext: {
70555 pOp->p4.xAdvance = sqlite3BtreeNext;
70556 pOp->p4type = P4_ADVANCE;
70557 break;
70558 }
70559 case OP_Prev:
70560 case OP_PrevIfOpen: {
70561 pOp->p4.xAdvance = sqlite3BtreePrevious;
70562 pOp->p4type = P4_ADVANCE;
70563 break;
70564 }
70565 }
70566 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70567 assert( ADDR(pOp->p2)<pParse->nLabel );
70568 pOp->p2 = aLabel[ADDR(pOp->p2)];
70569 }
70570 }
70571 if( pOp==p->aOp ) break;
70572 pOp--;
70573 }
70574 sqlite3DbFree(p->db, pParse->aLabel);
70575 pParse->aLabel = 0;
70576 pParse->nLabel = 0;
70577 *pMaxFuncArgs = nMaxArgs;
@@ -68814,56 +70747,54 @@
70747
70748 /*
70749 ** Delete a P4 value if necessary.
70750 */
70751 static void freeP4(sqlite3 *db, int p4type, void *p4){
70752 assert( db );
70753 switch( p4type ){
70754 case P4_FUNCCTX: {
70755 freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
70756 /* Fall through into the next case */
70757 }
70758 case P4_REAL:
70759 case P4_INT64:
70760 case P4_DYNAMIC:
70761 case P4_INTARRAY: {
70762 sqlite3DbFree(db, p4);
70763 break;
70764 }
70765 case P4_KEYINFO: {
70766 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
70767 break;
70768 }
 
70769 #ifdef SQLITE_ENABLE_CURSOR_HINTS
70770 case P4_EXPR: {
70771 sqlite3ExprDelete(db, (Expr*)p4);
70772 break;
70773 }
70774 #endif
70775 case P4_MPRINTF: {
70776 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
70777 break;
70778 }
70779 case P4_FUNCDEF: {
70780 freeEphemeralFunction(db, (FuncDef*)p4);
70781 break;
70782 }
70783 case P4_MEM: {
70784 if( db->pnBytesFreed==0 ){
70785 sqlite3ValueFree((sqlite3_value*)p4);
70786 }else{
70787 Mem *p = (Mem*)p4;
70788 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
70789 sqlite3DbFree(db, p);
70790 }
70791 break;
70792 }
70793 case P4_VTAB : {
70794 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
70795 break;
 
70796 }
70797 }
70798 }
70799
70800 /*
@@ -69340,10 +71271,14 @@
71271 break;
71272 }
71273 case P4_ADVANCE: {
71274 zTemp[0] = 0;
71275 break;
71276 }
71277 case P4_TABLE: {
71278 sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71279 break;
71280 }
71281 default: {
71282 zP4 = pOp->p4.z;
71283 if( zP4==0 ){
71284 zP4 = zTemp;
@@ -71531,10 +73466,11 @@
73466 idx += getVarint32(&aKey[idx], serial_type);
73467 pMem->enc = pKeyInfo->enc;
73468 pMem->db = pKeyInfo->db;
73469 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
73470 pMem->szMalloc = 0;
73471 pMem->z = 0;
73472 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
73473 pMem++;
73474 if( (++u)>=p->nField ) break;
73475 }
73476 assert( u<=pKeyInfo->nField + 1 );
@@ -72511,10 +74447,94 @@
74447 pVtab->zErrMsg = 0;
74448 }
74449 }
74450 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74451
74452 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74453
74454 /*
74455 ** If the second argument is not NULL, release any allocations associated
74456 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74457 ** structure itself, using sqlite3DbFree().
74458 **
74459 ** This function is used to free UnpackedRecord structures allocated by
74460 ** the vdbeUnpackRecord() function found in vdbeapi.c.
74461 */
74462 static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74463 if( p ){
74464 int i;
74465 for(i=0; i<p->nField; i++){
74466 Mem *pMem = &p->aMem[i];
74467 if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74468 }
74469 sqlite3DbFree(db, p);
74470 }
74471 }
74472 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74473
74474 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74475 /*
74476 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74477 ** then cursor passed as the second argument should point to the row about
74478 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74479 ** the required value will be read from the row the cursor points to.
74480 */
74481 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74482 Vdbe *v, /* Vdbe pre-update hook is invoked by */
74483 VdbeCursor *pCsr, /* Cursor to grab old.* values from */
74484 int op, /* SQLITE_INSERT, UPDATE or DELETE */
74485 const char *zDb, /* Database name */
74486 Table *pTab, /* Modified table */
74487 i64 iKey1, /* Initial key value */
74488 int iReg /* Register for new.* record */
74489 ){
74490 sqlite3 *db = v->db;
74491 i64 iKey2;
74492 PreUpdate preupdate;
74493 const char *zTbl = pTab->zName;
74494 static const u8 fakeSortOrder = 0;
74495
74496 assert( db->pPreUpdate==0 );
74497 memset(&preupdate, 0, sizeof(PreUpdate));
74498 if( op==SQLITE_UPDATE ){
74499 iKey2 = v->aMem[iReg].u.i;
74500 }else{
74501 iKey2 = iKey1;
74502 }
74503
74504 assert( pCsr->nField==pTab->nCol
74505 || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74506 );
74507
74508 preupdate.v = v;
74509 preupdate.pCsr = pCsr;
74510 preupdate.op = op;
74511 preupdate.iNewReg = iReg;
74512 preupdate.keyinfo.db = db;
74513 preupdate.keyinfo.enc = ENC(db);
74514 preupdate.keyinfo.nField = pTab->nCol;
74515 preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74516 preupdate.iKey1 = iKey1;
74517 preupdate.iKey2 = iKey2;
74518 preupdate.iPKey = pTab->iPKey;
74519
74520 db->pPreUpdate = &preupdate;
74521 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74522 db->pPreUpdate = 0;
74523 sqlite3DbFree(db, preupdate.aRecord);
74524 vdbeFreeUnpacked(db, preupdate.pUnpacked);
74525 vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74526 if( preupdate.aNew ){
74527 int i;
74528 for(i=0; i<pCsr->nField; i++){
74529 sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74530 }
74531 sqlite3DbFree(db, preupdate.aNew);
74532 }
74533 }
74534 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74535
74536 /************** End of vdbeaux.c *********************************************/
74537 /************** Begin file vdbeapi.c *****************************************/
74538 /*
74539 ** 2004 May 26
74540 **
@@ -74119,10 +76139,191 @@
76139 v = pVdbe->aCounter[op];
76140 if( resetFlag ) pVdbe->aCounter[op] = 0;
76141 return (int)v;
76142 }
76143
76144 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76145 /*
76146 ** Allocate and populate an UnpackedRecord structure based on the serialized
76147 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76148 ** if successful, or a NULL pointer if an OOM error is encountered.
76149 */
76150 static UnpackedRecord *vdbeUnpackRecord(
76151 KeyInfo *pKeyInfo,
76152 int nKey,
76153 const void *pKey
76154 ){
76155 char *dummy; /* Dummy argument for AllocUnpackedRecord() */
76156 UnpackedRecord *pRet; /* Return value */
76157
76158 pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76159 if( pRet ){
76160 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76161 sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76162 }
76163 return pRet;
76164 }
76165
76166 /*
76167 ** This function is called from within a pre-update callback to retrieve
76168 ** a field of the row currently being updated or deleted.
76169 */
76170 SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76171 PreUpdate *p = db->pPreUpdate;
76172 int rc = SQLITE_OK;
76173
76174 /* Test that this call is being made from within an SQLITE_DELETE or
76175 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76176 if( !p || p->op==SQLITE_INSERT ){
76177 rc = SQLITE_MISUSE_BKPT;
76178 goto preupdate_old_out;
76179 }
76180 if( iIdx>=p->pCsr->nField || iIdx<0 ){
76181 rc = SQLITE_RANGE;
76182 goto preupdate_old_out;
76183 }
76184
76185 /* If the old.* record has not yet been loaded into memory, do so now. */
76186 if( p->pUnpacked==0 ){
76187 u32 nRec;
76188 u8 *aRec;
76189
76190 rc = sqlite3BtreeDataSize(p->pCsr->uc.pCursor, &nRec);
76191 if( rc!=SQLITE_OK ) goto preupdate_old_out;
76192 aRec = sqlite3DbMallocRaw(db, nRec);
76193 if( !aRec ) goto preupdate_old_out;
76194 rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76195 if( rc==SQLITE_OK ){
76196 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76197 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76198 }
76199 if( rc!=SQLITE_OK ){
76200 sqlite3DbFree(db, aRec);
76201 goto preupdate_old_out;
76202 }
76203 p->aRecord = aRec;
76204 }
76205
76206 if( iIdx>=p->pUnpacked->nField ){
76207 *ppValue = (sqlite3_value *)columnNullValue();
76208 }else{
76209 *ppValue = &p->pUnpacked->aMem[iIdx];
76210 if( iIdx==p->iPKey ){
76211 sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76212 }
76213 }
76214
76215 preupdate_old_out:
76216 sqlite3Error(db, rc);
76217 return sqlite3ApiExit(db, rc);
76218 }
76219 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76220
76221 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76222 /*
76223 ** This function is called from within a pre-update callback to retrieve
76224 ** the number of columns in the row being updated, deleted or inserted.
76225 */
76226 SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *db){
76227 PreUpdate *p = db->pPreUpdate;
76228 return (p ? p->keyinfo.nField : 0);
76229 }
76230 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76231
76232 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76233 /*
76234 ** This function is designed to be called from within a pre-update callback
76235 ** only. It returns zero if the change that caused the callback was made
76236 ** immediately by a user SQL statement. Or, if the change was made by a
76237 ** trigger program, it returns the number of trigger programs currently
76238 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76239 ** top-level trigger etc.).
76240 **
76241 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76242 ** or SET DEFAULT action is considered a trigger.
76243 */
76244 SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *db){
76245 PreUpdate *p = db->pPreUpdate;
76246 return (p ? p->v->nFrame : 0);
76247 }
76248 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76249
76250 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76251 /*
76252 ** This function is called from within a pre-update callback to retrieve
76253 ** a field of the row currently being updated or inserted.
76254 */
76255 SQLITE_API int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76256 PreUpdate *p = db->pPreUpdate;
76257 int rc = SQLITE_OK;
76258 Mem *pMem;
76259
76260 if( !p || p->op==SQLITE_DELETE ){
76261 rc = SQLITE_MISUSE_BKPT;
76262 goto preupdate_new_out;
76263 }
76264 if( iIdx>=p->pCsr->nField || iIdx<0 ){
76265 rc = SQLITE_RANGE;
76266 goto preupdate_new_out;
76267 }
76268
76269 if( p->op==SQLITE_INSERT ){
76270 /* For an INSERT, memory cell p->iNewReg contains the serialized record
76271 ** that is being inserted. Deserialize it. */
76272 UnpackedRecord *pUnpack = p->pNewUnpacked;
76273 if( !pUnpack ){
76274 Mem *pData = &p->v->aMem[p->iNewReg];
76275 rc = sqlite3VdbeMemExpandBlob(pData);
76276 if( rc!=SQLITE_OK ) goto preupdate_new_out;
76277 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76278 if( !pUnpack ){
76279 rc = SQLITE_NOMEM;
76280 goto preupdate_new_out;
76281 }
76282 p->pNewUnpacked = pUnpack;
76283 }
76284 if( iIdx>=pUnpack->nField ){
76285 pMem = (sqlite3_value *)columnNullValue();
76286 }else{
76287 pMem = &pUnpack->aMem[iIdx];
76288 if( iIdx==p->iPKey ){
76289 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76290 }
76291 }
76292 }else{
76293 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76294 ** value. Make a copy of the cell contents and return a pointer to it.
76295 ** It is not safe to return a pointer to the memory cell itself as the
76296 ** caller may modify the value text encoding.
76297 */
76298 assert( p->op==SQLITE_UPDATE );
76299 if( !p->aNew ){
76300 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76301 if( !p->aNew ){
76302 rc = SQLITE_NOMEM;
76303 goto preupdate_new_out;
76304 }
76305 }
76306 assert( iIdx>=0 && iIdx<p->pCsr->nField );
76307 pMem = &p->aNew[iIdx];
76308 if( pMem->flags==0 ){
76309 if( iIdx==p->iPKey ){
76310 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76311 }else{
76312 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76313 if( rc!=SQLITE_OK ) goto preupdate_new_out;
76314 }
76315 }
76316 }
76317 *ppValue = pMem;
76318
76319 preupdate_new_out:
76320 sqlite3Error(db, rc);
76321 return sqlite3ApiExit(db, rc);
76322 }
76323 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76324
76325 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76326 /*
76327 ** Return status data for a single loop within query pStmt.
76328 */
76329 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
@@ -74469,10 +76670,20 @@
76670 sqlite3_max_blobsize = p->n;
76671 }
76672 }
76673 #endif
76674
76675 /*
76676 ** This macro evaluates to true if either the update hook or the preupdate
76677 ** hook are enabled for database connect DB.
76678 */
76679 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76680 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
76681 #else
76682 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
76683 #endif
76684
76685 /*
76686 ** The next global variable is incremented each time the OP_Found opcode
76687 ** is executed. This is used to test whether or not the foreign key
76688 ** operation implemented using OP_FkIsZero is working. This variable
76689 ** has no function other than to help verify the correct operation of the
@@ -74588,11 +76799,11 @@
76799 nByte =
76800 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
76801 (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
76802
76803 assert( iCur>=0 && iCur<p->nCursor );
76804 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
76805 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
76806 p->apCsr[iCur] = 0;
76807 }
76808 if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
76809 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
@@ -74665,24 +76876,27 @@
76876 u8 enc /* Use this text encoding */
76877 ){
76878 if( affinity>=SQLITE_AFF_NUMERIC ){
76879 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
76880 || affinity==SQLITE_AFF_NUMERIC );
76881 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
76882 if( (pRec->flags & MEM_Real)==0 ){
76883 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
76884 }else{
76885 sqlite3VdbeIntegerAffinity(pRec);
76886 }
76887 }
76888 }else if( affinity==SQLITE_AFF_TEXT ){
76889 /* Only attempt the conversion to TEXT if there is an integer or real
76890 ** representation (blob and NULL do not get converted) but no string
76891 ** representation. It would be harmless to repeat the conversion if
76892 ** there is already a string rep, but it is pointless to waste those
76893 ** CPU cycles. */
76894 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
76895 if( (pRec->flags&(MEM_Real|MEM_Int)) ){
76896 sqlite3VdbeMemStringify(pRec, enc, 1);
76897 }
76898 }
76899 pRec->flags &= ~(MEM_Real|MEM_Int);
76900 }
76901 }
76902
@@ -75004,11 +77218,11 @@
77218 Mem *pOut;
77219 assert( pOp->p2>0 );
77220 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77221 pOut = &p->aMem[pOp->p2];
77222 memAboutToChange(p, pOut);
77223 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77224 return out2PrereleaseWithClear(pOut);
77225 }else{
77226 pOut->flags = MEM_Int;
77227 return pOut;
77228 }
@@ -75136,41 +77350,43 @@
77350 }
77351 #endif
77352
77353 /* Sanity checking on other operands */
77354 #ifdef SQLITE_DEBUG
77355 {
77356 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77357 if( (opProperty & OPFLG_IN1)!=0 ){
77358 assert( pOp->p1>0 );
77359 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77360 assert( memIsValid(&aMem[pOp->p1]) );
77361 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77362 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77363 }
77364 if( (opProperty & OPFLG_IN2)!=0 ){
77365 assert( pOp->p2>0 );
77366 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77367 assert( memIsValid(&aMem[pOp->p2]) );
77368 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77369 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77370 }
77371 if( (opProperty & OPFLG_IN3)!=0 ){
77372 assert( pOp->p3>0 );
77373 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77374 assert( memIsValid(&aMem[pOp->p3]) );
77375 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77376 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77377 }
77378 if( (opProperty & OPFLG_OUT2)!=0 ){
77379 assert( pOp->p2>0 );
77380 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77381 memAboutToChange(p, &aMem[pOp->p2]);
77382 }
77383 if( (opProperty & OPFLG_OUT3)!=0 ){
77384 assert( pOp->p3>0 );
77385 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77386 memAboutToChange(p, &aMem[pOp->p3]);
77387 }
77388 }
77389 #endif
77390 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77391 pOrigOp = pOp;
77392 #endif
@@ -75406,12 +77622,10 @@
77622 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
77623 ** every program. So a jump past the last instruction of the program
77624 ** is the same as executing Halt.
77625 */
77626 case OP_Halt: {
 
 
77627 VdbeFrame *pFrame;
77628 int pcx;
77629
77630 pcx = (int)(pOp - aOp);
77631 if( pOp->p1==SQLITE_OK && p->pFrame ){
@@ -75436,38 +77650,32 @@
77650 break;
77651 }
77652 p->rc = pOp->p1;
77653 p->errorAction = (u8)pOp->p2;
77654 p->pc = pcx;
77655 assert( pOp->p5>=0 && pOp->p5<=4 );
77656 if( p->rc ){
77657 if( pOp->p5 ){
77658 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
77659 "FOREIGN KEY" };
 
77660 testcase( pOp->p5==1 );
77661 testcase( pOp->p5==2 );
77662 testcase( pOp->p5==3 );
77663 testcase( pOp->p5==4 );
77664 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
77665 if( pOp->p4.z ){
77666 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
77667 }
77668 }else{
 
 
 
 
 
 
 
77669 sqlite3VdbeError(p, "%s", pOp->p4.z);
 
 
77670 }
77671 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
77672 }
77673 rc = sqlite3VdbeHalt(p);
77674 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
77675 if( rc==SQLITE_BUSY ){
77676 p->rc = SQLITE_BUSY;
77677 }else{
77678 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
77679 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
77680 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
77681 }
@@ -75529,14 +77737,11 @@
77737 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
77738
77739 #ifndef SQLITE_OMIT_UTF16
77740 if( encoding!=SQLITE_UTF8 ){
77741 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
77742 assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
 
 
 
77743 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
77744 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
77745 assert( VdbeMemDynamic(pOut)==0 );
77746 pOut->szMalloc = 0;
77747 pOut->flags |= MEM_Static;
@@ -75545,26 +77750,30 @@
77750 }
77751 pOp->p4type = P4_DYNAMIC;
77752 pOp->p4.z = pOut->z;
77753 pOp->p1 = pOut->n;
77754 }
77755 testcase( rc==SQLITE_TOOBIG );
77756 #endif
77757 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77758 goto too_big;
77759 }
77760 assert( rc==SQLITE_OK );
77761 /* Fall through to the next case, OP_String */
77762 }
77763
77764 /* Opcode: String P1 P2 P3 P4 P5
77765 ** Synopsis: r[P2]='P4' (len=P1)
77766 **
77767 ** The string value P4 of length P1 (bytes) is stored in register P2.
77768 **
77769 ** If P3 is not zero and the content of register P3 is equal to P5, then
77770 ** the datatype of the register P2 is converted to BLOB. The content is
77771 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
77772 ** of a string, as if it had been CAST. In other words:
77773 **
77774 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
77775 */
77776 case OP_String: { /* out2 */
77777 assert( pOp->p4.z!=0 );
77778 pOut = out2Prerelease(p, pOp);
77779 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
@@ -75571,16 +77780,15 @@
77780 pOut->z = pOp->p4.z;
77781 pOut->n = pOp->p1;
77782 pOut->enc = encoding;
77783 UPDATE_MAX_BLOBSIZE(pOut);
77784 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
77785 if( pOp->p3>0 ){
 
77786 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77787 pIn3 = &aMem[pOp->p3];
77788 assert( pIn3->flags & MEM_Int );
77789 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
77790 }
77791 #endif
77792 break;
77793 }
77794
@@ -76478,15 +78686,17 @@
78686 }
78687 }else{
78688 /* Neither operand is NULL. Do a comparison. */
78689 affinity = pOp->p5 & SQLITE_AFF_MASK;
78690 if( affinity>=SQLITE_AFF_NUMERIC ){
78691 if( (flags1 | flags3)&MEM_Str ){
78692 if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78693 applyNumericAffinity(pIn1,0);
78694 }
78695 if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78696 applyNumericAffinity(pIn3,0);
78697 }
78698 }
78699 }else if( affinity==SQLITE_AFF_TEXT ){
78700 if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
78701 testcase( pIn1->flags & MEM_Int );
78702 testcase( pIn1->flags & MEM_Real );
@@ -77215,11 +79425,13 @@
79425 }
79426 nData += len;
79427 testcase( serial_type==127 );
79428 testcase( serial_type==128 );
79429 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
79430 if( pRec==pData0 ) break;
79431 pRec--;
79432 }while(1);
79433
79434 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
79435 ** which determines the total number of bytes in the header. The varint
79436 ** value is the size of the header in bytes including the size varint
79437 ** itself. */
@@ -77363,11 +79575,11 @@
79575 db->autoCommit = 0;
79576 db->isTransactionSavepoint = 1;
79577 }else{
79578 db->nSavepoint++;
79579 }
79580
79581 /* Link the new savepoint into the database handle's list. */
79582 pNew->pNext = db->pSavepoint;
79583 db->pSavepoint = pNew;
79584 pNew->nDeferredCons = db->nDeferredCons;
79585 pNew->nDeferredImmCons = db->nDeferredImmCons;
@@ -78720,13 +80932,13 @@
80932 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
80933 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
80934 ** is part of an INSERT operation. The difference is only important to
80935 ** the update hook.
80936 **
80937 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
80938 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
80939 ** following a successful insert.
80940 **
80941 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
80942 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
80943 ** and register P2 becomes ephemeral. If the cursor is changed, the
80944 ** value of register P2 will then change. Make sure this does not
@@ -78748,21 +80960,23 @@
80960 i64 iKey; /* The integer ROWID or key for the record to be inserted */
80961 VdbeCursor *pC; /* Cursor to table into which insert is written */
80962 int nZero; /* Number of zero-bytes to append */
80963 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
80964 const char *zDb; /* database name - used by the update hook */
80965 Table *pTab; /* Table structure - used by update and pre-update hooks */
80966 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
80967
80968 op = 0;
80969 pData = &aMem[pOp->p2];
80970 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80971 assert( memIsValid(pData) );
80972 pC = p->apCsr[pOp->p1];
80973 assert( pC!=0 );
80974 assert( pC->eCurType==CURTYPE_BTREE );
80975 assert( pC->uc.pCursor!=0 );
80976 assert( pC->isTable );
80977 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
80978 REGISTER_TRACE(pOp->p2, pData);
80979
80980 if( pOp->opcode==OP_Insert ){
80981 pKey = &aMem[pOp->p3];
80982 assert( pKey->flags & MEM_Int );
@@ -78771,10 +80985,32 @@
80985 iKey = pKey->u.i;
80986 }else{
80987 assert( pOp->opcode==OP_InsertInt );
80988 iKey = pOp->p3;
80989 }
80990
80991 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
80992 assert( pC->isTable );
80993 assert( pC->iDb>=0 );
80994 zDb = db->aDb[pC->iDb].zName;
80995 pTab = pOp->p4.pTab;
80996 assert( HasRowid(pTab) );
80997 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
80998 }else{
80999 pTab = 0; /* Not needed. Silence a comiler warning. */
81000 zDb = 0; /* Not needed. Silence a compiler warning. */
81001 }
81002
81003 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81004 /* Invoke the pre-update hook, if any */
81005 if( db->xPreUpdateCallback
81006 && pOp->p4type==P4_TABLE
81007 && !(pOp->p5 & OPFLAG_ISUPDATE)
81008 ){
81009 sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, iKey, pOp->p2);
81010 }
81011 #endif
81012
81013 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81014 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
81015 if( pData->flags & MEM_Null ){
81016 pData->z = 0;
@@ -78795,22 +81031,17 @@
81031 pC->deferredMoveto = 0;
81032 pC->cacheStatus = CACHE_STALE;
81033
81034 /* Invoke the update-hook if required. */
81035 if( rc ) goto abort_due_to_error;
81036 if( db->xUpdateCallback && op ){
81037 db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, iKey);
 
 
 
 
 
81038 }
81039 break;
81040 }
81041
81042 /* Opcode: Delete P1 P2 P3 P4 P5
81043 **
81044 ** Delete the record at which the P1 cursor is currently pointing.
81045 **
81046 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81047 ** the cursor will be left pointing at either the next or the previous
@@ -78830,42 +81061,77 @@
81061 ** change count is incremented (otherwise not).
81062 **
81063 ** P1 must not be pseudo-table. It has to be a real table with
81064 ** multiple rows.
81065 **
81066 ** If P4 is not NULL then it points to a Table struture. In this case either
81067 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81068 ** have been positioned using OP_NotFound prior to invoking this opcode in
81069 ** this case. Specifically, if one is configured, the pre-update hook is
81070 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81071 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81072 **
81073 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81074 ** of the memory cell that contains the value that the rowid of the row will
81075 ** be set to by the update.
81076 */
81077 case OP_Delete: {
81078 VdbeCursor *pC;
81079 const char *zDb;
81080 Table *pTab;
81081 int opflags;
81082
81083 opflags = pOp->p2;
81084 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81085 pC = p->apCsr[pOp->p1];
81086 assert( pC!=0 );
81087 assert( pC->eCurType==CURTYPE_BTREE );
81088 assert( pC->uc.pCursor!=0 );
81089 assert( pC->deferredMoveto==0 );
81090
 
 
 
 
 
81091 #ifdef SQLITE_DEBUG
81092 if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81093 /* If p5 is zero, the seek operation that positioned the cursor prior to
81094 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81095 ** the row that is being deleted */
81096 i64 iKey = 0;
81097 sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
81098 assert( pC->movetoTarget==iKey );
81099 }
81100 #endif
81101
81102 /* If the update-hook or pre-update-hook will be invoked, set zDb to
81103 ** the name of the db to pass as to it. Also set local pTab to a copy
81104 ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81105 ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81106 ** VdbeCursor.movetoTarget to the current rowid. */
81107 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81108 assert( pC->iDb>=0 );
81109 assert( pOp->p4.pTab!=0 );
81110 zDb = db->aDb[pC->iDb].zName;
81111 pTab = pOp->p4.pTab;
81112 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81113 sqlite3BtreeKeySize(pC->uc.pCursor, &pC->movetoTarget);
81114 }
81115 }else{
81116 zDb = 0; /* Not needed. Silence a compiler warning. */
81117 pTab = 0; /* Not needed. Silence a compiler warning. */
81118 }
81119
81120 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81121 /* Invoke the pre-update-hook if required. */
81122 if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81123 assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81124 sqlite3VdbePreUpdateHook(p, pC,
81125 (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81126 zDb, pTab, pC->movetoTarget,
81127 pOp->p3
81128 );
81129 }
81130 if( opflags & OPFLAG_ISNOOP ) break;
81131 #endif
81132
81133 /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81134 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81135 assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
81136 assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81137
@@ -78883,19 +81149,22 @@
81149 }
81150 #endif
81151
81152 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81153 pC->cacheStatus = CACHE_STALE;
81154 if( rc ) goto abort_due_to_error;
81155
81156 /* Invoke the update-hook if required. */
81157 if( opflags & OPFLAG_NCHANGE ){
81158 p->nChange++;
81159 if( db->xUpdateCallback && HasRowid(pTab) ){
81160 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81161 pC->movetoTarget);
81162 assert( pC->iDb>=0 );
81163 }
81164 }
81165
81166 break;
81167 }
81168 /* Opcode: ResetCount * * * * *
81169 **
81170 ** The value of the change counter is copied to the database handle
@@ -80371,25 +82640,10 @@
82640 if( pIn1->u.i==0 ) goto jump_to_p2;
82641 break;
82642 }
82643
82644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82645 /* Opcode: AggStep0 * P2 P3 P4 P5
82646 ** Synopsis: accum=r[P3] step(r[P2@P5])
82647 **
82648 ** Execute the step function for an aggregate. The
82649 ** function has P5 arguments. P4 is a pointer to the FuncDef
@@ -81278,15 +83532,16 @@
83532 #ifndef NDEBUG
83533 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
83534
83535 #ifdef SQLITE_DEBUG
83536 if( db->flags & SQLITE_VdbeTrace ){
83537 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
83538 if( rc!=0 ) printf("rc=%d\n",rc);
83539 if( opProperty & (OPFLG_OUT2) ){
83540 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
83541 }
83542 if( opProperty & OPFLG_OUT3 ){
83543 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
83544 }
83545 }
83546 #endif /* SQLITE_DEBUG */
83547 #endif /* NDEBUG */
@@ -81386,10 +83641,12 @@
83641 int iOffset; /* Byte offset of blob in cursor data */
83642 int iCol; /* Table column this handle is open on */
83643 BtCursor *pCsr; /* Cursor pointing at blob row */
83644 sqlite3_stmt *pStmt; /* Statement holding cursor open */
83645 sqlite3 *db; /* The associated database */
83646 char *zDb; /* Database name */
83647 Table *pTab; /* Table object */
83648 };
83649
83650
83651 /*
83652 ** This function is used by both blob_open() and blob_reopen(). It seeks
@@ -81529,10 +83786,12 @@
83786 }
83787 rc = SQLITE_ERROR;
83788 sqlite3BtreeLeaveAll(db);
83789 goto blob_open_out;
83790 }
83791 pBlob->pTab = pTab;
83792 pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
83793
83794 /* Now search pTab for the exact column. */
83795 for(iCol=0; iCol<pTab->nCol; iCol++) {
83796 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
83797 break;
@@ -81750,10 +84009,34 @@
84009 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84010 ** returned, clean-up the statement handle.
84011 */
84012 assert( db == v->db );
84013 sqlite3BtreeEnterCursor(p->pCsr);
84014
84015 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84016 if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84017 /* If a pre-update hook is registered and this is a write cursor,
84018 ** invoke it here.
84019 **
84020 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84021 ** operation should really be an SQLITE_UPDATE. This is probably
84022 ** incorrect, but is convenient because at this point the new.* values
84023 ** are not easily obtainable. And for the sessions module, an
84024 ** SQLITE_UPDATE where the PK columns do not change is handled in the
84025 ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84026 ** slightly more efficient). Since you cannot write to a PK column
84027 ** using the incremental-blob API, this works. For the sessions module
84028 ** anyhow.
84029 */
84030 sqlite3_int64 iKey;
84031 sqlite3BtreeKeySize(p->pCsr, &iKey);
84032 sqlite3VdbePreUpdateHook(
84033 v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84034 );
84035 }
84036 #endif
84037
84038 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84039 sqlite3BtreeLeaveCursor(p->pCsr);
84040 if( rc==SQLITE_ABORT ){
84041 sqlite3VdbeFinalize(v);
84042 p->pStmt = 0;
@@ -82767,11 +85050,10 @@
85050 int nField, /* Number of key fields in each record */
85051 VdbeCursor *pCsr /* Cursor that holds the new sorter */
85052 ){
85053 int pgsz; /* Page size of main database */
85054 int i; /* Used to iterate through aTask[] */
 
85055 VdbeSorter *pSorter; /* The new sorter */
85056 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
85057 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
85058 int sz; /* Size of pSorter in bytes */
85059 int rc = SQLITE_OK;
@@ -82824,15 +85106,24 @@
85106 SortSubtask *pTask = &pSorter->aTask[i];
85107 pTask->pSorter = pSorter;
85108 }
85109
85110 if( !sqlite3TempInMemory(db) ){
85111 i64 mxCache; /* Cache size in bytes*/
85112 u32 szPma = sqlite3GlobalConfig.szPma;
85113 pSorter->mnPmaSize = szPma * pgsz;
85114
85115 mxCache = db->aDb[0].pSchema->cache_size;
85116 if( mxCache<0 ){
85117 /* A negative cache-size value C indicates that the cache is abs(C)
85118 ** KiB in size. */
85119 mxCache = mxCache * -1024;
85120 }else{
85121 mxCache = mxCache * pgsz;
85122 }
85123 mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85124 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85125
85126 /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85127 ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85128 ** large heap allocations.
85129 */
@@ -84592,10 +86883,19 @@
86883 *************************************************************************
86884 **
86885 ** This file contains code use to implement an in-memory rollback journal.
86886 ** The in-memory rollback journal is used to journal transactions for
86887 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
86888 **
86889 ** Update: The in-memory journal is also used to temporarily cache
86890 ** smaller journals that are not critical for power-loss recovery.
86891 ** For example, statement journals that are not too big will be held
86892 ** entirely in memory, thus reducing the number of file I/O calls, and
86893 ** more importantly, reducing temporary file creation events. If these
86894 ** journals become too large for memory, they are spilled to disk. But
86895 ** in the common case, they are usually small and no file I/O needs to
86896 ** occur.
86897 */
86898 /* #include "sqliteInt.h" */
86899
86900 /* Forward references to internal structures */
86901 typedef struct MemJournal MemJournal;
@@ -85918,10 +88218,11 @@
88218 notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88219 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88220 assert( pNC->nRef>=nRef );
88221 if( nRef!=pNC->nRef ){
88222 ExprSetProperty(pExpr, EP_VarSelect);
88223 pNC->ncFlags |= NC_VarSelect;
88224 }
88225 }
88226 break;
88227 }
88228 case TK_VARIABLE: {
@@ -87125,19 +89426,17 @@
89426 if( pToken ){
89427 if( nExtra==0 ){
89428 pNew->flags |= EP_IntValue;
89429 pNew->u.iValue = iValue;
89430 }else{
 
89431 pNew->u.zToken = (char*)&pNew[1];
89432 assert( pToken->z!=0 || pToken->n==0 );
89433 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
89434 pNew->u.zToken[pToken->n] = 0;
89435 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89436 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
89437 sqlite3Dequote(pNew->u.zToken);
 
89438 }
89439 }
89440 }
89441 #if SQLITE_MAX_EXPR_DEPTH>0
89442 pNew->nHeight = 1;
@@ -87215,10 +89514,26 @@
89514 if( p ) {
89515 sqlite3ExprCheckHeight(pParse, p->nHeight);
89516 }
89517 return p;
89518 }
89519
89520 /*
89521 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
89522 ** do a memory allocation failure) then delete the pSelect object.
89523 */
89524 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
89525 if( pExpr ){
89526 pExpr->x.pSelect = pSelect;
89527 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
89528 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
89529 }else{
89530 assert( pParse->db->mallocFailed );
89531 sqlite3SelectDelete(pParse->db, pSelect);
89532 }
89533 }
89534
89535
89536 /*
89537 ** If the expression is always either TRUE or FALSE (respectively),
89538 ** then return 1. If one cannot determine the truth value of the
89539 ** expression at compile-time return 0.
@@ -87376,12 +89691,12 @@
89691 }
89692
89693 /*
89694 ** Recursively delete an expression tree.
89695 */
89696 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
89697 assert( p!=0 );
89698 /* Sanity check: Assert that the IntValue is non-negative if it exists */
89699 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
89700 if( !ExprHasProperty(p, EP_TokenOnly) ){
89701 /* The Expr.x union is never used at the same time as Expr.pRight */
89702 assert( p->x.pList==0 || p->pRight==0 );
@@ -87395,10 +89710,13 @@
89710 }
89711 }
89712 if( !ExprHasProperty(p, EP_Static) ){
89713 sqlite3DbFree(db, p);
89714 }
89715 }
89716 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
89717 if( p ) sqlite3ExprDeleteNN(db, p);
89718 }
89719
89720 /*
89721 ** Return the number of bytes allocated for the expression structure
89722 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
@@ -87447,11 +89765,11 @@
89765 static int dupedExprStructSize(Expr *p, int flags){
89766 int nSize;
89767 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
89768 assert( EXPR_FULLSIZE<=0xfff );
89769 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
89770 if( 0==flags ){
89771 nSize = EXPR_FULLSIZE;
89772 }else{
89773 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
89774 assert( !ExprHasProperty(p, EP_FromJoin) );
89775 assert( !ExprHasProperty(p, EP_MemToken) );
@@ -87509,92 +89827,92 @@
89827 ** to store the copy of expression p, the copies of p->u.zToken
89828 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
89829 ** if any. Before returning, *pzBuffer is set to the first byte past the
89830 ** portion of the buffer copied into by this function.
89831 */
89832 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
89833 Expr *pNew; /* Value to return */
89834 u8 *zAlloc; /* Memory space from which to build Expr object */
89835 u32 staticFlag; /* EP_Static if space not obtained from malloc */
89836
89837 assert( db!=0 );
89838 assert( p );
89839 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
89840 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
89841
89842 /* Figure out where to write the new Expr structure. */
89843 if( pzBuffer ){
89844 zAlloc = *pzBuffer;
89845 staticFlag = EP_Static;
89846 }else{
89847 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
89848 staticFlag = 0;
89849 }
89850 pNew = (Expr *)zAlloc;
89851
89852 if( pNew ){
89853 /* Set nNewSize to the size allocated for the structure pointed to
89854 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
89855 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
89856 ** by the copy of the p->u.zToken string (if any).
89857 */
89858 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
89859 const int nNewSize = nStructSize & 0xfff;
89860 int nToken;
89861 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89862 nToken = sqlite3Strlen30(p->u.zToken) + 1;
89863 }else{
89864 nToken = 0;
89865 }
89866 if( dupFlags ){
89867 assert( ExprHasProperty(p, EP_Reduced)==0 );
89868 memcpy(zAlloc, p, nNewSize);
89869 }else{
89870 u32 nSize = (u32)exprStructSize(p);
89871 memcpy(zAlloc, p, nSize);
89872 if( nSize<EXPR_FULLSIZE ){
89873 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
89874 }
89875 }
89876
89877 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
89878 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
89879 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
89880 pNew->flags |= staticFlag;
89881
89882 /* Copy the p->u.zToken string, if any. */
89883 if( nToken ){
89884 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
89885 memcpy(zToken, p->u.zToken, nToken);
89886 }
89887
89888 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
89889 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
89890 if( ExprHasProperty(p, EP_xIsSelect) ){
89891 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
89892 }else{
89893 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
89894 }
89895 }
89896
89897 /* Fill in pNew->pLeft and pNew->pRight. */
89898 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
89899 zAlloc += dupedExprNodeSize(p, dupFlags);
89900 if( ExprHasProperty(pNew, EP_Reduced) ){
89901 pNew->pLeft = p->pLeft ?
89902 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
89903 pNew->pRight = p->pRight ?
89904 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
89905 }
89906 if( pzBuffer ){
89907 *pzBuffer = zAlloc;
89908 }
89909 }else{
89910 if( !ExprHasProperty(p, EP_TokenOnly) ){
89911 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
89912 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
89913 }
 
 
89914 }
89915 }
89916 return pNew;
89917 }
89918
@@ -87642,11 +89960,11 @@
89960 ** truncated version of the usual Expr structure that will be stored as
89961 ** part of the in-memory representation of the database schema.
89962 */
89963 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
89964 assert( flags==0 || flags==EXPRDUP_REDUCE );
89965 return p ? exprDup(db, p, flags, 0) : 0;
89966 }
89967 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
89968 ExprList *pNew;
89969 struct ExprList_item *pItem, *pOldItem;
89970 int i;
@@ -87864,11 +90182,11 @@
90182 struct ExprList_item *pItem;
90183 assert( pList->nExpr>0 );
90184 pItem = &pList->a[pList->nExpr-1];
90185 assert( pItem->zName==0 );
90186 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
90187 if( dequote ) sqlite3Dequote(pItem->zName);
90188 }
90189 }
90190
90191 /*
90192 ** Set the ExprList.a[].zSpan element of the most recently added item
@@ -87913,22 +90231,24 @@
90231 }
90232
90233 /*
90234 ** Delete an entire expression list.
90235 */
90236 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
90237 int i;
90238 struct ExprList_item *pItem;
 
90239 assert( pList->a!=0 || pList->nExpr==0 );
90240 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
90241 sqlite3ExprDelete(db, pItem->pExpr);
90242 sqlite3DbFree(db, pItem->zName);
90243 sqlite3DbFree(db, pItem->zSpan);
90244 }
90245 sqlite3DbFree(db, pList->a);
90246 sqlite3DbFree(db, pList);
90247 }
90248 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90249 if( pList ) exprListDeleteNN(db, pList);
90250 }
90251
90252 /*
90253 ** Return the bitwise-OR of all Expr.flags fields in the given
90254 ** ExprList.
@@ -88970,10 +91290,23 @@
91290 #endif
91291 }
91292 }
91293 }
91294
91295 #if defined(SQLITE_DEBUG)
91296 /*
91297 ** Verify the consistency of the column cache
91298 */
91299 static int cacheIsValid(Parse *pParse){
91300 int i, n;
91301 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91302 if( pParse->aColCache[i].iReg>0 ) n++;
91303 }
91304 return n==pParse->nColCache;
91305 }
91306 #endif
91307
91308 /*
91309 ** Clear a cache entry.
91310 */
91311 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
91312 if( p->tempReg ){
@@ -88980,10 +91313,13 @@
91313 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
91314 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
91315 }
91316 p->tempReg = 0;
91317 }
91318 p->iReg = 0;
91319 pParse->nColCache--;
91320 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91321 }
91322
91323
91324 /*
91325 ** Record in the column cache that a particular column from a
@@ -89023,10 +91359,12 @@
91359 p->iTable = iTab;
91360 p->iColumn = iCol;
91361 p->iReg = iReg;
91362 p->tempReg = 0;
91363 p->lru = pParse->iCacheCnt++;
91364 pParse->nColCache++;
91365 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91366 return;
91367 }
91368 }
91369
91370 /* Replace the last recently used */
@@ -89044,28 +91382,27 @@
91382 p->iTable = iTab;
91383 p->iColumn = iCol;
91384 p->iReg = iReg;
91385 p->tempReg = 0;
91386 p->lru = pParse->iCacheCnt++;
91387 assert( cacheIsValid(pParse) );
91388 return;
91389 }
91390 }
91391
91392 /*
91393 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
91394 ** Purge the range of registers from the column cache.
91395 */
91396 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
 
 
91397 struct yColCache *p;
91398 if( iReg<=0 || pParse->nColCache==0 ) return;
91399 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91400 while(1){
91401 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91402 if( p==pParse->aColCache ) break;
91403 p--;
91404 }
91405 }
91406
91407 /*
91408 ** Remember the current column cache context. Any new entries added
@@ -89097,11 +91434,10 @@
91434 }
91435 #endif
91436 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91437 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
91438 cacheEntryClear(pParse, p);
 
91439 }
91440 }
91441 }
91442
91443 /*
@@ -89232,11 +91568,10 @@
91568 }
91569 #endif
91570 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91571 if( p->iReg ){
91572 cacheEntryClear(pParse, p);
 
91573 }
91574 }
91575 }
91576
91577 /*
@@ -89273,10 +91608,11 @@
91608 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
91609 }
91610 return 0;
91611 }
91612 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
91613
91614
91615 /*
91616 ** Convert an expression node to a TK_REGISTER
91617 */
91618 static void exprToRegister(Expr *p, int iReg){
@@ -93567,43 +95903,46 @@
95903 */
95904 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
95905 analysisInfo sInfo;
95906 HashElem *i;
95907 char *zSql;
95908 int rc = SQLITE_OK;
95909
95910 assert( iDb>=0 && iDb<db->nDb );
95911 assert( db->aDb[iDb].pBt!=0 );
95912
95913 /* Clear any prior statistics */
95914 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95915 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95916 Index *pIdx = sqliteHashData(i);
95917 pIdx->aiRowLogEst[0] = 0;
95918 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95919 sqlite3DeleteIndexSamples(db, pIdx);
95920 pIdx->aSample = 0;
95921 #endif
95922 }
95923
95924 /* Load new statistics out of the sqlite_stat1 table */
95925 sInfo.db = db;
95926 sInfo.zDatabase = db->aDb[iDb].zName;
95927 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
95928 zSql = sqlite3MPrintf(db,
95929 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
95930 if( zSql==0 ){
95931 rc = SQLITE_NOMEM_BKPT;
95932 }else{
95933 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
95934 sqlite3DbFree(db, zSql);
95935 }
95936 }
95937
95938 /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
95939 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95940 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95941 Index *pIdx = sqliteHashData(i);
95942 if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
95943 }
 
 
 
 
95944
95945 /* Load the statistics from the sqlite_stat4 table. */
95946 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95947 if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
95948 db->lookaside.bDisable++;
@@ -95067,20 +97406,14 @@
97406 ** contains lookaside memory. (Table objects in the schema do not use
97407 ** lookaside memory, but some ephemeral Table objects do.) Or the
97408 ** db parameter can be used with db->pnBytesFreed to measure the memory
97409 ** used by the Table object.
97410 */
97411 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
97412 Index *pIndex, *pNext;
97413 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
97414
 
 
 
 
 
 
97415 /* Record the number of outstanding lookaside allocations in schema Tables
97416 ** prior to doing any free() operations. Since schema Tables do not use
97417 ** lookaside, this number should not change. */
97418 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
97419 db->lookaside.nOut : 0 );
@@ -95116,10 +97449,17 @@
97449 sqlite3DbFree(db, pTable);
97450
97451 /* Verify that no lookaside memory was used by schema tables */
97452 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
97453 }
97454 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
97455 /* Do not delete the table until the reference count reaches zero. */
97456 if( !pTable ) return;
97457 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
97458 deleteTable(db, pTable);
97459 }
97460
97461
97462 /*
97463 ** Unlink the given table from the hash tables and the delete the
97464 ** table structure with all its indices and foreign keys.
97465 */
@@ -95561,10 +97901,11 @@
97901 pCol->szEst = 1;
97902 }else{
97903 zType = z + sqlite3Strlen30(z) + 1;
97904 memcpy(zType, pType->z, pType->n);
97905 zType[pType->n] = 0;
97906 sqlite3Dequote(zType);
97907 pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
97908 pCol->colFlags |= COLFLAG_HASTYPE;
97909 }
97910 p->nCol++;
97911 pParse->constraintName.n = 0;
@@ -96695,11 +99036,11 @@
99036 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
99037 }else{
99038 pTable->nCol = 0;
99039 nErr++;
99040 }
99041 sqlite3DeleteTable(db, pSelTab);
99042 sqlite3SelectDelete(db, pSel);
99043 db->lookaside.bDisable--;
99044 } else {
99045 nErr++;
99046 }
@@ -97248,10 +99589,11 @@
99589 tnum = memRootPage;
99590 }else{
99591 tnum = pIndex->tnum;
99592 }
99593 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
99594 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
99595
99596 /* Open the sorter cursor if we are to use one. */
99597 iSorter = pParse->nTab++;
99598 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
99599 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
@@ -97271,12 +99613,11 @@
99613 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
99614 (char *)pKey, P4_KEYINFO);
99615 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
99616
99617 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
99618 if( IsUniqueIndex(pIndex) ){
 
99619 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
99620 sqlite3VdbeGoto(v, j2);
99621 addr2 = sqlite3VdbeCurrentAddr(v);
99622 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
99623 pIndex->nKeyCol); VdbeCoverage(v);
@@ -99526,11 +101867,11 @@
101867
101868 /* Check that there isn't an ORDER BY without a LIMIT clause.
101869 */
101870 if( pOrderBy && (pLimit == 0) ) {
101871 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
101872 goto limit_where_cleanup;
101873 }
101874
101875 /* We only need to generate a select expression if there
101876 ** is a limit/offset term to enforce.
101877 */
@@ -99548,44 +101889,34 @@
101889 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
101890 ** );
101891 */
101892
101893 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
101894 if( pSelectRowid == 0 ) goto limit_where_cleanup;
101895 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
101896 if( pEList == 0 ) goto limit_where_cleanup;
101897
101898 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
101899 ** and the SELECT subtree. */
101900 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
101901 if( pSelectSrc == 0 ) {
101902 sqlite3ExprListDelete(pParse->db, pEList);
101903 goto limit_where_cleanup;
101904 }
101905
101906 /* generate the SELECT expression tree. */
101907 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
101908 pOrderBy,0,pLimit,pOffset);
101909 if( pSelect == 0 ) return 0;
101910
101911 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
101912 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
101913 pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
101914 sqlite3PExprAddSelect(pParse, pInClause, pSelect);
 
 
 
 
 
101915 return pInClause;
101916
101917 limit_where_cleanup:
 
 
 
 
 
101918 sqlite3ExprDelete(pParse->db, pWhere);
101919 sqlite3ExprListDelete(pParse->db, pOrderBy);
101920 sqlite3ExprDelete(pParse->db, pLimit);
101921 sqlite3ExprDelete(pParse->db, pOffset);
101922 return 0;
@@ -99632,15 +101963,16 @@
101963 int iEphCur = 0; /* Ephemeral table holding all primary key values */
101964 int iRowSet = 0; /* Register for rowset of rows to delete */
101965 int addrBypass = 0; /* Address of jump over the delete logic */
101966 int addrLoop = 0; /* Top of the delete loop */
101967 int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
101968 int bComplex; /* True if there are triggers or FKs or
101969 ** subqueries in the WHERE clause */
101970
101971 #ifndef SQLITE_OMIT_TRIGGER
101972 int isView; /* True if attempting to delete from a view */
101973 Trigger *pTrigger; /* List of table triggers, if required */
 
101974 #endif
101975
101976 memset(&sContext, 0, sizeof(sContext));
101977 db = pParse->db;
101978 if( pParse->nErr || db->mallocFailed ){
@@ -99664,11 +101996,10 @@
101996 isView = pTab->pSelect!=0;
101997 bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
101998 #else
101999 # define pTrigger 0
102000 # define isView 0
 
102001 #endif
102002 #ifdef SQLITE_OMIT_VIEW
102003 # undef isView
102004 # define isView 0
102005 #endif
@@ -99749,10 +102080,13 @@
102080 ** API function sqlite3_count_changes) to be set incorrectly. */
102081 if( rcauth==SQLITE_OK
102082 && pWhere==0
102083 && !bComplex
102084 && !IsVirtual(pTab)
102085 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102086 && db->xPreUpdateCallback==0
102087 #endif
102088 ){
102089 assert( !isView );
102090 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102091 if( HasRowid(pTab) ){
102092 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
@@ -99763,11 +102097,12 @@
102097 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
102098 }
102099 }else
102100 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
102101 {
102102 u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
102103 if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
102104 wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
102105 if( HasRowid(pTab) ){
102106 /* For a rowid table, initialize the RowSet to an empty set */
102107 pPk = 0;
102108 nPk = 1;
@@ -100098,18 +102433,23 @@
102433 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
102434 }
102435
102436 /* Delete the index and table entries. Skip this step if pTab is really
102437 ** a view (in which case the only effect of the DELETE statement is to
102438 ** fire the INSTEAD OF triggers).
102439 **
102440 ** If variable 'count' is non-zero, then this OP_Delete instruction should
102441 ** invoke the update-hook. The pre-update-hook, on the other hand should
102442 ** be invoked unless table pTab is a system table. The difference is that
102443 ** the update-hook is not invoked for rows removed by REPLACE, but the
102444 ** pre-update-hook is.
102445 */
102446 if( pTab->pSelect==0 ){
102447 u8 p5 = 0;
102448 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
102449 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
102450 sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
 
 
102451 if( eMode!=ONEPASS_OFF ){
102452 sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
102453 }
102454 if( iIdxNoSeek>=0 ){
102455 sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
@@ -101669,10 +104009,18 @@
104009 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
104010 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
104011 const char *zProc;
104012 sqlite3 *db = sqlite3_context_db_handle(context);
104013 char *zErrMsg = 0;
104014
104015 /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
104016 ** flag is set. See the sqlite3_enable_load_extension() API.
104017 */
104018 if( (db->flags & SQLITE_LoadExtFunc)==0 ){
104019 sqlite3_result_error(context, "not authorized", -1);
104020 return;
104021 }
104022
104023 if( argc==2 ){
104024 zProc = (const char *)sqlite3_value_text(argv[1]);
104025 }else{
104026 zProc = 0;
@@ -103268,11 +105616,10 @@
105616
105617 action = pFKey->aAction[iAction];
105618 if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
105619 return 0;
105620 }
 
105621 pTrigger = pFKey->apTrigger[iAction];
105622
105623 if( action!=OE_None && !pTrigger ){
105624 char const *zFrom; /* Name of child table */
105625 int nFrom; /* Length in bytes of zFrom */
@@ -104945,13 +107292,22 @@
107292 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107293 }
107294 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
107295 sqlite3MultiWrite(pParse);
107296 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107297 regNewData, 1, 0, OE_Replace, 1, -1);
 
107298 }else{
107299 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107300 if( HasRowid(pTab) ){
107301 /* This OP_Delete opcode fires the pre-update-hook only. It does
107302 ** not modify the b-tree. It is more efficient to let the coming
107303 ** OP_Insert replace the existing entry than it is to delete the
107304 ** existing entry and then insert a new one. */
107305 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107306 sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107307 }
107308 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
107309 if( pTab->pIndex ){
107310 sqlite3MultiWrite(pParse);
107311 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
107312 }
107313 }
@@ -105217,11 +107573,11 @@
107573 if( useSeekResult ){
107574 pik_flags |= OPFLAG_USESEEKRESULT;
107575 }
107576 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
107577 if( !pParse->nested ){
107578 sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107579 }
107580 sqlite3VdbeChangeP5(v, pik_flags);
107581 }
107582
107583 /*
@@ -105617,11 +107973,11 @@
107973 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
107974 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
107975 }
107976 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
107977 sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
107978 (char*)pDest, P4_TABLE);
107979 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
107980 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
107981 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
107982 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
107983 }else{
@@ -106856,12 +109212,13 @@
109212 if( pzErrMsg ) *pzErrMsg = 0;
109213
109214 /* Ticket #1863. To avoid a creating security problems for older
109215 ** applications that relink against newer versions of SQLite, the
109216 ** ability to run load_extension is turned off by default. One
109217 ** must call either sqlite3_enable_load_extension(db) or
109218 ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109219 ** to turn on extension loading.
109220 */
109221 if( (db->flags & SQLITE_LoadExtension)==0 ){
109222 if( pzErrMsg ){
109223 *pzErrMsg = sqlite3_mprintf("not authorized");
109224 }
@@ -106996,13 +109353,13 @@
109353 ** default so as not to open security holes in older applications.
109354 */
109355 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
109356 sqlite3_mutex_enter(db->mutex);
109357 if( onoff ){
109358 db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
109359 }else{
109360 db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
109361 }
109362 sqlite3_mutex_leave(db->mutex);
109363 return SQLITE_OK;
109364 }
109365
@@ -110575,11 +112932,11 @@
112932 sqlite3ExprListDelete(db, p->pGroupBy);
112933 sqlite3ExprDelete(db, p->pHaving);
112934 sqlite3ExprListDelete(db, p->pOrderBy);
112935 sqlite3ExprDelete(db, p->pLimit);
112936 sqlite3ExprDelete(db, p->pOffset);
112937 if( p->pWith ) sqlite3WithDelete(db, p->pWith);
112938 if( bFree ) sqlite3DbFree(db, p);
112939 p = pPrior;
112940 bFree = 1;
112941 }
112942 }
@@ -110670,11 +113027,11 @@
113027
113028 /*
113029 ** Delete the given Select structure and all of its substructures.
113030 */
113031 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
113032 if( p ) clearSelect(db, p, 1);
113033 }
113034
113035 /*
113036 ** Return a pointer to the right-most SELECT statement in a compound.
113037 */
@@ -112290,23 +114647,23 @@
114647
114648 /*
114649 ** Get a VDBE for the given parser context. Create a new one if necessary.
114650 ** If an error occurs, return NULL and leave a message in pParse.
114651 */
114652 static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
114653 Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
114654 if( v ) sqlite3VdbeAddOp0(v, OP_Init);
114655 if( pParse->pToplevel==0
114656 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
114657 ){
114658 pParse->okConstFactor = 1;
 
 
 
 
114659 }
114660 return v;
114661 }
114662 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
114663 Vdbe *v = pParse->pVdbe;
114664 return v ? v : allocVdbe(pParse);
114665 }
114666
114667
114668 /*
114669 ** Compute the iLimit and iOffset fields of the SELECT based on the
@@ -114286,16 +116643,22 @@
116643 Expr *pWhere, /* The WHERE clause of the outer query */
116644 int iCursor /* Cursor number of the subquery */
116645 ){
116646 Expr *pNew;
116647 int nChng = 0;
116648 Select *pX; /* For looping over compound SELECTs in pSubq */
116649 if( pWhere==0 ) return 0;
116650 for(pX=pSubq; pX; pX=pX->pPrior){
116651 if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
116652 testcase( pX->selFlags & SF_Aggregate );
116653 testcase( pX->selFlags & SF_Recursive );
116654 testcase( pX!=pSubq );
116655 return 0; /* restrictions (1) and (2) */
116656 }
116657 }
116658 if( pSubq->pLimit!=0 ){
116659 return 0; /* restriction (3) */
116660 }
116661 while( pWhere->op==TK_AND ){
116662 nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
116663 pWhere = pWhere->pLeft;
116664 }
@@ -115593,10 +117956,17 @@
117956 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
117957 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
117958 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
117959 ** original setting of the SF_Distinct flag, not the current setting */
117960 assert( sDistinct.isTnct );
117961
117962 #if SELECTTRACE_ENABLED
117963 if( sqlite3SelectTrace & 0x400 ){
117964 SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
117965 sqlite3TreeViewSelect(0, p, 0);
117966 }
117967 #endif
117968 }
117969
117970 /* If there is an ORDER BY clause, then create an ephemeral index to
117971 ** do the sorting. But this sorting ephemeral index might end up
117972 ** being unused if the data can be extracted in pre-sorted order.
@@ -117831,11 +120201,12 @@
120201 /* Begin the database scan
120202 */
120203 if( HasRowid(pTab) ){
120204 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
120205 pWInfo = sqlite3WhereBegin(
120206 pParse, pTabList, pWhere, 0, 0,
120207 WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
120208 );
120209 if( pWInfo==0 ) goto update_cleanup;
120210 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120211
120212 /* Remember the rowid of every item to be updated.
@@ -118069,15 +120440,34 @@
120440 addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
120441 }
120442 VdbeCoverageNeverTaken(v);
120443 }
120444 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
120445
120446 /* If changing the rowid value, or if there are foreign key constraints
120447 ** to process, delete the old record. Otherwise, add a noop OP_Delete
120448 ** to invoke the pre-update hook.
120449 **
120450 ** That (regNew==regnewRowid+1) is true is also important for the
120451 ** pre-update hook. If the caller invokes preupdate_new(), the returned
120452 ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
120453 ** is the column index supplied by the user.
120454 */
120455 assert( regNew==regNewRowid+1 );
120456 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
120457 sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
120458 OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
120459 regNewRowid
120460 );
120461 if( !pParse->nested ){
120462 sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
120463 }
120464 #else
120465 if( hasFK || chngKey || pPk!=0 ){
120466 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
120467 }
120468 #endif
120469 if( bReplace || chngKey ){
120470 sqlite3VdbeJumpHere(v, addr1);
120471 }
120472
120473 if( hasFK ){
@@ -119969,11 +122359,11 @@
122359 int addrSkip; /* Jump here for next iteration of skip-scan */
122360 int addrCont; /* Jump here to continue with the next loop cycle */
122361 int addrFirst; /* First instruction of interior of the loop */
122362 int addrBody; /* Beginning of the body of this loop */
122363 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
122364 u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
122365 int addrLikeRep; /* LIKE range processing address */
122366 #endif
122367 u8 iFrom; /* Which entry in the FROM clause */
122368 u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
122369 int p1, p2; /* Operands of the opcode used to ends the loop */
@@ -120307,11 +122697,11 @@
122697 */
122698 struct WhereInfo {
122699 Parse *pParse; /* Parsing and code generating context */
122700 SrcList *pTabList; /* List of tables in the join */
122701 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
122702 ExprList *pDistinctSet; /* DISTINCT over all these values */
122703 WhereLoop *pLoops; /* List of all WhereLoop objects */
122704 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
122705 LogEst nRowOut; /* Estimated number of output rows */
122706 LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
122707 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
@@ -120391,10 +122781,18 @@
122781 /*
122782 ** Bitmasks for the operators on WhereTerm objects. These are all
122783 ** operators that are of interest to the query planner. An
122784 ** OR-ed combination of these values can be used when searching for
122785 ** particular WhereTerms within a WhereClause.
122786 **
122787 ** Value constraints:
122788 ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
122789 ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
122790 ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
122791 ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
122792 ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
122793 ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
122794 */
122795 #define WO_IN 0x0001
122796 #define WO_EQ 0x0002
122797 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
122798 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
@@ -120977,13 +123375,14 @@
123375 return regBase;
123376 }
123377
123378 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123379 /*
123380 ** If the most recently coded instruction is a constant range constraint
123381 ** (a string literal) that originated from the LIKE optimization, then
123382 ** set P3 and P5 on the OP_String opcode so that the string will be cast
123383 ** to a BLOB at appropriate times.
123384 **
123385 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
123386 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
123387 ** scan loop run twice, once for strings and a second time for BLOBs.
123388 ** The OP_String opcodes on the second pass convert the upper and lower
@@ -121004,12 +123403,12 @@
123403 assert( pLevel->iLikeRepCntr>0 );
123404 pOp = sqlite3VdbeGetOp(v, -1);
123405 assert( pOp!=0 );
123406 assert( pOp->opcode==OP_String8
123407 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
123408 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
123409 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
123410 }
123411 }
123412 #else
123413 # define whereLikeOptimizationStringFixup(A,B,C)
123414 #endif
@@ -121358,11 +123757,17 @@
123757 pCompare->pLeft = 0;
123758 sqlite3ExprDelete(db, pCompare);
123759 }
123760 }
123761 }
123762 /* These registers need to be preserved in case there is an IN operator
123763 ** loop. So we could deallocate the registers here (and potentially
123764 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
123765 ** simpler and safer to simply not reuse the registers.
123766 **
123767 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
123768 */
123769 sqlite3ExprCachePop(pParse);
123770 }else
123771 #endif /* SQLITE_OMIT_VIRTUALTABLE */
123772
123773 if( (pLoop->wsFlags & WHERE_IPK)!=0
@@ -121586,18 +123991,21 @@
123991 nExtraReg = 1;
123992 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123993 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
123994 assert( pRangeStart!=0 ); /* LIKE opt constraints */
123995 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
123996 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
123997 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
123998 VdbeComment((v, "LIKE loop counter"));
123999 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124000 /* iLikeRepCntr actually stores 2x the counter register number. The
124001 ** bottom bit indicates whether the search order is ASC or DESC. */
124002 testcase( bRev );
124003 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
124004 assert( (bRev & ~1)==0 );
124005 pLevel->iLikeRepCntr <<=1;
124006 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
 
 
124007 }
124008 #endif
124009 if( pRangeStart==0
124010 && (j = pIdx->aiColumn[nEq])>=0
124011 && pIdx->pTable->aCol[j].notNull==0
@@ -121731,11 +124139,11 @@
124139 disableTerm(pLevel, pRangeStart);
124140 disableTerm(pLevel, pRangeEnd);
124141 if( omitTable ){
124142 /* pIdx is a covering index. No need to access the main table. */
124143 }else if( HasRowid(pIdx->pTable) ){
124144 if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
124145 iRowidReg = ++pParse->nMem;
124146 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
124147 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124148 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
124149 VdbeCoverage(v);
@@ -121927,11 +124335,12 @@
124335 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
124336 */
124337 wctrlFlags = WHERE_OMIT_OPEN_CLOSE
124338 | WHERE_FORCE_TABLE
124339 | WHERE_ONETABLE_ONLY
124340 | WHERE_NO_AUTOINDEX
124341 | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
124342 for(ii=0; ii<pOrWc->nTerm; ii++){
124343 WhereTerm *pOrTerm = &pOrWc->a[ii];
124344 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
124345 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
124346 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
@@ -122107,15 +124516,21 @@
124516 assert( pE!=0 );
124517 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
124518 continue;
124519 }
124520 if( pTerm->wtFlags & TERM_LIKECOND ){
124521 /* If the TERM_LIKECOND flag is set, that means that the range search
124522 ** is sufficient to guarantee that the LIKE operator is true, so we
124523 ** can skip the call to the like(A,B) function. But this only works
124524 ** for strings. So do not skip the call to the function on the pass
124525 ** that compares BLOBs. */
124526 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124527 continue;
124528 #else
124529 u32 x = pLevel->iLikeRepCntr;
124530 assert( x>0 );
124531 skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
124532 VdbeCoverage(v);
124533 #endif
124534 }
124535 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
124536 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
@@ -123467,14 +125882,14 @@
125882 if( p->op==TK_COLUMN ){
125883 mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
125884 return mask;
125885 }
125886 mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
125887 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
125888 if( ExprHasProperty(p, EP_xIsSelect) ){
125889 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
125890 }else if( p->x.pList ){
125891 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
125892 }
125893 return mask;
125894 }
125895 SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
@@ -123810,11 +126225,14 @@
126225 ** Initialize a WHERE clause scanner object. Return a pointer to the
126226 ** first match. Return NULL if there are no matches.
126227 **
126228 ** The scanner will be searching the WHERE clause pWC. It will look
126229 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
126230 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
126231 ** must be one of the indexes of table iCur.
126232 **
126233 ** The <op> must be one of the operators described by opMask.
126234 **
126235 ** If the search is for X and the WHERE clause contains terms of the
126236 ** form X=Y then this routine might also return terms of the form
126237 ** "Y <op> <expr>". The number of levels of transitivity is limited,
126238 ** but is enough to handle most commonly occurring SQL statements.
@@ -123858,15 +126276,16 @@
126276 return whereScanNext(pScan);
126277 }
126278
126279 /*
126280 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
126281 ** where X is a reference to the iColumn of table iCur or of index pIdx
126282 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
126283 ** the op parameter. Return a pointer to the term. Return 0 if not found.
126284 **
126285 ** If pIdx!=0 then it must be one of the indexes of table iCur.
126286 ** Search for terms matching the iColumn-th column of pIdx
126287 ** rather than the iColumn-th column of table iCur.
126288 **
126289 ** The term returned might by Y=<expr> if there is another constraint in
126290 ** the WHERE clause that specifies that X=Y. Any such constraints will be
126291 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
@@ -125200,15 +127619,16 @@
127619 /*
127620 ** Print a WhereLoop object for debugging purposes
127621 */
127622 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
127623 WhereInfo *pWInfo = pWC->pWInfo;
127624 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
127625 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
127626 Table *pTab = pItem->pTab;
127627 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
127628 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
127629 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
127630 sqlite3DebugPrintf(" %12s",
127631 pItem->zAlias ? pItem->zAlias : pTab->zName);
127632 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
127633 const char *zName;
127634 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
@@ -127429,13 +129849,13 @@
129849 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
129850 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
129851 && nRowEst
129852 ){
129853 Bitmask notUsed;
129854 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
129855 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
129856 if( rc==pWInfo->pDistinctSet->nExpr ){
129857 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
129858 }
129859 }
129860 if( pWInfo->pOrderBy ){
129861 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
@@ -127646,18 +130066,18 @@
130066 ** the first cursor in an array of cursors for all indices. iIdxCur should
130067 ** be used to compute the appropriate cursor depending on which index is
130068 ** used.
130069 */
130070 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
130071 Parse *pParse, /* The parser context */
130072 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
130073 Expr *pWhere, /* The WHERE clause */
130074 ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
130075 ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130076 u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
130077 int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number
130078 ** If WHERE_USE_LIMIT, then the limit amount */
130079 ){
130080 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
130081 int nTabList; /* Number of elements in pTabList */
130082 WhereInfo *pWInfo; /* Will become the return value of this function */
130083 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
@@ -127728,11 +130148,11 @@
130148 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
130149 pWInfo->nLevel = nTabList;
130150 pWInfo->pParse = pParse;
130151 pWInfo->pTabList = pTabList;
130152 pWInfo->pOrderBy = pOrderBy;
130153 pWInfo->pDistinctSet = pDistinctSet;
130154 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
130155 pWInfo->wctrlFlags = wctrlFlags;
130156 pWInfo->iLimit = iAuxArg;
130157 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
130158 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
@@ -127801,17 +130221,17 @@
130221 /* Analyze all of the subexpressions. */
130222 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
130223 if( db->mallocFailed ) goto whereBeginError;
130224
130225 if( wctrlFlags & WHERE_WANT_DISTINCT ){
130226 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
130227 /* The DISTINCT marking is pointless. Ignore it. */
130228 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130229 }else if( pOrderBy==0 ){
130230 /* Try to ORDER BY the result set to make distinct processing easier */
130231 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
130232 pWInfo->pOrderBy = pDistinctSet;
130233 }
130234 }
130235
130236 /* Construct the WhereLoop objects */
130237 #if defined(WHERETRACE_ENABLED)
@@ -127886,14 +130306,14 @@
130306 }
130307 }
130308 #endif
130309 /* Attempt to omit tables from the join that do not effect the result */
130310 if( pWInfo->nLevel>=2
130311 && pDistinctSet!=0
130312 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
130313 ){
130314 Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
130315 if( sWLB.pOrderBy ){
130316 tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
130317 }
130318 while( pWInfo->nLevel>=2 ){
130319 WhereTerm *pTerm, *pEnd;
@@ -128155,17 +130575,12 @@
130575 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
130576 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
130577 }
130578 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
130579 if( pLevel->addrLikeRep ){
130580 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
130581 pLevel->addrLikeRep);
 
 
 
 
 
130582 VdbeCoverage(v);
130583 }
130584 #endif
130585 if( pLevel->iLeftJoin ){
130586 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
@@ -128567,11 +130982,11 @@
130982 #endif
130983 /************* Begin control #defines *****************************************/
130984 #define YYCODETYPE unsigned char
130985 #define YYNOCODE 251
130986 #define YYACTIONTYPE unsigned short int
130987 #define YYWILDCARD 96
130988 #define sqlite3ParserTOKENTYPE Token
130989 typedef union {
130990 int yyinit;
130991 sqlite3ParserTOKENTYPE yy0;
130992 struct LimitVal yy64;
@@ -128671,402 +131086,404 @@
131086 ** yy_reduce_ofst[] For each state, the offset into yy_action for
131087 ** shifting non-terminals after a reduce.
131088 ** yy_default[] Default action for each state.
131089 **
131090 *********** Begin parsing tables **********************************************/
131091 #define YY_ACTTAB_COUNT (1501)
131092 static const YYACTIONTYPE yy_action[] = {
131093 /* 0 */ 315, 810, 339, 804, 5, 194, 194, 798, 92, 93,
131094 /* 10 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131095 /* 20 */ 91, 91, 91, 290, 89, 89, 89, 89, 88, 88,
131096 /* 30 */ 87, 87, 87, 86, 339, 315, 952, 952, 803, 803,
131097 /* 40 */ 803, 922, 342, 92, 93, 83, 819, 819, 831, 834,
131098 /* 50 */ 823, 823, 90, 90, 91, 91, 91, 91, 123, 89,
131099 /* 60 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131100 /* 70 */ 88, 88, 87, 87, 87, 86, 339, 772, 952, 952,
131101 /* 80 */ 315, 87, 87, 87, 86, 339, 773, 68, 92, 93,
131102 /* 90 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131103 /* 100 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
131104 /* 110 */ 87, 87, 87, 86, 339, 1302, 146, 921, 2, 315,
131105 /* 120 */ 427, 24, 679, 953, 48, 86, 339, 92, 93, 83,
131106 /* 130 */ 819, 819, 831, 834, 823, 823, 90, 90, 91, 91,
131107 /* 140 */ 91, 91, 94, 89, 89, 89, 89, 88, 88, 87,
131108 /* 150 */ 87, 87, 86, 339, 933, 933, 315, 259, 412, 398,
131109 /* 160 */ 396, 57, 733, 733, 92, 93, 83, 819, 819, 831,
131110 /* 170 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 56,
131111 /* 180 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131112 /* 190 */ 339, 315, 1245, 922, 342, 268, 934, 935, 241, 92,
131113 /* 200 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131114 /* 210 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131115 /* 220 */ 88, 87, 87, 87, 86, 339, 315, 913, 1295, 682,
131116 /* 230 */ 687, 1295, 233, 397, 92, 93, 83, 819, 819, 831,
131117 /* 240 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
131118 /* 250 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131119 /* 260 */ 339, 315, 85, 82, 168, 680, 431, 938, 939, 92,
131120 /* 270 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131121 /* 280 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131122 /* 290 */ 88, 87, 87, 87, 86, 339, 315, 319, 913, 1296,
131123 /* 300 */ 797, 911, 1296, 681, 92, 93, 83, 819, 819, 831,
131124 /* 310 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 335,
131125 /* 320 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131126 /* 330 */ 339, 315, 876, 876, 373, 85, 82, 168, 944, 92,
131127 /* 340 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131128 /* 350 */ 91, 91, 91, 91, 896, 89, 89, 89, 89, 88,
131129 /* 360 */ 88, 87, 87, 87, 86, 339, 315, 370, 307, 973,
131130 /* 370 */ 367, 1, 911, 433, 92, 93, 83, 819, 819, 831,
131131 /* 380 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 189,
131132 /* 390 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131133 /* 400 */ 339, 315, 720, 948, 933, 933, 149, 718, 948, 92,
131134 /* 410 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131135 /* 420 */ 91, 91, 91, 91, 434, 89, 89, 89, 89, 88,
131136 /* 430 */ 88, 87, 87, 87, 86, 339, 338, 938, 939, 947,
131137 /* 440 */ 694, 940, 974, 315, 953, 48, 934, 935, 715, 689,
131138 /* 450 */ 71, 92, 93, 83, 819, 819, 831, 834, 823, 823,
131139 /* 460 */ 90, 90, 91, 91, 91, 91, 320, 89, 89, 89,
131140 /* 470 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 412,
131141 /* 480 */ 403, 820, 820, 832, 835, 74, 92, 81, 83, 819,
131142 /* 490 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131143 /* 500 */ 91, 698, 89, 89, 89, 89, 88, 88, 87, 87,
131144 /* 510 */ 87, 86, 339, 315, 259, 654, 655, 656, 393, 111,
131145 /* 520 */ 331, 153, 93, 83, 819, 819, 831, 834, 823, 823,
131146 /* 530 */ 90, 90, 91, 91, 91, 91, 434, 89, 89, 89,
131147 /* 540 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 188,
131148 /* 550 */ 187, 186, 824, 937, 328, 219, 953, 48, 83, 819,
131149 /* 560 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131150 /* 570 */ 91, 956, 89, 89, 89, 89, 88, 88, 87, 87,
131151 /* 580 */ 87, 86, 339, 79, 429, 738, 3, 1174, 955, 348,
131152 /* 590 */ 737, 332, 792, 933, 933, 937, 79, 429, 730, 3,
131153 /* 600 */ 203, 160, 278, 391, 273, 390, 190, 892, 434, 400,
131154 /* 610 */ 741, 76, 77, 271, 287, 253, 353, 242, 78, 340,
131155 /* 620 */ 340, 85, 82, 168, 76, 77, 233, 397, 953, 48,
131156 /* 630 */ 432, 78, 340, 340, 277, 934, 935, 185, 439, 651,
131157 /* 640 */ 388, 385, 384, 432, 234, 276, 107, 418, 349, 337,
131158 /* 650 */ 336, 383, 893, 728, 215, 949, 123, 971, 308, 810,
131159 /* 660 */ 418, 436, 435, 412, 394, 798, 400, 873, 894, 123,
131160 /* 670 */ 721, 872, 810, 889, 436, 435, 215, 949, 798, 351,
131161 /* 680 */ 722, 697, 380, 434, 771, 371, 22, 434, 400, 79,
131162 /* 690 */ 429, 232, 3, 189, 413, 870, 803, 803, 803, 805,
131163 /* 700 */ 18, 54, 148, 953, 48, 956, 113, 953, 9, 803,
131164 /* 710 */ 803, 803, 805, 18, 310, 123, 748, 76, 77, 742,
131165 /* 720 */ 123, 325, 955, 866, 78, 340, 340, 113, 350, 359,
131166 /* 730 */ 85, 82, 168, 343, 960, 960, 432, 770, 412, 414,
131167 /* 740 */ 407, 23, 1240, 1240, 79, 429, 357, 3, 166, 91,
131168 /* 750 */ 91, 91, 91, 418, 89, 89, 89, 89, 88, 88,
131169 /* 760 */ 87, 87, 87, 86, 339, 810, 434, 436, 435, 792,
131170 /* 770 */ 320, 798, 76, 77, 789, 271, 123, 434, 360, 78,
131171 /* 780 */ 340, 340, 864, 85, 82, 168, 953, 9, 395, 743,
131172 /* 790 */ 360, 432, 253, 358, 252, 933, 933, 953, 30, 889,
131173 /* 800 */ 327, 216, 803, 803, 803, 805, 18, 113, 418, 89,
131174 /* 810 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131175 /* 820 */ 810, 113, 436, 435, 792, 185, 798, 288, 388, 385,
131176 /* 830 */ 384, 123, 113, 920, 2, 796, 696, 934, 935, 383,
131177 /* 840 */ 69, 429, 434, 3, 218, 110, 738, 253, 358, 252,
131178 /* 850 */ 434, 737, 933, 933, 892, 359, 222, 803, 803, 803,
131179 /* 860 */ 805, 18, 953, 47, 933, 933, 933, 933, 76, 77,
131180 /* 870 */ 953, 9, 366, 904, 217, 78, 340, 340, 677, 305,
131181 /* 880 */ 304, 303, 206, 301, 224, 259, 664, 432, 337, 336,
131182 /* 890 */ 434, 228, 247, 144, 934, 935, 933, 933, 667, 893,
131183 /* 900 */ 324, 1259, 96, 434, 418, 796, 934, 935, 934, 935,
131184 /* 910 */ 953, 48, 401, 148, 289, 894, 810, 417, 436, 435,
131185 /* 920 */ 677, 759, 798, 953, 9, 314, 220, 162, 161, 170,
131186 /* 930 */ 402, 239, 953, 8, 194, 683, 683, 410, 934, 935,
131187 /* 940 */ 238, 959, 933, 933, 225, 408, 945, 365, 957, 212,
131188 /* 950 */ 958, 172, 757, 803, 803, 803, 805, 18, 173, 365,
131189 /* 960 */ 176, 123, 171, 113, 244, 952, 246, 434, 356, 796,
131190 /* 970 */ 372, 365, 236, 960, 960, 810, 290, 804, 191, 165,
131191 /* 980 */ 852, 798, 259, 316, 934, 935, 237, 953, 34, 404,
131192 /* 990 */ 91, 91, 91, 91, 84, 89, 89, 89, 89, 88,
131193 /* 1000 */ 88, 87, 87, 87, 86, 339, 701, 952, 434, 240,
131194 /* 1010 */ 347, 758, 803, 803, 803, 434, 245, 1179, 434, 389,
131195 /* 1020 */ 434, 376, 434, 895, 167, 434, 405, 702, 953, 35,
131196 /* 1030 */ 673, 321, 221, 434, 333, 953, 11, 434, 953, 26,
131197 /* 1040 */ 953, 36, 953, 37, 251, 953, 38, 434, 259, 434,
131198 /* 1050 */ 757, 434, 329, 953, 27, 434, 223, 953, 28, 434,
131199 /* 1060 */ 690, 434, 67, 434, 65, 434, 862, 953, 39, 953,
131200 /* 1070 */ 40, 953, 41, 423, 434, 953, 10, 434, 772, 953,
131201 /* 1080 */ 42, 953, 98, 953, 43, 953, 44, 773, 434, 346,
131202 /* 1090 */ 434, 75, 434, 73, 953, 31, 434, 953, 45, 434,
131203 /* 1100 */ 259, 434, 690, 434, 757, 434, 887, 434, 953, 46,
131204 /* 1110 */ 953, 32, 953, 115, 434, 266, 953, 116, 951, 953,
131205 /* 1120 */ 117, 953, 52, 953, 33, 953, 99, 953, 49, 726,
131206 /* 1130 */ 434, 909, 434, 19, 953, 100, 434, 344, 434, 113,
131207 /* 1140 */ 434, 258, 692, 434, 259, 434, 670, 434, 20, 434,
131208 /* 1150 */ 953, 101, 953, 97, 434, 259, 953, 114, 953, 112,
131209 /* 1160 */ 953, 105, 113, 953, 104, 953, 102, 953, 103, 953,
131210 /* 1170 */ 51, 434, 148, 434, 953, 53, 167, 434, 259, 113,
131211 /* 1180 */ 300, 307, 912, 363, 311, 860, 248, 261, 209, 264,
131212 /* 1190 */ 416, 953, 50, 953, 25, 420, 727, 953, 29, 430,
131213 /* 1200 */ 321, 424, 757, 428, 322, 124, 1269, 214, 165, 710,
131214 /* 1210 */ 859, 908, 806, 794, 309, 158, 193, 361, 254, 723,
131215 /* 1220 */ 364, 67, 381, 269, 735, 199, 67, 70, 113, 700,
131216 /* 1230 */ 699, 707, 708, 884, 113, 766, 113, 855, 193, 883,
131217 /* 1240 */ 199, 869, 869, 675, 868, 868, 109, 368, 255, 260,
131218 /* 1250 */ 263, 280, 859, 265, 806, 974, 267, 711, 695, 272,
131219 /* 1260 */ 764, 282, 795, 284, 150, 744, 755, 415, 292, 293,
131220 /* 1270 */ 802, 678, 672, 661, 660, 662, 927, 6, 306, 386,
131221 /* 1280 */ 352, 786, 243, 250, 886, 362, 163, 286, 419, 298,
131222 /* 1290 */ 930, 159, 968, 196, 126, 903, 901, 965, 55, 58,
131223 /* 1300 */ 323, 275, 857, 136, 147, 694, 856, 121, 65, 354,
131224 /* 1310 */ 355, 379, 175, 61, 151, 369, 180, 871, 375, 129,
131225 /* 1320 */ 257, 756, 210, 181, 145, 131, 132, 377, 262, 663,
131226 /* 1330 */ 133, 134, 139, 783, 791, 182, 392, 183, 312, 330,
131227 /* 1340 */ 714, 888, 713, 851, 692, 195, 712, 406, 686, 705,
131228 /* 1350 */ 313, 685, 64, 839, 274, 72, 684, 334, 942, 95,
131229 /* 1360 */ 752, 279, 281, 704, 753, 751, 422, 283, 411, 750,
131230 /* 1370 */ 426, 66, 204, 409, 21, 285, 928, 669, 437, 205,
131231 /* 1380 */ 207, 208, 438, 658, 657, 652, 118, 108, 119, 226,
131232 /* 1390 */ 650, 341, 157, 235, 169, 345, 106, 734, 790, 296,
131233 /* 1400 */ 294, 295, 120, 297, 867, 865, 127, 128, 130, 724,
131234 /* 1410 */ 229, 174, 249, 882, 137, 230, 138, 135, 885, 231,
131235 /* 1420 */ 59, 60, 177, 881, 7, 178, 12, 179, 256, 874,
131236 /* 1430 */ 140, 193, 962, 374, 141, 152, 666, 378, 276, 184,
131237 /* 1440 */ 270, 122, 142, 382, 387, 62, 13, 14, 703, 63,
131238 /* 1450 */ 125, 317, 318, 227, 809, 808, 837, 732, 15, 164,
131239 /* 1460 */ 736, 4, 765, 211, 399, 213, 192, 143, 760, 70,
131240 /* 1470 */ 67, 16, 17, 838, 836, 891, 841, 890, 198, 197,
131241 /* 1480 */ 917, 154, 421, 923, 918, 155, 200, 977, 425, 840,
131242 /* 1490 */ 156, 201, 807, 676, 80, 302, 299, 977, 202, 1261,
131243 /* 1500 */ 1260,
131244 };
131245 static const YYCODETYPE yy_lookahead[] = {
131246 /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28,
131247 /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131248 /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131249 /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133,
131250 /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33,
131251 /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 92, 43,
131252 /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131253 /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97,
131254 /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28,
131255 /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131256 /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131257 /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19,
131258 /* 120 */ 249, 22, 172, 172, 173, 52, 53, 27, 28, 29,
131259 /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
131260 /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49,
131261 /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208,
131262 /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32,
131263 /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79,
131264 /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131265 /* 190 */ 53, 19, 0, 1, 2, 23, 97, 98, 193, 27,
131266 /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131267 /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131268 /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172,
131269 /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32,
131270 /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131271 /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131272 /* 260 */ 53, 19, 221, 222, 223, 23, 168, 169, 170, 27,
131273 /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131274 /* 280 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131275 /* 290 */ 48, 49, 50, 51, 52, 53, 19, 157, 22, 23,
131276 /* 300 */ 23, 96, 26, 172, 27, 28, 29, 30, 31, 32,
131277 /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131278 /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131279 /* 330 */ 53, 19, 108, 109, 110, 221, 222, 223, 185, 27,
131280 /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131281 /* 350 */ 38, 39, 40, 41, 240, 43, 44, 45, 46, 47,
131282 /* 360 */ 48, 49, 50, 51, 52, 53, 19, 227, 22, 23,
131283 /* 370 */ 230, 22, 96, 152, 27, 28, 29, 30, 31, 32,
131284 /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 30,
131285 /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131286 /* 400 */ 53, 19, 190, 191, 55, 56, 24, 190, 191, 27,
131287 /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131288 /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131289 /* 430 */ 48, 49, 50, 51, 52, 53, 168, 169, 170, 179,
131290 /* 440 */ 180, 171, 96, 19, 172, 173, 97, 98, 188, 179,
131291 /* 450 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35,
131292 /* 460 */ 36, 37, 38, 39, 40, 41, 107, 43, 44, 45,
131293 /* 470 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 207,
131294 /* 480 */ 208, 30, 31, 32, 33, 138, 27, 28, 29, 30,
131295 /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131296 /* 500 */ 41, 181, 43, 44, 45, 46, 47, 48, 49, 50,
131297 /* 510 */ 51, 52, 53, 19, 152, 7, 8, 9, 49, 22,
131298 /* 520 */ 19, 24, 28, 29, 30, 31, 32, 33, 34, 35,
131299 /* 530 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45,
131300 /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 108,
131301 /* 550 */ 109, 110, 101, 55, 53, 193, 172, 173, 29, 30,
131302 /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131303 /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
131304 /* 580 */ 51, 52, 53, 19, 20, 116, 22, 23, 169, 170,
131305 /* 590 */ 121, 207, 85, 55, 56, 97, 19, 20, 195, 22,
131306 /* 600 */ 99, 100, 101, 102, 103, 104, 105, 12, 152, 206,
131307 /* 610 */ 210, 47, 48, 112, 152, 108, 109, 110, 54, 55,
131308 /* 620 */ 56, 221, 222, 223, 47, 48, 119, 120, 172, 173,
131309 /* 630 */ 66, 54, 55, 56, 101, 97, 98, 99, 148, 149,
131310 /* 640 */ 102, 103, 104, 66, 154, 112, 156, 83, 229, 47,
131311 /* 650 */ 48, 113, 57, 163, 194, 195, 92, 246, 247, 95,
131312 /* 660 */ 83, 97, 98, 207, 208, 101, 206, 59, 73, 92,
131313 /* 670 */ 75, 63, 95, 163, 97, 98, 194, 195, 101, 219,
131314 /* 680 */ 85, 181, 19, 152, 175, 77, 196, 152, 206, 19,
131315 /* 690 */ 20, 199, 22, 30, 163, 11, 132, 133, 134, 135,
131316 /* 700 */ 136, 209, 152, 172, 173, 152, 196, 172, 173, 132,
131317 /* 710 */ 133, 134, 135, 136, 164, 92, 213, 47, 48, 49,
131318 /* 720 */ 92, 186, 169, 170, 54, 55, 56, 196, 100, 219,
131319 /* 730 */ 221, 222, 223, 243, 132, 133, 66, 175, 207, 208,
131320 /* 740 */ 152, 231, 119, 120, 19, 20, 236, 22, 152, 38,
131321 /* 750 */ 39, 40, 41, 83, 43, 44, 45, 46, 47, 48,
131322 /* 760 */ 49, 50, 51, 52, 53, 95, 152, 97, 98, 85,
131323 /* 770 */ 107, 101, 47, 48, 163, 112, 92, 152, 152, 54,
131324 /* 780 */ 55, 56, 229, 221, 222, 223, 172, 173, 163, 49,
131325 /* 790 */ 152, 66, 108, 109, 110, 55, 56, 172, 173, 163,
131326 /* 800 */ 186, 22, 132, 133, 134, 135, 136, 196, 83, 43,
131327 /* 810 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131328 /* 820 */ 95, 196, 97, 98, 85, 99, 101, 152, 102, 103,
131329 /* 830 */ 104, 92, 196, 146, 147, 152, 181, 97, 98, 113,
131330 /* 840 */ 19, 20, 152, 22, 218, 22, 116, 108, 109, 110,
131331 /* 850 */ 152, 121, 55, 56, 12, 219, 218, 132, 133, 134,
131332 /* 860 */ 135, 136, 172, 173, 55, 56, 55, 56, 47, 48,
131333 /* 870 */ 172, 173, 236, 152, 5, 54, 55, 56, 55, 10,
131334 /* 880 */ 11, 12, 13, 14, 186, 152, 17, 66, 47, 48,
131335 /* 890 */ 152, 210, 16, 84, 97, 98, 55, 56, 21, 57,
131336 /* 900 */ 217, 122, 22, 152, 83, 152, 97, 98, 97, 98,
131337 /* 910 */ 172, 173, 152, 152, 224, 73, 95, 75, 97, 98,
131338 /* 920 */ 97, 124, 101, 172, 173, 164, 193, 47, 48, 60,
131339 /* 930 */ 163, 62, 172, 173, 24, 55, 56, 186, 97, 98,
131340 /* 940 */ 71, 100, 55, 56, 183, 207, 185, 152, 107, 23,
131341 /* 950 */ 109, 82, 26, 132, 133, 134, 135, 136, 89, 152,
131342 /* 960 */ 26, 92, 93, 196, 88, 55, 90, 152, 91, 152,
131343 /* 970 */ 217, 152, 152, 132, 133, 95, 152, 97, 211, 212,
131344 /* 980 */ 103, 101, 152, 114, 97, 98, 152, 172, 173, 19,
131345 /* 990 */ 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
131346 /* 1000 */ 48, 49, 50, 51, 52, 53, 65, 97, 152, 152,
131347 /* 1010 */ 141, 124, 132, 133, 134, 152, 140, 140, 152, 78,
131348 /* 1020 */ 152, 233, 152, 193, 98, 152, 56, 86, 172, 173,
131349 /* 1030 */ 166, 167, 237, 152, 217, 172, 173, 152, 172, 173,
131350 /* 1040 */ 172, 173, 172, 173, 237, 172, 173, 152, 152, 152,
131351 /* 1050 */ 124, 152, 111, 172, 173, 152, 237, 172, 173, 152,
131352 /* 1060 */ 55, 152, 26, 152, 130, 152, 152, 172, 173, 172,
131353 /* 1070 */ 173, 172, 173, 249, 152, 172, 173, 152, 61, 172,
131354 /* 1080 */ 173, 172, 173, 172, 173, 172, 173, 70, 152, 193,
131355 /* 1090 */ 152, 137, 152, 139, 172, 173, 152, 172, 173, 152,
131356 /* 1100 */ 152, 152, 97, 152, 26, 152, 163, 152, 172, 173,
131357 /* 1110 */ 172, 173, 172, 173, 152, 16, 172, 173, 26, 172,
131358 /* 1120 */ 173, 172, 173, 172, 173, 172, 173, 172, 173, 163,
131359 /* 1130 */ 152, 152, 152, 22, 172, 173, 152, 241, 152, 196,
131360 /* 1140 */ 152, 193, 106, 152, 152, 152, 163, 152, 37, 152,
131361 /* 1150 */ 172, 173, 172, 173, 152, 152, 172, 173, 172, 173,
131362 /* 1160 */ 172, 173, 196, 172, 173, 172, 173, 172, 173, 172,
131363 /* 1170 */ 173, 152, 152, 152, 172, 173, 98, 152, 152, 196,
131364 /* 1180 */ 160, 22, 23, 19, 164, 193, 152, 88, 232, 90,
131365 /* 1190 */ 191, 172, 173, 172, 173, 163, 193, 172, 173, 166,
131366 /* 1200 */ 167, 163, 124, 163, 244, 245, 23, 211, 212, 26,
131367 /* 1210 */ 55, 23, 55, 23, 26, 123, 26, 152, 23, 193,
131368 /* 1220 */ 56, 26, 23, 23, 23, 26, 26, 26, 196, 100,
131369 /* 1230 */ 101, 7, 8, 152, 196, 23, 196, 23, 26, 152,
131370 /* 1240 */ 26, 132, 133, 23, 132, 133, 26, 152, 152, 152,
131371 /* 1250 */ 152, 210, 97, 152, 97, 96, 152, 152, 152, 152,
131372 /* 1260 */ 152, 210, 152, 210, 197, 152, 152, 152, 152, 152,
131373 /* 1270 */ 152, 152, 152, 152, 152, 152, 152, 198, 150, 176,
131374 /* 1280 */ 214, 201, 214, 238, 201, 238, 184, 214, 226, 200,
131375 /* 1290 */ 155, 198, 67, 122, 242, 159, 159, 69, 239, 239,
131376 /* 1300 */ 159, 175, 175, 22, 220, 180, 175, 27, 130, 18,
131377 /* 1310 */ 159, 18, 158, 137, 220, 159, 158, 235, 74, 189,
131378 /* 1320 */ 234, 159, 159, 158, 22, 192, 192, 177, 159, 159,
131379 /* 1330 */ 192, 192, 189, 201, 189, 158, 107, 158, 177, 76,
131380 /* 1340 */ 174, 201, 174, 201, 106, 159, 174, 125, 174, 182,
131381 /* 1350 */ 177, 176, 107, 159, 174, 137, 174, 53, 174, 129,
131382 /* 1360 */ 216, 215, 215, 182, 216, 216, 177, 215, 126, 216,
131383 /* 1370 */ 177, 128, 25, 127, 26, 215, 13, 162, 161, 153,
131384 /* 1380 */ 153, 6, 151, 151, 151, 151, 165, 178, 165, 178,
131385 /* 1390 */ 4, 3, 22, 142, 15, 94, 16, 205, 120, 202,
131386 /* 1400 */ 204, 203, 165, 201, 23, 23, 131, 111, 123, 20,
131387 /* 1410 */ 225, 125, 16, 1, 131, 228, 111, 123, 56, 228,
131388 /* 1420 */ 37, 37, 64, 1, 5, 122, 22, 107, 140, 80,
131389 /* 1430 */ 80, 26, 87, 72, 107, 24, 20, 19, 112, 105,
131390 /* 1440 */ 23, 68, 22, 79, 79, 22, 22, 22, 58, 22,
131391 /* 1450 */ 245, 248, 248, 79, 23, 23, 23, 116, 22, 122,
131392 /* 1460 */ 23, 22, 56, 23, 26, 23, 64, 22, 124, 26,
131393 /* 1470 */ 26, 64, 64, 23, 23, 23, 11, 23, 22, 26,
131394 /* 1480 */ 23, 22, 24, 1, 23, 22, 26, 250, 24, 23,
131395 /* 1490 */ 22, 122, 23, 23, 22, 15, 23, 250, 122, 122,
131396 /* 1500 */ 122,
131397 };
131398 #define YY_SHIFT_USE_DFLT (-95)
131399 #define YY_SHIFT_COUNT (439)
131400 #define YY_SHIFT_MIN (-94)
131401 #define YY_SHIFT_MAX (1482)
131402 static const short yy_shift_ofst[] = {
131403 /* 0 */ 40, 564, 869, 577, 725, 725, 725, 739, -19, 16,
131404 /* 10 */ 16, 100, 725, 725, 725, 725, 725, 725, 725, 841,
131405 /* 20 */ 841, 538, 507, 684, 623, 61, 137, 172, 207, 242,
131406 /* 30 */ 277, 312, 347, 382, 424, 424, 424, 424, 424, 424,
131407 /* 40 */ 424, 424, 424, 424, 424, 424, 424, 424, 424, 459,
131408 /* 50 */ 424, 494, 529, 529, 670, 725, 725, 725, 725, 725,
131409 /* 60 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131410 /* 70 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131411 /* 80 */ 725, 725, 725, 821, 725, 725, 725, 725, 725, 725,
131412 /* 90 */ 725, 725, 725, 725, 725, 725, 725, 952, 711, 711,
131413 /* 100 */ 711, 711, 711, 766, 23, 32, 811, 877, 663, 602,
131414 /* 110 */ 602, 811, 73, 113, -51, -95, -95, -95, 501, 501,
131415 /* 120 */ 501, 595, 595, 809, 205, 276, 811, 811, 811, 811,
131416 /* 130 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131417 /* 140 */ 811, 811, 811, 811, 811, 811, 192, 628, 498, 498,
131418 /* 150 */ 113, -34, -34, -34, -34, -34, -34, -95, -95, -95,
131419 /* 160 */ 880, -94, -94, 726, 740, 99, 797, 887, 349, 811,
131420 /* 170 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131421 /* 180 */ 811, 811, 811, 811, 811, 811, 941, 941, 941, 811,
131422 /* 190 */ 811, 926, 811, 811, 811, -18, 811, 811, 842, 811,
131423 /* 200 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 224,
131424 /* 210 */ 608, 910, 910, 910, 1078, 45, 469, 508, 934, 970,
131425 /* 220 */ 970, 1164, 934, 1164, 1036, 1183, 359, 1017, 970, 954,
131426 /* 230 */ 1017, 1017, 1092, 730, 497, 1225, 1171, 1171, 1228, 1228,
131427 /* 240 */ 1171, 1281, 1280, 1178, 1291, 1291, 1291, 1291, 1171, 1293,
131428 /* 250 */ 1178, 1281, 1280, 1280, 1178, 1171, 1293, 1176, 1244, 1171,
131429 /* 260 */ 1171, 1293, 1302, 1171, 1293, 1171, 1293, 1302, 1229, 1229,
131430 /* 270 */ 1229, 1263, 1302, 1229, 1238, 1229, 1263, 1229, 1229, 1222,
131431 /* 280 */ 1245, 1222, 1245, 1222, 1245, 1222, 1245, 1171, 1171, 1218,
131432 /* 290 */ 1302, 1304, 1304, 1302, 1230, 1242, 1243, 1246, 1178, 1347,
131433 /* 300 */ 1348, 1363, 1363, 1375, 1375, 1375, 1375, -95, -95, -95,
131434 /* 310 */ -95, -95, -95, -95, -95, 451, 876, 346, 1159, 1099,
131435 /* 320 */ 441, 823, 1188, 1111, 1190, 1195, 1199, 1200, 1005, 1129,
131436 /* 330 */ 1224, 533, 1201, 1212, 1155, 1214, 1109, 1112, 1220, 1157,
131437 /* 340 */ 779, 1386, 1388, 1370, 1251, 1379, 1301, 1380, 1381, 1382,
131438 /* 350 */ 1278, 1275, 1296, 1285, 1389, 1286, 1396, 1412, 1294, 1283,
131439 /* 360 */ 1383, 1384, 1305, 1362, 1358, 1303, 1422, 1419, 1404, 1320,
131440 /* 370 */ 1288, 1349, 1405, 1350, 1345, 1361, 1327, 1411, 1416, 1418,
131441 /* 380 */ 1326, 1334, 1420, 1364, 1423, 1424, 1417, 1425, 1365, 1390,
131442 /* 390 */ 1427, 1374, 1373, 1431, 1432, 1433, 1341, 1436, 1437, 1439,
131443 /* 400 */ 1438, 1337, 1440, 1442, 1406, 1402, 1445, 1344, 1443, 1407,
131444 /* 410 */ 1444, 1408, 1443, 1450, 1451, 1452, 1453, 1454, 1456, 1465,
131445 /* 420 */ 1457, 1459, 1458, 1460, 1461, 1463, 1464, 1460, 1466, 1468,
131446 /* 430 */ 1469, 1470, 1472, 1369, 1376, 1377, 1378, 1473, 1480, 1482,
131447 };
131448 #define YY_REDUCE_USE_DFLT (-130)
131449 #define YY_REDUCE_COUNT (314)
131450 #define YY_REDUCE_MIN (-129)
131451 #define YY_REDUCE_MAX (1237)
131452 static const short yy_reduce_ofst[] = {
131453 /* 0 */ -29, 531, 490, 625, -49, 272, 456, 510, 400, 509,
131454 /* 10 */ 562, 114, 535, 614, 698, 384, 738, 751, 690, 419,
131455 /* 20 */ 553, 761, 460, 636, 767, 41, 41, 41, 41, 41,
131456 /* 30 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131457 /* 40 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131458 /* 50 */ 41, 41, 41, 41, 760, 815, 856, 863, 866, 868,
131459 /* 60 */ 870, 873, 881, 885, 895, 897, 899, 903, 907, 909,
131460 /* 70 */ 911, 913, 922, 925, 936, 938, 940, 944, 947, 949,
131461 /* 80 */ 951, 953, 955, 962, 978, 980, 984, 986, 988, 991,
131462 /* 90 */ 993, 995, 997, 1002, 1019, 1021, 1025, 41, 41, 41,
131463 /* 100 */ 41, 41, 41, 41, 41, 41, 896, 140, 260, 98,
131464 /* 110 */ 268, 1020, 41, 482, 41, 41, 41, 41, 270, 270,
131465 /* 120 */ 270, 212, 217, -129, 411, 411, 550, 5, 626, 362,
131466 /* 130 */ 733, 830, 992, 1003, 1026, 795, 683, 807, 638, 819,
131467 /* 140 */ 753, 948, 62, 817, 824, 132, 687, 611, 864, 1033,
131468 /* 150 */ 403, 943, 966, 983, 1032, 1038, 1040, 960, 996, 492,
131469 /* 160 */ -50, 57, 131, 153, 221, 462, 588, 596, 675, 721,
131470 /* 170 */ 820, 834, 857, 914, 979, 1034, 1065, 1081, 1087, 1095,
131471 /* 180 */ 1096, 1097, 1098, 1101, 1104, 1105, 320, 500, 655, 1106,
131472 /* 190 */ 1107, 503, 1108, 1110, 1113, 681, 1114, 1115, 999, 1116,
131473 /* 200 */ 1117, 1118, 221, 1119, 1120, 1121, 1122, 1123, 1124, 788,
131474 /* 210 */ 956, 1041, 1051, 1053, 503, 1067, 1079, 1128, 1080, 1066,
131475 /* 220 */ 1068, 1045, 1083, 1047, 1103, 1102, 1125, 1126, 1073, 1062,
131476 /* 230 */ 1127, 1131, 1089, 1093, 1135, 1052, 1136, 1137, 1059, 1060,
131477 /* 240 */ 1141, 1084, 1130, 1132, 1133, 1134, 1138, 1139, 1151, 1154,
131478 /* 250 */ 1140, 1094, 1143, 1145, 1142, 1156, 1158, 1082, 1086, 1162,
131479 /* 260 */ 1163, 1165, 1150, 1169, 1177, 1170, 1179, 1161, 1166, 1168,
131480 /* 270 */ 1172, 1167, 1173, 1174, 1175, 1180, 1181, 1182, 1184, 1144,
131481 /* 280 */ 1146, 1148, 1147, 1149, 1152, 1153, 1160, 1186, 1194, 1185,
131482 /* 290 */ 1189, 1187, 1191, 1193, 1192, 1196, 1198, 1197, 1202, 1215,
131483 /* 300 */ 1217, 1226, 1227, 1231, 1232, 1233, 1234, 1203, 1204, 1205,
131484 /* 310 */ 1221, 1223, 1209, 1211, 1237,
131485 };
131486 static const YYACTIONTYPE yy_default[] = {
131487 /* 0 */ 1250, 1240, 1240, 1240, 1174, 1174, 1174, 1240, 1071, 1100,
131488 /* 10 */ 1100, 1224, 1301, 1301, 1301, 1301, 1301, 1301, 1173, 1301,
131489 /* 20 */ 1301, 1301, 1301, 1240, 1075, 1106, 1301, 1301, 1301, 1301,
@@ -129130,78 +131547,104 @@
131547 */
131548 #ifdef YYFALLBACK
131549 static const YYCODETYPE yyFallback[] = {
131550 0, /* $ => nothing */
131551 0, /* SEMI => nothing */
131552 55, /* EXPLAIN => ID */
131553 55, /* QUERY => ID */
131554 55, /* PLAN => ID */
131555 55, /* BEGIN => ID */
131556 0, /* TRANSACTION => nothing */
131557 55, /* DEFERRED => ID */
131558 55, /* IMMEDIATE => ID */
131559 55, /* EXCLUSIVE => ID */
131560 0, /* COMMIT => nothing */
131561 55, /* END => ID */
131562 55, /* ROLLBACK => ID */
131563 55, /* SAVEPOINT => ID */
131564 55, /* RELEASE => ID */
131565 0, /* TO => nothing */
131566 0, /* TABLE => nothing */
131567 0, /* CREATE => nothing */
131568 55, /* IF => ID */
131569 0, /* NOT => nothing */
131570 0, /* EXISTS => nothing */
131571 55, /* TEMP => ID */
131572 0, /* LP => nothing */
131573 0, /* RP => nothing */
131574 0, /* AS => nothing */
131575 55, /* WITHOUT => ID */
131576 0, /* COMMA => nothing */
131577 0, /* OR => nothing */
131578 0, /* AND => nothing */
131579 0, /* IS => nothing */
131580 55, /* MATCH => ID */
131581 55, /* LIKE_KW => ID */
131582 0, /* BETWEEN => nothing */
131583 0, /* IN => nothing */
131584 0, /* ISNULL => nothing */
131585 0, /* NOTNULL => nothing */
131586 0, /* NE => nothing */
131587 0, /* EQ => nothing */
131588 0, /* GT => nothing */
131589 0, /* LE => nothing */
131590 0, /* LT => nothing */
131591 0, /* GE => nothing */
131592 0, /* ESCAPE => nothing */
131593 0, /* BITAND => nothing */
131594 0, /* BITOR => nothing */
131595 0, /* LSHIFT => nothing */
131596 0, /* RSHIFT => nothing */
131597 0, /* PLUS => nothing */
131598 0, /* MINUS => nothing */
131599 0, /* STAR => nothing */
131600 0, /* SLASH => nothing */
131601 0, /* REM => nothing */
131602 0, /* CONCAT => nothing */
131603 0, /* COLLATE => nothing */
131604 0, /* BITNOT => nothing */
131605 0, /* ID => nothing */
131606 0, /* INDEXED => nothing */
131607 55, /* ABORT => ID */
131608 55, /* ACTION => ID */
131609 55, /* AFTER => ID */
131610 55, /* ANALYZE => ID */
131611 55, /* ASC => ID */
131612 55, /* ATTACH => ID */
131613 55, /* BEFORE => ID */
131614 55, /* BY => ID */
131615 55, /* CASCADE => ID */
131616 55, /* CAST => ID */
131617 55, /* COLUMNKW => ID */
131618 55, /* CONFLICT => ID */
131619 55, /* DATABASE => ID */
131620 55, /* DESC => ID */
131621 55, /* DETACH => ID */
131622 55, /* EACH => ID */
131623 55, /* FAIL => ID */
131624 55, /* FOR => ID */
131625 55, /* IGNORE => ID */
131626 55, /* INITIALLY => ID */
131627 55, /* INSTEAD => ID */
131628 55, /* NO => ID */
131629 55, /* KEY => ID */
131630 55, /* OF => ID */
131631 55, /* OFFSET => ID */
131632 55, /* PRAGMA => ID */
131633 55, /* RAISE => ID */
131634 55, /* RECURSIVE => ID */
131635 55, /* REPLACE => ID */
131636 55, /* RESTRICT => ID */
131637 55, /* ROW => ID */
131638 55, /* TRIGGER => ID */
131639 55, /* VACUUM => ID */
131640 55, /* VIEW => ID */
131641 55, /* VIRTUAL => ID */
131642 55, /* WITH => ID */
131643 55, /* REINDEX => ID */
131644 55, /* RENAME => ID */
131645 55, /* CTIME_KW => ID */
 
 
131646 };
131647 #endif /* YYFALLBACK */
131648
131649 /* The following structure represents a single element of the
131650 ** parser's stack. Information stored includes:
@@ -129288,29 +131731,29 @@
131731 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
131732 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
131733 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
131734 "TABLE", "CREATE", "IF", "NOT",
131735 "EXISTS", "TEMP", "LP", "RP",
131736 "AS", "WITHOUT", "COMMA", "OR",
131737 "AND", "IS", "MATCH", "LIKE_KW",
131738 "BETWEEN", "IN", "ISNULL", "NOTNULL",
131739 "NE", "EQ", "GT", "LE",
131740 "LT", "GE", "ESCAPE", "BITAND",
131741 "BITOR", "LSHIFT", "RSHIFT", "PLUS",
131742 "MINUS", "STAR", "SLASH", "REM",
131743 "CONCAT", "COLLATE", "BITNOT", "ID",
131744 "INDEXED", "ABORT", "ACTION", "AFTER",
131745 "ANALYZE", "ASC", "ATTACH", "BEFORE",
131746 "BY", "CASCADE", "CAST", "COLUMNKW",
131747 "CONFLICT", "DATABASE", "DESC", "DETACH",
131748 "EACH", "FAIL", "FOR", "IGNORE",
131749 "INITIALLY", "INSTEAD", "NO", "KEY",
131750 "OF", "OFFSET", "PRAGMA", "RAISE",
131751 "RECURSIVE", "REPLACE", "RESTRICT", "ROW",
131752 "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
131753 "WITH", "REINDEX", "RENAME", "CTIME_KW",
131754 "ANY", "STRING", "JOIN_KW", "CONSTRAINT",
 
 
 
 
 
 
 
131755 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
131756 "CHECK", "REFERENCES", "AUTOINCR", "ON",
131757 "INSERT", "DELETE", "UPDATE", "SET",
131758 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
131759 "ALL", "EXCEPT", "INTERSECT", "SELECT",
@@ -131086,26 +133529,27 @@
133529 yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
133530 }
133531 break;
133532 case 156: /* expr ::= VARIABLE */
133533 {
133534 if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
133535 spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
133536 sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
133537 }else{
133538 /* When doing a nested parse, one can include terms in an expression
133539 ** that look like this: #1 #2 ... These terms refer to registers
133540 ** in the virtual machine. #N is the N-th register. */
133541 Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
133542 assert( t.n>=2 );
133543 spanSet(&yymsp[0].minor.yy342, &t, &t);
133544 if( pParse->nested==0 ){
133545 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
133546 yymsp[0].minor.yy342.pExpr = 0;
133547 }else{
133548 yymsp[0].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
133549 if( yymsp[0].minor.yy342.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy342.pExpr->iTable);
133550 }
 
 
 
133551 }
133552 }
133553 break;
133554 case 157: /* expr ::= expr COLLATE ID|STRING */
133555 {
@@ -131286,60 +133730,37 @@
133730 break;
133731 case 188: /* expr ::= LP select RP */
133732 {
133733 spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
133734 yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
133735 sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy342.pExpr, yymsp[-1].minor.yy159);
 
 
 
 
 
 
133736 }
133737 break;
133738 case 189: /* expr ::= expr in_op LP select RP */
133739 {
133740 yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
133741 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy342.pExpr, yymsp[-1].minor.yy159);
 
 
 
 
 
 
133742 exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
133743 yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
133744 }
133745 break;
133746 case 190: /* expr ::= expr in_op nm dbnm */
133747 {
133748 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
133749 Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
133750 yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
133751 sqlite3PExprAddSelect(pParse, yymsp[-3].minor.yy342.pExpr, pSelect);
 
 
 
 
 
 
133752 exprNot(pParse, yymsp[-2].minor.yy392, &yymsp[-3].minor.yy342);
133753 yymsp[-3].minor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
133754 }
133755 break;
133756 case 191: /* expr ::= EXISTS LP select RP */
133757 {
133758 Expr *p;
133759 spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
133760 p = yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
133761 sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy159);
 
 
 
 
 
 
133762 }
133763 break;
133764 case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
133765 {
133766 spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
@@ -132820,11 +135241,11 @@
135241 ** will take responsibility for freeing the Table structure.
135242 */
135243 sqlite3DeleteTable(db, pParse->pNewTable);
135244 }
135245
135246 if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
135247 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
135248 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
135249 sqlite3DbFree(db, pParse->azVar);
135250 while( pParse->pAinc ){
135251 AutoincInfo *p = pParse->pAinc;
@@ -134030,10 +136451,11 @@
136451 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
136452 } aFlagOp[] = {
136453 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
136454 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
136455 { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
136456 { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
136457 };
136458 unsigned int i;
136459 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
136460 for(i=0; i<ArraySize(aFlagOp); i++){
136461 if( aFlagOp[i].op==op ){
@@ -135148,10 +137570,31 @@
137570 db->pRollbackArg = pArg;
137571 sqlite3_mutex_leave(db->mutex);
137572 return pRet;
137573 }
137574
137575 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
137576 /*
137577 ** Register a callback to be invoked each time a row is updated,
137578 ** inserted or deleted using this database connection.
137579 */
137580 SQLITE_API void *SQLITE_STDCALL sqlite3_preupdate_hook(
137581 sqlite3 *db, /* Attach the hook to this database */
137582 void(*xCallback)( /* Callback function */
137583 void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
137584 void *pArg /* First callback argument */
137585 ){
137586 void *pRet;
137587 sqlite3_mutex_enter(db->mutex);
137588 pRet = db->pPreUpdateArg;
137589 db->xPreUpdateCallback = xCallback;
137590 db->pPreUpdateArg = pArg;
137591 sqlite3_mutex_leave(db->mutex);
137592 return pRet;
137593 }
137594 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
137595
137596 #ifndef SQLITE_OMIT_WAL
137597 /*
137598 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
137599 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
137600 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
@@ -160507,19 +162950,21 @@
162950 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
162951 **
162952 ** http://www.icu-project.org/userguide/posix.html#case_mappings
162953 */
162954 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
162955 const UChar *zInput; /* Pointer to input string */
162956 UChar *zOutput = 0; /* Pointer to output buffer */
162957 int nInput; /* Size of utf-16 input string in bytes */
162958 int nOut; /* Size of output buffer in bytes */
162959 int cnt;
162960 int bToUpper; /* True for toupper(), false for tolower() */
162961 UErrorCode status;
162962 const char *zLocale = 0;
162963
162964 assert(nArg==1 || nArg==2);
162965 bToUpper = (sqlite3_user_data(p)!=0);
162966 if( nArg==2 ){
162967 zLocale = (const char *)sqlite3_value_text(apArg[1]);
162968 }
162969
162970 zInput = sqlite3_value_text16(apArg[0]);
@@ -160539,23 +162984,27 @@
162984 sqlite3_result_error_nomem(p);
162985 return;
162986 }
162987 zOutput = zNew;
162988 status = U_ZERO_ERROR;
162989 if( bToUpper ){
162990 nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
162991 }else{
162992 nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
162993 }
162994
162995 if( U_SUCCESS(status) ){
162996 sqlite3_result_text16(p, zOutput, nOut, xFree);
162997 }else if( status==U_BUFFER_OVERFLOW_ERROR ){
162998 assert( cnt==0 );
162999 continue;
163000 }else{
163001 icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
163002 }
163003 return;
163004 }
163005 assert( 0 ); /* Unreachable */
163006 }
163007
163008 /*
163009 ** Collation sequence destructor function. The pCtx argument points to
163010 ** a UCollator structure previously allocated using ucol_open().
@@ -161368,10 +163817,42 @@
163817 const char *zTarget,
163818 const char *zRbu,
163819 const char *zState
163820 );
163821
163822 /*
163823 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
163824 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
163825 ** that it can be suspended and resumed like an RBU update.
163826 **
163827 ** The second argument to this function, which may not be NULL, identifies
163828 ** a database in which to store the state of the RBU vacuum operation if
163829 ** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
163830 ** an RBU vacuum operation, the state database should either not exist or
163831 ** be empty (contain no tables). If an RBU vacuum is suspended by calling
163832 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
163833 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
163834 ** The vacuum can be resumed by calling this function to open a new RBU
163835 ** handle specifying the same target and state databases.
163836 **
163837 ** This function does not delete the state database after an RBU vacuum
163838 ** is completed, even if it created it. However, if the call to
163839 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
163840 ** of the state tables within the state database are zeroed. This way,
163841 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
163842 ** new RBU vacuum operation.
163843 **
163844 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
163845 ** describing the sqlite3rbu_create_vfs() API function below for
163846 ** a description of the complications associated with using RBU with
163847 ** zipvfs databases.
163848 */
163849 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
163850 const char *zTarget,
163851 const char *zState
163852 );
163853
163854 /*
163855 ** Internally, each RBU connection uses a separate SQLite database
163856 ** connection to access the target and rbu update databases. This
163857 ** API allows the application direct access to these database handles.
163858 **
@@ -161646,10 +164127,11 @@
164127 typedef struct rbu_file rbu_file;
164128 typedef struct RbuUpdateStmt RbuUpdateStmt;
164129
164130 #if !defined(SQLITE_AMALGAMATION)
164131 typedef unsigned int u32;
164132 typedef unsigned short u16;
164133 typedef unsigned char u8;
164134 typedef sqlite3_int64 i64;
164135 #endif
164136
164137 /*
@@ -161658,10 +164140,12 @@
164140 ** format.
164141 */
164142 #define WAL_LOCK_WRITE 0
164143 #define WAL_LOCK_CKPT 1
164144 #define WAL_LOCK_READ0 3
164145
164146 #define SQLITE_FCNTL_RBUCNT 5149216
164147
164148 /*
164149 ** A structure to store values read from the rbu_state table in memory.
164150 */
164151 struct RbuState {
@@ -161837,10 +164321,14 @@
164321 int nFrameAlloc; /* Allocated size of aFrame[] array */
164322 RbuFrame *aFrame;
164323 int pgsz;
164324 u8 *aBuf;
164325 i64 iWalCksum;
164326
164327 /* Used in RBU vacuum mode only */
164328 int nRbu; /* Number of RBU VFS in the stack */
164329 rbu_file *pRbuFd; /* Fd for main db of dbRbu */
164330 };
164331
164332 /*
164333 ** An rbu VFS is implemented using an instance of this structure.
164334 */
@@ -161862,10 +164350,11 @@
164350 sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
164351
164352 int openFlags; /* Flags this file was opened with */
164353 u32 iCookie; /* Cookie value for main db files */
164354 u8 iWriteVer; /* "write-version" value for main db files */
164355 u8 bNolock; /* True to fail EXCLUSIVE locks */
164356
164357 int nShm; /* Number of entries in apShm[] array */
164358 char **apShm; /* Array of mmap'd *-shm regions */
164359 char *zDel; /* Delete this when closing file */
164360
@@ -161872,10 +164361,15 @@
164361 const char *zWal; /* Wal filename for this main db file */
164362 rbu_file *pWalFd; /* Wal file descriptor for this main db */
164363 rbu_file *pMainNext; /* Next MAIN_DB file */
164364 };
164365
164366 /*
164367 ** True for an RBU vacuum handle, or false otherwise.
164368 */
164369 #define rbuIsVacuum(p) ((p)->zTarget==0)
164370
164371
164372 /*************************************************************************
164373 ** The following three functions, found below:
164374 **
164375 ** rbuDeltaGetInt()
@@ -162320,12 +164814,15 @@
164814 }
164815
164816
164817 /*
164818 ** The implementation of the rbu_target_name() SQL function. This function
164819 ** accepts one or two arguments. The first argument is the name of a table -
164820 ** the name of a table in the RBU database. The second, if it is present, is 1
164821 ** for a view or 0 for a table.
164822 **
164823 ** For a non-vacuum RBU handle, if the table name matches the pattern:
164824 **
164825 ** data[0-9]_<name>
164826 **
164827 ** where <name> is any sequence of 1 or more characters, <name> is returned.
164828 ** Otherwise, if the only argument does not match the above pattern, an SQL
@@ -162332,25 +164829,37 @@
164829 ** NULL is returned.
164830 **
164831 ** "data_t1" -> "t1"
164832 ** "data0123_t2" -> "t2"
164833 ** "dataAB_t3" -> NULL
164834 **
164835 ** For an rbu vacuum handle, a copy of the first argument is returned if
164836 ** the second argument is either missing or 0 (not a view).
164837 */
164838 static void rbuTargetNameFunc(
164839 sqlite3_context *pCtx,
164840 int argc,
164841 sqlite3_value **argv
164842 ){
164843 sqlite3rbu *p = sqlite3_user_data(pCtx);
164844 const char *zIn;
164845 assert( argc==1 || argc==2 );
164846
164847 zIn = (const char*)sqlite3_value_text(argv[0]);
164848 if( zIn ){
164849 if( rbuIsVacuum(p) ){
164850 if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
164851 sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
164852 }
164853 }else{
164854 if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
164855 int i;
164856 for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
164857 if( zIn[i]=='_' && zIn[i+1] ){
164858 sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
164859 }
164860 }
164861 }
164862 }
164863 }
164864
164865 /*
@@ -162364,11 +164873,12 @@
164873 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
164874 int rc;
164875 memset(pIter, 0, sizeof(RbuObjIter));
164876
164877 rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
164878 "SELECT rbu_target_name(name, type='view') AS target, name "
164879 "FROM sqlite_master "
164880 "WHERE type IN ('table', 'view') AND target IS NOT NULL "
164881 "ORDER BY name"
164882 );
164883
164884 if( rc==SQLITE_OK ){
@@ -162740,10 +165250,11 @@
165250 }
165251 sqlite3_finalize(pStmt);
165252 pStmt = 0;
165253
165254 if( p->rc==SQLITE_OK
165255 && rbuIsVacuum(p)==0
165256 && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
165257 ){
165258 p->rc = SQLITE_ERROR;
165259 p->zErrmsg = sqlite3_mprintf(
165260 "table %q %s rbu_rowid column", pIter->zDataTbl,
@@ -162879,10 +165390,12 @@
165390 if( pIter->eType==RBU_PK_IPK ){
165391 int i;
165392 for(i=0; pIter->abTblPk[i]==0; i++);
165393 assert( i<pIter->nTblCol );
165394 zCol = pIter->azTblCol[i];
165395 }else if( rbuIsVacuum(p) ){
165396 zCol = "_rowid_";
165397 }else{
165398 zCol = "rbu_rowid";
165399 }
165400 zType = "INTEGER";
165401 }else{
@@ -163419,20 +165932,29 @@
165932 sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
165933 );
165934 }
165935
165936 /* And to delete index entries */
165937 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
165938 p->rc = prepareFreeAndCollectError(
165939 p->dbMain, &pIter->pDelete, &p->zErrmsg,
165940 sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
165941 );
165942 }
165943
165944 /* Create the SELECT statement to read keys in sorted order */
165945 if( p->rc==SQLITE_OK ){
165946 char *zSql;
165947 if( rbuIsVacuum(p) ){
165948 zSql = sqlite3_mprintf(
165949 "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
165950 zCollist,
165951 pIter->zDataTbl,
165952 zCollist, zLimit
165953 );
165954 }else
165955
165956 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
165957 zSql = sqlite3_mprintf(
165958 "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
165959 zCollist, p->zStateDb, pIter->zDataTbl,
165960 zCollist, zLimit
@@ -163455,11 +165977,13 @@
165977 sqlite3_free(zImposterCols);
165978 sqlite3_free(zImposterPK);
165979 sqlite3_free(zWhere);
165980 sqlite3_free(zBind);
165981 }else{
165982 int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
165983 ||(pIter->eType==RBU_PK_NONE)
165984 ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
165985 const char *zTbl = pIter->zTbl; /* Table this step applies to */
165986 const char *zWrite; /* Imposter table name */
165987
165988 char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
165989 char *zWhere = rbuObjIterGetWhere(p, pIter);
@@ -163482,20 +166006,22 @@
166006 zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
166007 )
166008 );
166009 }
166010
166011 /* Create the DELETE statement to write to the target PK b-tree.
166012 ** Because it only performs INSERT operations, this is not required for
166013 ** an rbu vacuum handle. */
166014 if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166015 p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
166016 sqlite3_mprintf(
166017 "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
166018 )
166019 );
166020 }
166021
166022 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
166023 const char *zRbuRowid = "";
166024 if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166025 zRbuRowid = ", rbu_rowid";
166026 }
166027
@@ -163541,14 +166067,20 @@
166067 rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
166068 }
166069
166070 /* Create the SELECT statement to read keys from data_xxx */
166071 if( p->rc==SQLITE_OK ){
166072 const char *zRbuRowid = "";
166073 if( bRbuRowid ){
166074 zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
166075 }
166076 p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
166077 sqlite3_mprintf(
166078 "SELECT %s,%s rbu_control%s FROM '%q'%s",
166079 zCollist,
166080 (rbuIsVacuum(p) ? "0 AS " : ""),
166081 zRbuRowid,
166082 pIter->zDataTbl, zLimit
166083 )
166084 );
166085 }
166086
@@ -163639,44 +166171,231 @@
166171 }
166172
166173 return p->rc;
166174 }
166175
166176 static sqlite3 *rbuOpenDbhandle(
166177 sqlite3rbu *p,
166178 const char *zName,
166179 int bUseVfs
166180 ){
166181 sqlite3 *db = 0;
166182 if( p->rc==SQLITE_OK ){
166183 const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
166184 p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
166185 if( p->rc ){
166186 p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166187 sqlite3_close(db);
166188 db = 0;
166189 }
166190 }
166191 return db;
166192 }
166193
166194 /*
166195 ** Free an RbuState object allocated by rbuLoadState().
166196 */
166197 static void rbuFreeState(RbuState *p){
166198 if( p ){
166199 sqlite3_free(p->zTbl);
166200 sqlite3_free(p->zIdx);
166201 sqlite3_free(p);
166202 }
166203 }
166204
166205 /*
166206 ** Allocate an RbuState object and load the contents of the rbu_state
166207 ** table into it. Return a pointer to the new object. It is the
166208 ** responsibility of the caller to eventually free the object using
166209 ** sqlite3_free().
166210 **
166211 ** If an error occurs, leave an error code and message in the rbu handle
166212 ** and return NULL.
166213 */
166214 static RbuState *rbuLoadState(sqlite3rbu *p){
166215 RbuState *pRet = 0;
166216 sqlite3_stmt *pStmt = 0;
166217 int rc;
166218 int rc2;
166219
166220 pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
166221 if( pRet==0 ) return 0;
166222
166223 rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
166224 sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
166225 );
166226 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166227 switch( sqlite3_column_int(pStmt, 0) ){
166228 case RBU_STATE_STAGE:
166229 pRet->eStage = sqlite3_column_int(pStmt, 1);
166230 if( pRet->eStage!=RBU_STAGE_OAL
166231 && pRet->eStage!=RBU_STAGE_MOVE
166232 && pRet->eStage!=RBU_STAGE_CKPT
166233 ){
166234 p->rc = SQLITE_CORRUPT;
166235 }
166236 break;
166237
166238 case RBU_STATE_TBL:
166239 pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166240 break;
166241
166242 case RBU_STATE_IDX:
166243 pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166244 break;
166245
166246 case RBU_STATE_ROW:
166247 pRet->nRow = sqlite3_column_int(pStmt, 1);
166248 break;
166249
166250 case RBU_STATE_PROGRESS:
166251 pRet->nProgress = sqlite3_column_int64(pStmt, 1);
166252 break;
166253
166254 case RBU_STATE_CKPT:
166255 pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
166256 break;
166257
166258 case RBU_STATE_COOKIE:
166259 pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
166260 break;
166261
166262 case RBU_STATE_OALSZ:
166263 pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
166264 break;
166265
166266 case RBU_STATE_PHASEONESTEP:
166267 pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
166268 break;
166269
166270 default:
166271 rc = SQLITE_CORRUPT;
166272 break;
166273 }
166274 }
166275 rc2 = sqlite3_finalize(pStmt);
166276 if( rc==SQLITE_OK ) rc = rc2;
166277
166278 p->rc = rc;
166279 return pRet;
166280 }
166281
166282
166283 /*
166284 ** Open the database handle and attach the RBU database as "rbu". If an
166285 ** error occurs, leave an error code and message in the RBU handle.
166286 */
166287 static void rbuOpenDatabase(sqlite3rbu *p){
166288 assert( p->rc==SQLITE_OK );
166289 assert( p->dbMain==0 && p->dbRbu==0 );
166290 assert( rbuIsVacuum(p) || p->zTarget!=0 );
166291
166292 /* Open the RBU database */
166293 p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
166294
166295 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166296 sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166297 }
166298
166299 /* If using separate RBU and state databases, attach the state database to
166300 ** the RBU db handle now. */
166301 if( p->zState ){
166302 rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
166303 memcpy(p->zStateDb, "stat", 4);
166304 }else{
166305 memcpy(p->zStateDb, "main", 4);
166306 }
166307
166308 #if 0
166309 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166310 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
166311 }
166312 #endif
166313
166314 /* If it has not already been created, create the rbu_state table */
166315 rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
166316
166317 #if 0
166318 if( rbuIsVacuum(p) ){
166319 if( p->rc==SQLITE_OK ){
166320 int rc2;
166321 int bOk = 0;
166322 sqlite3_stmt *pCnt = 0;
166323 p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
166324 "SELECT count(*) FROM stat.sqlite_master"
166325 );
166326 if( p->rc==SQLITE_OK
166327 && sqlite3_step(pCnt)==SQLITE_ROW
166328 && 1==sqlite3_column_int(pCnt, 0)
166329 ){
166330 bOk = 1;
166331 }
166332 rc2 = sqlite3_finalize(pCnt);
166333 if( p->rc==SQLITE_OK ) p->rc = rc2;
166334
166335 if( p->rc==SQLITE_OK && bOk==0 ){
166336 p->rc = SQLITE_ERROR;
166337 p->zErrmsg = sqlite3_mprintf("invalid state database");
166338 }
166339
166340 if( p->rc==SQLITE_OK ){
166341 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
166342 }
166343 }
166344 }
166345 #endif
166346
166347 if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166348 int bOpen = 0;
166349 int rc;
166350 p->nRbu = 0;
166351 p->pRbuFd = 0;
166352 rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166353 if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
166354 if( p->eStage>=RBU_STAGE_MOVE ){
166355 bOpen = 1;
166356 }else{
166357 RbuState *pState = rbuLoadState(p);
166358 if( pState ){
166359 bOpen = (pState->eStage>RBU_STAGE_MOVE);
166360 rbuFreeState(pState);
166361 }
166362 }
166363 if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
166364 }
166365
166366 p->eStage = 0;
166367 if( p->rc==SQLITE_OK && p->dbMain==0 ){
166368 if( !rbuIsVacuum(p) ){
166369 p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
166370 }else if( p->pRbuFd->pWalFd ){
166371 p->rc = SQLITE_ERROR;
166372 p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
166373 }else{
166374 char *zTarget;
166375 char *zExtra = 0;
166376 if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
166377 zExtra = &p->zRbu[5];
166378 while( *zExtra ){
166379 if( *zExtra++=='?' ) break;
166380 }
166381 if( *zExtra=='\0' ) zExtra = 0;
166382 }
166383
166384 zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
166385 sqlite3_db_filename(p->dbRbu, "main"),
166386 (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
166387 );
166388
166389 if( zTarget==0 ){
166390 p->rc = SQLITE_NOMEM;
166391 return;
166392 }
166393 p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
166394 sqlite3_free(zTarget);
166395 }
166396 }
166397
166398 if( p->rc==SQLITE_OK ){
166399 p->rc = sqlite3_create_function(p->dbMain,
166400 "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
166401 );
@@ -163688,11 +166407,11 @@
166407 );
166408 }
166409
166410 if( p->rc==SQLITE_OK ){
166411 p->rc = sqlite3_create_function(p->dbRbu,
166412 "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
166413 );
166414 }
166415
166416 if( p->rc==SQLITE_OK ){
166417 p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
@@ -163947,13 +166666,19 @@
166666 ** If an error occurs, leave an error code and error message in the rbu
166667 ** handle.
166668 */
166669 static void rbuMoveOalFile(sqlite3rbu *p){
166670 const char *zBase = sqlite3_db_filename(p->dbMain, "main");
166671 const char *zMove = zBase;
166672 char *zOal;
166673 char *zWal;
166674
166675 if( rbuIsVacuum(p) ){
166676 zMove = sqlite3_db_filename(p->dbRbu, "main");
166677 }
166678 zOal = sqlite3_mprintf("%s-oal", zMove);
166679 zWal = sqlite3_mprintf("%s-wal", zMove);
166680
166681 assert( p->eStage==RBU_STAGE_MOVE );
166682 assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
166683 if( zWal==0 || zOal==0 ){
166684 p->rc = SQLITE_NOMEM;
@@ -163970,12 +166695,12 @@
166695 rbuFileSuffix3(zBase, zWal);
166696 rbuFileSuffix3(zBase, zOal);
166697
166698 /* Re-open the databases. */
166699 rbuObjIterFinalize(&p->objiter);
 
166700 sqlite3_close(p->dbRbu);
166701 sqlite3_close(p->dbMain);
166702 p->dbMain = 0;
166703 p->dbRbu = 0;
166704
166705 #if defined(_WIN32_WCE)
166706 {
@@ -164133,23 +166858,28 @@
166858
166859 pVal = sqlite3_column_value(pIter->pSelect, i);
166860 p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
166861 if( p->rc ) return;
166862 }
166863 if( pIter->zIdx==0 ){
166864 if( pIter->eType==RBU_PK_VTAB
166865 || pIter->eType==RBU_PK_NONE
166866 || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
166867 ){
166868 /* For a virtual table, or a table with no primary key, the
166869 ** SELECT statement is:
166870 **
166871 ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
166872 **
166873 ** Hence column_value(pIter->nCol+1).
166874 */
166875 assertColumnName(pIter->pSelect, pIter->nCol+1,
166876 rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
166877 );
166878 pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
166879 p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
166880 }
166881 }
166882 if( p->rc==SQLITE_OK ){
166883 sqlite3_step(pWriter);
166884 p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
166885 }
@@ -164224,17 +166954,22 @@
166954 return p->rc;
166955 }
166956
166957 /*
166958 ** Increment the schema cookie of the main database opened by p->dbMain.
166959 **
166960 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
166961 ** opened by p->dbMain to one more than the schema cookie of the main
166962 ** db opened by p->dbRbu.
166963 */
166964 static void rbuIncrSchemaCookie(sqlite3rbu *p){
166965 if( p->rc==SQLITE_OK ){
166966 sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
166967 int iCookie = 1000000;
166968 sqlite3_stmt *pStmt;
166969
166970 p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
166971 "PRAGMA schema_version"
166972 );
166973 if( p->rc==SQLITE_OK ){
166974 /* Coverage: it may be that this sqlite3_step() cannot fail. There
166975 ** is already a transaction open, so the prepared statement cannot
@@ -164258,10 +166993,11 @@
166993 ** are determined by inspecting the rbu handle passed as the first argument.
166994 */
166995 static void rbuSaveState(sqlite3rbu *p, int eStage){
166996 if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
166997 sqlite3_stmt *pInsert = 0;
166998 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
166999 int rc;
167000
167001 assert( p->zErrmsg==0 );
167002 rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
167003 sqlite3_mprintf(
@@ -164280,11 +167016,11 @@
167016 RBU_STATE_TBL, p->objiter.zTbl,
167017 RBU_STATE_IDX, p->objiter.zIdx,
167018 RBU_STATE_ROW, p->nStep,
167019 RBU_STATE_PROGRESS, p->nProgress,
167020 RBU_STATE_CKPT, p->iWalCksum,
167021 RBU_STATE_COOKIE, (i64)pFd->iCookie,
167022 RBU_STATE_OALSZ, p->iOalSz,
167023 RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
167024 )
167025 );
167026 assert( pInsert==0 || rc==SQLITE_OK );
@@ -164295,26 +167031,121 @@
167031 }
167032 if( rc!=SQLITE_OK ) p->rc = rc;
167033 }
167034 }
167035
167036
167037 /*
167038 ** The second argument passed to this function is the name of a PRAGMA
167039 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
167040 ** This function executes the following on sqlite3rbu.dbRbu:
167041 **
167042 ** "PRAGMA main.$zPragma"
167043 **
167044 ** where $zPragma is the string passed as the second argument, then
167045 ** on sqlite3rbu.dbMain:
167046 **
167047 ** "PRAGMA main.$zPragma = $val"
167048 **
167049 ** where $val is the value returned by the first PRAGMA invocation.
167050 **
167051 ** In short, it copies the value of the specified PRAGMA setting from
167052 ** dbRbu to dbMain.
167053 */
167054 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
167055 if( p->rc==SQLITE_OK ){
167056 sqlite3_stmt *pPragma = 0;
167057 p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
167058 sqlite3_mprintf("PRAGMA main.%s", zPragma)
167059 );
167060 if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
167061 p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
167062 zPragma, sqlite3_column_int(pPragma, 0)
167063 );
167064 }
167065 rbuFinalize(p, pPragma);
167066 }
167067 }
167068
167069 /*
167070 ** The RBU handle passed as the only argument has just been opened and
167071 ** the state database is empty. If this RBU handle was opened for an
167072 ** RBU vacuum operation, create the schema in the target db.
167073 */
167074 static void rbuCreateTargetSchema(sqlite3rbu *p){
167075 sqlite3_stmt *pSql = 0;
167076 sqlite3_stmt *pInsert = 0;
167077
167078 assert( rbuIsVacuum(p) );
167079 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
167080 if( p->rc==SQLITE_OK ){
167081 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167082 "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
167083 " AND name!='sqlite_sequence' "
167084 " ORDER BY type DESC"
167085 );
167086 }
167087
167088 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167089 const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
167090 p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
167091 }
167092 rbuFinalize(p, pSql);
167093 if( p->rc!=SQLITE_OK ) return;
167094
167095 if( p->rc==SQLITE_OK ){
167096 p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167097 "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
167098 );
167099 }
167100
167101 if( p->rc==SQLITE_OK ){
167102 p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
167103 "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
167104 );
167105 }
167106
167107 while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167108 int i;
167109 for(i=0; i<5; i++){
167110 sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
167111 }
167112 sqlite3_step(pInsert);
167113 p->rc = sqlite3_reset(pInsert);
167114 }
167115 if( p->rc==SQLITE_OK ){
167116 p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
167117 }
167118
167119 rbuFinalize(p, pSql);
167120 rbuFinalize(p, pInsert);
167121 }
167122
167123 /*
167124 ** Step the RBU object.
167125 */
167126 SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
167127 if( p ){
167128 switch( p->eStage ){
167129 case RBU_STAGE_OAL: {
167130 RbuObjIter *pIter = &p->objiter;
167131
167132 /* If this is an RBU vacuum operation and the state table was empty
167133 ** when this handle was opened, create the target database schema. */
167134 if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
167135 rbuCreateTargetSchema(p);
167136 rbuCopyPragma(p, "user_version");
167137 rbuCopyPragma(p, "application_id");
167138 }
167139
167140 while( p->rc==SQLITE_OK && pIter->zTbl ){
167141
167142 if( pIter->bCleanup ){
167143 /* Clean up the rbu_tmp_xxx table for the previous table. It
167144 ** cannot be dropped as there are currently active SQL statements.
167145 ** But the contents can be deleted. */
167146 if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
167147 rbuMPrintfExec(p, p->dbRbu,
167148 "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
167149 );
167150 }
167151 }else{
@@ -164397,98 +167228,10 @@
167228 }else{
167229 return SQLITE_NOMEM;
167230 }
167231 }
167232
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167233 /*
167234 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
167235 ** otherwise. Either or both argument may be NULL. Two NULL values are
167236 ** considered equal, and NULL is considered distinct from all other values.
167237 */
@@ -164674,20 +167417,18 @@
167417 }
167418 }
167419 }
167420 }
167421
167422
167423 static sqlite3rbu *openRbuHandle(
 
 
167424 const char *zTarget,
167425 const char *zRbu,
167426 const char *zState
167427 ){
167428 sqlite3rbu *p;
167429 size_t nTarget = zTarget ? strlen(zTarget) : 0;
167430 size_t nRbu = strlen(zRbu);
167431 size_t nState = zState ? strlen(zState) : 0;
167432 size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
167433
167434 p = (sqlite3rbu*)sqlite3_malloc64(nByte);
@@ -164696,26 +167437,28 @@
167437
167438 /* Create the custom VFS. */
167439 memset(p, 0, sizeof(sqlite3rbu));
167440 rbuCreateVfs(p);
167441
167442 /* Open the target, RBU and state databases */
167443 if( p->rc==SQLITE_OK ){
167444 char *pCsr = (char*)&p[1];
167445 if( zTarget ){
167446 p->zTarget = pCsr;
167447 memcpy(p->zTarget, zTarget, nTarget+1);
167448 pCsr += nTarget+1;
167449 }
167450 p->zRbu = pCsr;
167451 memcpy(p->zRbu, zRbu, nRbu+1);
167452 pCsr += nRbu+1;
167453 if( zState ){
167454 p->zState = pCsr;
167455 memcpy(p->zState, zState, nState+1);
167456 }
167457 rbuOpenDatabase(p);
167458 }
167459
 
 
 
167460 if( p->rc==SQLITE_OK ){
167461 pState = rbuLoadState(p);
167462 assert( pState || p->rc!=SQLITE_OK );
167463 if( p->rc==SQLITE_OK ){
167464
@@ -164741,31 +167484,43 @@
167484 p->eStage = RBU_STAGE_CKPT;
167485 p->nStep = 0;
167486 }
167487 }
167488
167489 if( p->rc==SQLITE_OK
167490 && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
167491 && pState->eStage!=0
167492 ){
167493 rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167494 if( pFd->iCookie!=pState->iCookie ){
167495 /* At this point (pTargetFd->iCookie) contains the value of the
167496 ** change-counter cookie (the thing that gets incremented when a
167497 ** transaction is committed in rollback mode) currently stored on
167498 ** page 1 of the database file. */
167499 p->rc = SQLITE_BUSY;
167500 p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
167501 (rbuIsVacuum(p) ? "vacuum" : "update")
167502 );
167503 }
167504 }
167505
167506 if( p->rc==SQLITE_OK ){
167507 if( p->eStage==RBU_STAGE_OAL ){
167508 sqlite3 *db = p->dbMain;
167509
167510 if( pState->eStage==0 && rbuIsVacuum(p) ){
167511 rbuCopyPragma(p, "page_size");
167512 rbuCopyPragma(p, "auto_vacuum");
167513 }
167514
167515 /* Open transactions both databases. The *-oal file is opened or
167516 ** created at this point. */
167517 if( p->rc==SQLITE_OK ){
167518 p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
167519 }
167520 if( p->rc==SQLITE_OK ){
167521 p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
167522 }
167523
167524 /* Check if the main database is a zipvfs db. If it is, set the upper
167525 ** level pager to use "journal_mode=off". This prevents it from
167526 ** generating a large journal using a temp file. */
@@ -164806,10 +167561,32 @@
167561 }
167562
167563 return p;
167564 }
167565
167566 /*
167567 ** Open and return a new RBU handle.
167568 */
167569 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
167570 const char *zTarget,
167571 const char *zRbu,
167572 const char *zState
167573 ){
167574 /* TODO: Check that zTarget and zRbu are non-NULL */
167575 return openRbuHandle(zTarget, zRbu, zState);
167576 }
167577
167578 /*
167579 ** Open a handle to begin or resume an RBU VACUUM operation.
167580 */
167581 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
167582 const char *zTarget,
167583 const char *zState
167584 ){
167585 /* TODO: Check that both arguments are non-NULL */
167586 return openRbuHandle(0, zTarget, zState);
167587 }
167588
167589 /*
167590 ** Return the database handle used by pRbu.
167591 */
167592 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
@@ -164826,11 +167603,11 @@
167603 ** then edit any error message string so as to remove all occurrences of
167604 ** the pattern "rbu_imp_[0-9]*".
167605 */
167606 static void rbuEditErrmsg(sqlite3rbu *p){
167607 if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
167608 unsigned int i;
167609 size_t nErrmsg = strlen(p->zErrmsg);
167610 for(i=0; i<(nErrmsg-8); i++){
167611 if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
167612 int nDel = 8;
167613 while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
@@ -164859,14 +167636,24 @@
167636 p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
167637 }
167638
167639 /* Close any open statement handles. */
167640 rbuObjIterFinalize(&p->objiter);
167641
167642 /* If this is an RBU vacuum handle and the vacuum has either finished
167643 ** successfully or encountered an error, delete the contents of the
167644 ** state table. This causes the next call to sqlite3rbu_vacuum()
167645 ** specifying the current target and state databases to start a new
167646 ** vacuum from scratch. */
167647 if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
167648 int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
167649 if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
167650 }
167651
167652 /* Close the open database handle and VFS object. */
 
167653 sqlite3_close(p->dbRbu);
167654 sqlite3_close(p->dbMain);
167655 rbuDeleteVfs(p);
167656 sqlite3_free(p->aBuf);
167657 sqlite3_free(p->aFrame);
167658
167659 rbuEditErrmsg(p);
@@ -165063,10 +167850,26 @@
167850 return ((u32)aBuf[0] << 24)
167851 + ((u32)aBuf[1] << 16)
167852 + ((u32)aBuf[2] << 8)
167853 + ((u32)aBuf[3]);
167854 }
167855
167856 /*
167857 ** Write an unsigned 32-bit value in big-endian format to the supplied
167858 ** buffer.
167859 */
167860 static void rbuPutU32(u8 *aBuf, u32 iVal){
167861 aBuf[0] = (iVal >> 24) & 0xFF;
167862 aBuf[1] = (iVal >> 16) & 0xFF;
167863 aBuf[2] = (iVal >> 8) & 0xFF;
167864 aBuf[3] = (iVal >> 0) & 0xFF;
167865 }
167866
167867 static void rbuPutU16(u8 *aBuf, u16 iVal){
167868 aBuf[0] = (iVal >> 8) & 0xFF;
167869 aBuf[1] = (iVal >> 0) & 0xFF;
167870 }
167871
167872 /*
167873 ** Read data from an rbuVfs-file.
167874 */
167875 static int rbuVfsRead(
@@ -165089,10 +167892,39 @@
167892 ){
167893 rc = SQLITE_OK;
167894 memset(zBuf, 0, iAmt);
167895 }else{
167896 rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
167897 #if 1
167898 /* If this is being called to read the first page of the target
167899 ** database as part of an rbu vacuum operation, synthesize the
167900 ** contents of the first page if it does not yet exist. Otherwise,
167901 ** SQLite will not check for a *-wal file. */
167902 if( pRbu && rbuIsVacuum(pRbu)
167903 && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
167904 && (p->openFlags & SQLITE_OPEN_MAIN_DB)
167905 && pRbu->rc==SQLITE_OK
167906 ){
167907 sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
167908 rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
167909 if( rc==SQLITE_OK ){
167910 u8 *aBuf = (u8*)zBuf;
167911 u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
167912 rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
167913 rbuPutU32(&aBuf[36], 0); /* number of free pages */
167914 rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
167915 rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
167916 rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
167917
167918 if( iAmt>100 ){
167919 memset(&aBuf[100], 0, iAmt-100);
167920 rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
167921 aBuf[100] = 0x0D;
167922 }
167923 }
167924 }
167925 #endif
167926 }
167927 if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
167928 /* These look like magic numbers. But they are stable, as they are part
167929 ** of the definition of the SQLite file format, which may not change. */
167930 u8 *pBuf = (u8*)zBuf;
@@ -165163,11 +167995,24 @@
167995 /*
167996 ** Return the current file-size of an rbuVfs-file.
167997 */
167998 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
167999 rbu_file *p = (rbu_file *)pFile;
168000 int rc;
168001 rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
168002
168003 /* If this is an RBU vacuum operation and this is the target database,
168004 ** pretend that it has at least one page. Otherwise, SQLite will not
168005 ** check for the existance of a *-wal file. rbuVfsRead() contains
168006 ** similar logic. */
168007 if( rc==SQLITE_OK && *pSize==0
168008 && p->pRbu && rbuIsVacuum(p->pRbu)
168009 && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168010 ){
168011 *pSize = 1024;
168012 }
168013 return rc;
168014 }
168015
168016 /*
168017 ** Lock an rbuVfs-file.
168018 */
@@ -165175,11 +168020,13 @@
168020 rbu_file *p = (rbu_file*)pFile;
168021 sqlite3rbu *pRbu = p->pRbu;
168022 int rc = SQLITE_OK;
168023
168024 assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
168025 if( eLock==SQLITE_LOCK_EXCLUSIVE
168026 && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
168027 ){
168028 /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
168029 ** prevents it from checkpointing the database from sqlite3_close(). */
168030 rc = SQLITE_BUSY;
168031 }else{
168032 rc = p->pReal->pMethods->xLock(p->pReal, eLock);
@@ -165237,10 +168084,16 @@
168084 if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
168085 rc = SQLITE_OK;
168086 }
168087 }
168088 return rc;
168089 }
168090 else if( op==SQLITE_FCNTL_RBUCNT ){
168091 sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
168092 pRbu->nRbu++;
168093 pRbu->pRbuFd = p;
168094 p->bNolock = 1;
168095 }
168096
168097 rc = xControl(p->pReal, op, pArg);
168098 if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
168099 rbu_vfs *pRbuVfs = p->pRbuVfs;
@@ -165400,10 +168253,37 @@
168253 sqlite3_mutex_enter(pRbuVfs->mutex);
168254 for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
168255 sqlite3_mutex_leave(pRbuVfs->mutex);
168256 return pDb;
168257 }
168258
168259 /*
168260 ** A main database named zName has just been opened. The following
168261 ** function returns a pointer to a buffer owned by SQLite that contains
168262 ** the name of the *-wal file this db connection will use. SQLite
168263 ** happens to pass a pointer to this buffer when using xAccess()
168264 ** or xOpen() to operate on the *-wal file.
168265 */
168266 static const char *rbuMainToWal(const char *zName, int flags){
168267 int n = (int)strlen(zName);
168268 const char *z = &zName[n];
168269 if( flags & SQLITE_OPEN_URI ){
168270 int odd = 0;
168271 while( 1 ){
168272 if( z[0]==0 ){
168273 odd = 1 - odd;
168274 if( odd && z[1]==0 ) break;
168275 }
168276 z++;
168277 }
168278 z += 2;
168279 }else{
168280 while( *z==0 ) z++;
168281 }
168282 z += (n + 8 + 1);
168283 return z;
168284 }
168285
168286 /*
168287 ** Open an rbu file handle.
168288 */
168289 static int rbuVfsOpen(
@@ -165436,10 +168316,11 @@
168316 rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
168317 sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
168318 rbu_file *pFd = (rbu_file *)pFile;
168319 int rc = SQLITE_OK;
168320 const char *zOpen = zName;
168321 int oflags = flags;
168322
168323 memset(pFd, 0, sizeof(rbu_file));
168324 pFd->pReal = (sqlite3_file*)&pFd[1];
168325 pFd->pRbuVfs = pRbuVfs;
168326 pFd->openFlags = flags;
@@ -165448,40 +168329,31 @@
168329 /* A main database has just been opened. The following block sets
168330 ** (pFd->zWal) to point to a buffer owned by SQLite that contains
168331 ** the name of the *-wal file this db connection will use. SQLite
168332 ** happens to pass a pointer to this buffer when using xAccess()
168333 ** or xOpen() to operate on the *-wal file. */
168334 pFd->zWal = rbuMainToWal(zName, flags);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168335 }
168336 else if( flags & SQLITE_OPEN_WAL ){
168337 rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
168338 if( pDb ){
168339 if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
168340 /* This call is to open a *-wal file. Intead, open the *-oal. This
168341 ** code ensures that the string passed to xOpen() is terminated by a
168342 ** pair of '\0' bytes in case the VFS attempts to extract a URI
168343 ** parameter from it. */
168344 const char *zBase = zName;
168345 size_t nCopy;
168346 char *zCopy;
168347 if( rbuIsVacuum(pDb->pRbu) ){
168348 zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
168349 zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
168350 }
168351 nCopy = strlen(zBase);
168352 zCopy = sqlite3_malloc64(nCopy+2);
168353 if( zCopy ){
168354 memcpy(zCopy, zBase, nCopy);
168355 zCopy[nCopy-3] = 'o';
168356 zCopy[nCopy] = '\0';
168357 zCopy[nCopy+1] = '\0';
168358 zOpen = (const char*)(pFd->zDel = zCopy);
168359 }else{
@@ -165491,13 +168363,22 @@
168363 }
168364 pDb->pWalFd = pFd;
168365 }
168366 }
168367 }
168368
168369 if( oflags & SQLITE_OPEN_MAIN_DB
168370 && sqlite3_uri_boolean(zName, "rbu_memory", 0)
168371 ){
168372 assert( oflags & SQLITE_OPEN_MAIN_DB );
168373 oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
168374 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
168375 zOpen = 0;
168376 }
168377
168378 if( rc==SQLITE_OK ){
168379 rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
168380 }
168381 if( pFd->pReal->pMethods ){
168382 /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
168383 ** pointer and, if the file is a main database file, link it into the
168384 ** mutex protected linked list of all such files. */
@@ -166457,10 +169338,4654 @@
169338 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
169339 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
169340 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
169341
169342 /************** End of dbstat.c **********************************************/
169343 /************** Begin file sqlite3session.c **********************************/
169344
169345 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
169346 /* #include "sqlite3session.h" */
169347 /* #include <assert.h> */
169348 /* #include <string.h> */
169349
169350 #ifndef SQLITE_AMALGAMATION
169351 /* # include "sqliteInt.h" */
169352 /* # include "vdbeInt.h" */
169353 #endif
169354
169355 typedef struct SessionTable SessionTable;
169356 typedef struct SessionChange SessionChange;
169357 typedef struct SessionBuffer SessionBuffer;
169358 typedef struct SessionInput SessionInput;
169359
169360 /*
169361 ** Minimum chunk size used by streaming versions of functions.
169362 */
169363 #ifndef SESSIONS_STRM_CHUNK_SIZE
169364 # ifdef SQLITE_TEST
169365 # define SESSIONS_STRM_CHUNK_SIZE 64
169366 # else
169367 # define SESSIONS_STRM_CHUNK_SIZE 1024
169368 # endif
169369 #endif
169370
169371 typedef struct SessionHook SessionHook;
169372 struct SessionHook {
169373 void *pCtx;
169374 int (*xOld)(void*,int,sqlite3_value**);
169375 int (*xNew)(void*,int,sqlite3_value**);
169376 int (*xCount)(void*);
169377 int (*xDepth)(void*);
169378 };
169379
169380 /*
169381 ** Session handle structure.
169382 */
169383 struct sqlite3_session {
169384 sqlite3 *db; /* Database handle session is attached to */
169385 char *zDb; /* Name of database session is attached to */
169386 int bEnable; /* True if currently recording */
169387 int bIndirect; /* True if all changes are indirect */
169388 int bAutoAttach; /* True to auto-attach tables */
169389 int rc; /* Non-zero if an error has occurred */
169390 void *pFilterCtx; /* First argument to pass to xTableFilter */
169391 int (*xTableFilter)(void *pCtx, const char *zTab);
169392 sqlite3_session *pNext; /* Next session object on same db. */
169393 SessionTable *pTable; /* List of attached tables */
169394 SessionHook hook; /* APIs to grab new and old data with */
169395 };
169396
169397 /*
169398 ** Instances of this structure are used to build strings or binary records.
169399 */
169400 struct SessionBuffer {
169401 u8 *aBuf; /* Pointer to changeset buffer */
169402 int nBuf; /* Size of buffer aBuf */
169403 int nAlloc; /* Size of allocation containing aBuf */
169404 };
169405
169406 /*
169407 ** An object of this type is used internally as an abstraction for
169408 ** input data. Input data may be supplied either as a single large buffer
169409 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
169410 ** sqlite3changeset_start_strm()).
169411 */
169412 struct SessionInput {
169413 int bNoDiscard; /* If true, discard no data */
169414 int iCurrent; /* Offset in aData[] of current change */
169415 int iNext; /* Offset in aData[] of next change */
169416 u8 *aData; /* Pointer to buffer containing changeset */
169417 int nData; /* Number of bytes in aData */
169418
169419 SessionBuffer buf; /* Current read buffer */
169420 int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
169421 void *pIn; /* First argument to xInput */
169422 int bEof; /* Set to true after xInput finished */
169423 };
169424
169425 /*
169426 ** Structure for changeset iterators.
169427 */
169428 struct sqlite3_changeset_iter {
169429 SessionInput in; /* Input buffer or stream */
169430 SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
169431 int bPatchset; /* True if this is a patchset */
169432 int rc; /* Iterator error code */
169433 sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
169434 char *zTab; /* Current table */
169435 int nCol; /* Number of columns in zTab */
169436 int op; /* Current operation */
169437 int bIndirect; /* True if current change was indirect */
169438 u8 *abPK; /* Primary key array */
169439 sqlite3_value **apValue; /* old.* and new.* values */
169440 };
169441
169442 /*
169443 ** Each session object maintains a set of the following structures, one
169444 ** for each table the session object is monitoring. The structures are
169445 ** stored in a linked list starting at sqlite3_session.pTable.
169446 **
169447 ** The keys of the SessionTable.aChange[] hash table are all rows that have
169448 ** been modified in any way since the session object was attached to the
169449 ** table.
169450 **
169451 ** The data associated with each hash-table entry is a structure containing
169452 ** a subset of the initial values that the modified row contained at the
169453 ** start of the session. Or no initial values if the row was inserted.
169454 */
169455 struct SessionTable {
169456 SessionTable *pNext;
169457 char *zName; /* Local name of table */
169458 int nCol; /* Number of columns in table zName */
169459 const char **azCol; /* Column names */
169460 u8 *abPK; /* Array of primary key flags */
169461 int nEntry; /* Total number of entries in hash table */
169462 int nChange; /* Size of apChange[] array */
169463 SessionChange **apChange; /* Hash table buckets */
169464 };
169465
169466 /*
169467 ** RECORD FORMAT:
169468 **
169469 ** The following record format is similar to (but not compatible with) that
169470 ** used in SQLite database files. This format is used as part of the
169471 ** change-set binary format, and so must be architecture independent.
169472 **
169473 ** Unlike the SQLite database record format, each field is self-contained -
169474 ** there is no separation of header and data. Each field begins with a
169475 ** single byte describing its type, as follows:
169476 **
169477 ** 0x00: Undefined value.
169478 ** 0x01: Integer value.
169479 ** 0x02: Real value.
169480 ** 0x03: Text value.
169481 ** 0x04: Blob value.
169482 ** 0x05: SQL NULL value.
169483 **
169484 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
169485 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
169486 ** only of the single type byte. For other types of values, the type byte
169487 ** is followed by:
169488 **
169489 ** Text values:
169490 ** A varint containing the number of bytes in the value (encoded using
169491 ** UTF-8). Followed by a buffer containing the UTF-8 representation
169492 ** of the text value. There is no nul terminator.
169493 **
169494 ** Blob values:
169495 ** A varint containing the number of bytes in the value, followed by
169496 ** a buffer containing the value itself.
169497 **
169498 ** Integer values:
169499 ** An 8-byte big-endian integer value.
169500 **
169501 ** Real values:
169502 ** An 8-byte big-endian IEEE 754-2008 real value.
169503 **
169504 ** Varint values are encoded in the same way as varints in the SQLite
169505 ** record format.
169506 **
169507 ** CHANGESET FORMAT:
169508 **
169509 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
169510 ** one or more tables. Operations on a single table are grouped together,
169511 ** but may occur in any order (i.e. deletes, updates and inserts are all
169512 ** mixed together).
169513 **
169514 ** Each group of changes begins with a table header:
169515 **
169516 ** 1 byte: Constant 0x54 (capital 'T')
169517 ** Varint: Number of columns in the table.
169518 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169519 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169520 **
169521 ** Followed by one or more changes to the table.
169522 **
169523 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169524 ** 1 byte: The "indirect-change" flag.
169525 ** old.* record: (delete and update only)
169526 ** new.* record: (insert and update only)
169527 **
169528 ** The "old.*" and "new.*" records, if present, are N field records in the
169529 ** format described above under "RECORD FORMAT", where N is the number of
169530 ** columns in the table. The i'th field of each record is associated with
169531 ** the i'th column of the table, counting from left to right in the order
169532 ** in which columns were declared in the CREATE TABLE statement.
169533 **
169534 ** The new.* record that is part of each INSERT change contains the values
169535 ** that make up the new row. Similarly, the old.* record that is part of each
169536 ** DELETE change contains the values that made up the row that was deleted
169537 ** from the database. In the changeset format, the records that are part
169538 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
169539 ** fields.
169540 **
169541 ** Within the old.* record associated with an UPDATE change, all fields
169542 ** associated with table columns that are not PRIMARY KEY columns and are
169543 ** not modified by the UPDATE change are set to "undefined". Other fields
169544 ** are set to the values that made up the row before the UPDATE that the
169545 ** change records took place. Within the new.* record, fields associated
169546 ** with table columns modified by the UPDATE change contain the new
169547 ** values. Fields associated with table columns that are not modified
169548 ** are set to "undefined".
169549 **
169550 ** PATCHSET FORMAT:
169551 **
169552 ** A patchset is also a collection of changes. It is similar to a changeset,
169553 ** but leaves undefined those fields that are not useful if no conflict
169554 ** resolution is required when applying the changeset.
169555 **
169556 ** Each group of changes begins with a table header:
169557 **
169558 ** 1 byte: Constant 0x50 (capital 'P')
169559 ** Varint: Number of columns in the table.
169560 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169561 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169562 **
169563 ** Followed by one or more changes to the table.
169564 **
169565 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169566 ** 1 byte: The "indirect-change" flag.
169567 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
169568 ** full record for INSERT).
169569 **
169570 ** As in the changeset format, each field of the single record that is part
169571 ** of a patchset change is associated with the correspondingly positioned
169572 ** table column, counting from left to right within the CREATE TABLE
169573 ** statement.
169574 **
169575 ** For a DELETE change, all fields within the record except those associated
169576 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
169577 ** contain the values identifying the row to delete.
169578 **
169579 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
169580 ** columns and columns that are modified by the UPDATE are set to "undefined".
169581 ** PRIMARY KEY fields contain the values identifying the table row to update,
169582 ** and fields associated with modified columns contain the new column values.
169583 **
169584 ** The records associated with INSERT changes are in the same format as for
169585 ** changesets. It is not possible for a record associated with an INSERT
169586 ** change to contain a field set to "undefined".
169587 */
169588
169589 /*
169590 ** For each row modified during a session, there exists a single instance of
169591 ** this structure stored in a SessionTable.aChange[] hash table.
169592 */
169593 struct SessionChange {
169594 int op; /* One of UPDATE, DELETE, INSERT */
169595 int bIndirect; /* True if this change is "indirect" */
169596 int nRecord; /* Number of bytes in buffer aRecord[] */
169597 u8 *aRecord; /* Buffer containing old.* record */
169598 SessionChange *pNext; /* For hash-table collisions */
169599 };
169600
169601 /*
169602 ** Write a varint with value iVal into the buffer at aBuf. Return the
169603 ** number of bytes written.
169604 */
169605 static int sessionVarintPut(u8 *aBuf, int iVal){
169606 return putVarint32(aBuf, iVal);
169607 }
169608
169609 /*
169610 ** Return the number of bytes required to store value iVal as a varint.
169611 */
169612 static int sessionVarintLen(int iVal){
169613 return sqlite3VarintLen(iVal);
169614 }
169615
169616 /*
169617 ** Read a varint value from aBuf[] into *piVal. Return the number of
169618 ** bytes read.
169619 */
169620 static int sessionVarintGet(u8 *aBuf, int *piVal){
169621 return getVarint32(aBuf, *piVal);
169622 }
169623
169624 /* Load an unaligned and unsigned 32-bit integer */
169625 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
169626
169627 /*
169628 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
169629 ** the value read.
169630 */
169631 static sqlite3_int64 sessionGetI64(u8 *aRec){
169632 u64 x = SESSION_UINT32(aRec);
169633 u32 y = SESSION_UINT32(aRec+4);
169634 x = (x<<32) + y;
169635 return (sqlite3_int64)x;
169636 }
169637
169638 /*
169639 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
169640 */
169641 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
169642 aBuf[0] = (i>>56) & 0xFF;
169643 aBuf[1] = (i>>48) & 0xFF;
169644 aBuf[2] = (i>>40) & 0xFF;
169645 aBuf[3] = (i>>32) & 0xFF;
169646 aBuf[4] = (i>>24) & 0xFF;
169647 aBuf[5] = (i>>16) & 0xFF;
169648 aBuf[6] = (i>> 8) & 0xFF;
169649 aBuf[7] = (i>> 0) & 0xFF;
169650 }
169651
169652 /*
169653 ** This function is used to serialize the contents of value pValue (see
169654 ** comment titled "RECORD FORMAT" above).
169655 **
169656 ** If it is non-NULL, the serialized form of the value is written to
169657 ** buffer aBuf. *pnWrite is set to the number of bytes written before
169658 ** returning. Or, if aBuf is NULL, the only thing this function does is
169659 ** set *pnWrite.
169660 **
169661 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
169662 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
169663 ** SQLITE_NOMEM is returned.
169664 */
169665 static int sessionSerializeValue(
169666 u8 *aBuf, /* If non-NULL, write serialized value here */
169667 sqlite3_value *pValue, /* Value to serialize */
169668 int *pnWrite /* IN/OUT: Increment by bytes written */
169669 ){
169670 int nByte; /* Size of serialized value in bytes */
169671
169672 if( pValue ){
169673 int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
169674
169675 eType = sqlite3_value_type(pValue);
169676 if( aBuf ) aBuf[0] = eType;
169677
169678 switch( eType ){
169679 case SQLITE_NULL:
169680 nByte = 1;
169681 break;
169682
169683 case SQLITE_INTEGER:
169684 case SQLITE_FLOAT:
169685 if( aBuf ){
169686 /* TODO: SQLite does something special to deal with mixed-endian
169687 ** floating point values (e.g. ARM7). This code probably should
169688 ** too. */
169689 u64 i;
169690 if( eType==SQLITE_INTEGER ){
169691 i = (u64)sqlite3_value_int64(pValue);
169692 }else{
169693 double r;
169694 assert( sizeof(double)==8 && sizeof(u64)==8 );
169695 r = sqlite3_value_double(pValue);
169696 memcpy(&i, &r, 8);
169697 }
169698 sessionPutI64(&aBuf[1], i);
169699 }
169700 nByte = 9;
169701 break;
169702
169703 default: {
169704 u8 *z;
169705 int n;
169706 int nVarint;
169707
169708 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
169709 if( eType==SQLITE_TEXT ){
169710 z = (u8 *)sqlite3_value_text(pValue);
169711 }else{
169712 z = (u8 *)sqlite3_value_blob(pValue);
169713 }
169714 n = sqlite3_value_bytes(pValue);
169715 if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169716 nVarint = sessionVarintLen(n);
169717
169718 if( aBuf ){
169719 sessionVarintPut(&aBuf[1], n);
169720 memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
169721 sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
169722 );
169723 }
169724
169725 nByte = 1 + nVarint + n;
169726 break;
169727 }
169728 }
169729 }else{
169730 nByte = 1;
169731 if( aBuf ) aBuf[0] = '\0';
169732 }
169733
169734 if( pnWrite ) *pnWrite += nByte;
169735 return SQLITE_OK;
169736 }
169737
169738
169739 /*
169740 ** This macro is used to calculate hash key values for data structures. In
169741 ** order to use this macro, the entire data structure must be represented
169742 ** as a series of unsigned integers. In order to calculate a hash-key value
169743 ** for a data structure represented as three such integers, the macro may
169744 ** then be used as follows:
169745 **
169746 ** int hash_key_value;
169747 ** hash_key_value = HASH_APPEND(0, <value 1>);
169748 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
169749 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
169750 **
169751 ** In practice, the data structures this macro is used for are the primary
169752 ** key values of modified rows.
169753 */
169754 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
169755
169756 /*
169757 ** Append the hash of the 64-bit integer passed as the second argument to the
169758 ** hash-key value passed as the first. Return the new hash-key value.
169759 */
169760 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
169761 h = HASH_APPEND(h, i & 0xFFFFFFFF);
169762 return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
169763 }
169764
169765 /*
169766 ** Append the hash of the blob passed via the second and third arguments to
169767 ** the hash-key value passed as the first. Return the new hash-key value.
169768 */
169769 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
169770 int i;
169771 for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
169772 return h;
169773 }
169774
169775 /*
169776 ** Append the hash of the data type passed as the second argument to the
169777 ** hash-key value passed as the first. Return the new hash-key value.
169778 */
169779 static unsigned int sessionHashAppendType(unsigned int h, int eType){
169780 return HASH_APPEND(h, eType);
169781 }
169782
169783 /*
169784 ** This function may only be called from within a pre-update callback.
169785 ** It calculates a hash based on the primary key values of the old.* or
169786 ** new.* row currently available and, assuming no error occurs, writes it to
169787 ** *piHash before returning. If the primary key contains one or more NULL
169788 ** values, *pbNullPK is set to true before returning.
169789 **
169790 ** If an error occurs, an SQLite error code is returned and the final values
169791 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
169792 ** and the output variables are set as described above.
169793 */
169794 static int sessionPreupdateHash(
169795 sqlite3_session *pSession, /* Session object that owns pTab */
169796 SessionTable *pTab, /* Session table handle */
169797 int bNew, /* True to hash the new.* PK */
169798 int *piHash, /* OUT: Hash value */
169799 int *pbNullPK /* OUT: True if there are NULL values in PK */
169800 ){
169801 unsigned int h = 0; /* Hash value to return */
169802 int i; /* Used to iterate through columns */
169803
169804 assert( *pbNullPK==0 );
169805 assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
169806 for(i=0; i<pTab->nCol; i++){
169807 if( pTab->abPK[i] ){
169808 int rc;
169809 int eType;
169810 sqlite3_value *pVal;
169811
169812 if( bNew ){
169813 rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
169814 }else{
169815 rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
169816 }
169817 if( rc!=SQLITE_OK ) return rc;
169818
169819 eType = sqlite3_value_type(pVal);
169820 h = sessionHashAppendType(h, eType);
169821 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169822 i64 iVal;
169823 if( eType==SQLITE_INTEGER ){
169824 iVal = sqlite3_value_int64(pVal);
169825 }else{
169826 double rVal = sqlite3_value_double(pVal);
169827 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
169828 memcpy(&iVal, &rVal, 8);
169829 }
169830 h = sessionHashAppendI64(h, iVal);
169831 }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
169832 const u8 *z;
169833 int n;
169834 if( eType==SQLITE_TEXT ){
169835 z = (const u8 *)sqlite3_value_text(pVal);
169836 }else{
169837 z = (const u8 *)sqlite3_value_blob(pVal);
169838 }
169839 n = sqlite3_value_bytes(pVal);
169840 if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169841 h = sessionHashAppendBlob(h, n, z);
169842 }else{
169843 assert( eType==SQLITE_NULL );
169844 *pbNullPK = 1;
169845 }
169846 }
169847 }
169848
169849 *piHash = (h % pTab->nChange);
169850 return SQLITE_OK;
169851 }
169852
169853 /*
169854 ** The buffer that the argument points to contains a serialized SQL value.
169855 ** Return the number of bytes of space occupied by the value (including
169856 ** the type byte).
169857 */
169858 static int sessionSerialLen(u8 *a){
169859 int e = *a;
169860 int n;
169861 if( e==0 ) return 1;
169862 if( e==SQLITE_NULL ) return 1;
169863 if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
169864 return sessionVarintGet(&a[1], &n) + 1 + n;
169865 }
169866
169867 /*
169868 ** Based on the primary key values stored in change aRecord, calculate a
169869 ** hash key. Assume the has table has nBucket buckets. The hash keys
169870 ** calculated by this function are compatible with those calculated by
169871 ** sessionPreupdateHash().
169872 **
169873 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
169874 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
169875 */
169876 static unsigned int sessionChangeHash(
169877 SessionTable *pTab, /* Table handle */
169878 int bPkOnly, /* Record consists of PK fields only */
169879 u8 *aRecord, /* Change record */
169880 int nBucket /* Assume this many buckets in hash table */
169881 ){
169882 unsigned int h = 0; /* Value to return */
169883 int i; /* Used to iterate through columns */
169884 u8 *a = aRecord; /* Used to iterate through change record */
169885
169886 for(i=0; i<pTab->nCol; i++){
169887 int eType = *a;
169888 int isPK = pTab->abPK[i];
169889 if( bPkOnly && isPK==0 ) continue;
169890
169891 /* It is not possible for eType to be SQLITE_NULL here. The session
169892 ** module does not record changes for rows with NULL values stored in
169893 ** primary key columns. */
169894 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
169895 || eType==SQLITE_TEXT || eType==SQLITE_BLOB
169896 || eType==SQLITE_NULL || eType==0
169897 );
169898 assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
169899
169900 if( isPK ){
169901 a++;
169902 h = sessionHashAppendType(h, eType);
169903 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169904 h = sessionHashAppendI64(h, sessionGetI64(a));
169905 a += 8;
169906 }else{
169907 int n;
169908 a += sessionVarintGet(a, &n);
169909 h = sessionHashAppendBlob(h, n, a);
169910 a += n;
169911 }
169912 }else{
169913 a += sessionSerialLen(a);
169914 }
169915 }
169916 return (h % nBucket);
169917 }
169918
169919 /*
169920 ** Arguments aLeft and aRight are pointers to change records for table pTab.
169921 ** This function returns true if the two records apply to the same row (i.e.
169922 ** have the same values stored in the primary key columns), or false
169923 ** otherwise.
169924 */
169925 static int sessionChangeEqual(
169926 SessionTable *pTab, /* Table used for PK definition */
169927 int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
169928 u8 *aLeft, /* Change record */
169929 int bRightPkOnly, /* True if aRight[] contains PK fields only */
169930 u8 *aRight /* Change record */
169931 ){
169932 u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
169933 u8 *a2 = aRight; /* Cursor to iterate through aRight */
169934 int iCol; /* Used to iterate through table columns */
169935
169936 for(iCol=0; iCol<pTab->nCol; iCol++){
169937 if( pTab->abPK[iCol] ){
169938 int n1 = sessionSerialLen(a1);
169939 int n2 = sessionSerialLen(a2);
169940
169941 if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
169942 return 0;
169943 }
169944 a1 += n1;
169945 a2 += n2;
169946 }else{
169947 if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
169948 if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
169949 }
169950 }
169951
169952 return 1;
169953 }
169954
169955 /*
169956 ** Arguments aLeft and aRight both point to buffers containing change
169957 ** records with nCol columns. This function "merges" the two records into
169958 ** a single records which is written to the buffer at *paOut. *paOut is
169959 ** then set to point to one byte after the last byte written before
169960 ** returning.
169961 **
169962 ** The merging of records is done as follows: For each column, if the
169963 ** aRight record contains a value for the column, copy the value from
169964 ** their. Otherwise, if aLeft contains a value, copy it. If neither
169965 ** record contains a value for a given column, then neither does the
169966 ** output record.
169967 */
169968 static void sessionMergeRecord(
169969 u8 **paOut,
169970 int nCol,
169971 u8 *aLeft,
169972 u8 *aRight
169973 ){
169974 u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
169975 u8 *a2 = aRight; /* Cursor used to iterate through aRight */
169976 u8 *aOut = *paOut; /* Output cursor */
169977 int iCol; /* Used to iterate from 0 to nCol */
169978
169979 for(iCol=0; iCol<nCol; iCol++){
169980 int n1 = sessionSerialLen(a1);
169981 int n2 = sessionSerialLen(a2);
169982 if( *a2 ){
169983 memcpy(aOut, a2, n2);
169984 aOut += n2;
169985 }else{
169986 memcpy(aOut, a1, n1);
169987 aOut += n1;
169988 }
169989 a1 += n1;
169990 a2 += n2;
169991 }
169992
169993 *paOut = aOut;
169994 }
169995
169996 /*
169997 ** This is a helper function used by sessionMergeUpdate().
169998 **
169999 ** When this function is called, both *paOne and *paTwo point to a value
170000 ** within a change record. Before it returns, both have been advanced so
170001 ** as to point to the next value in the record.
170002 **
170003 ** If, when this function is called, *paTwo points to a valid value (i.e.
170004 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
170005 ** pointer is returned and *pnVal is set to the number of bytes in the
170006 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
170007 ** set to the number of bytes in the value at *paOne. If *paOne points
170008 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
170009 **
170010 ** if( *paTwo is valid ) return *paTwo;
170011 ** return *paOne;
170012 **
170013 */
170014 static u8 *sessionMergeValue(
170015 u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
170016 u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
170017 int *pnVal /* OUT: Bytes in returned value */
170018 ){
170019 u8 *a1 = *paOne;
170020 u8 *a2 = *paTwo;
170021 u8 *pRet = 0;
170022 int n1;
170023
170024 assert( a1 );
170025 if( a2 ){
170026 int n2 = sessionSerialLen(a2);
170027 if( *a2 ){
170028 *pnVal = n2;
170029 pRet = a2;
170030 }
170031 *paTwo = &a2[n2];
170032 }
170033
170034 n1 = sessionSerialLen(a1);
170035 if( pRet==0 ){
170036 *pnVal = n1;
170037 pRet = a1;
170038 }
170039 *paOne = &a1[n1];
170040
170041 return pRet;
170042 }
170043
170044 /*
170045 ** This function is used by changeset_concat() to merge two UPDATE changes
170046 ** on the same row.
170047 */
170048 static int sessionMergeUpdate(
170049 u8 **paOut, /* IN/OUT: Pointer to output buffer */
170050 SessionTable *pTab, /* Table change pertains to */
170051 int bPatchset, /* True if records are patchset records */
170052 u8 *aOldRecord1, /* old.* record for first change */
170053 u8 *aOldRecord2, /* old.* record for second change */
170054 u8 *aNewRecord1, /* new.* record for first change */
170055 u8 *aNewRecord2 /* new.* record for second change */
170056 ){
170057 u8 *aOld1 = aOldRecord1;
170058 u8 *aOld2 = aOldRecord2;
170059 u8 *aNew1 = aNewRecord1;
170060 u8 *aNew2 = aNewRecord2;
170061
170062 u8 *aOut = *paOut;
170063 int i;
170064
170065 if( bPatchset==0 ){
170066 int bRequired = 0;
170067
170068 assert( aOldRecord1 && aNewRecord1 );
170069
170070 /* Write the old.* vector first. */
170071 for(i=0; i<pTab->nCol; i++){
170072 int nOld;
170073 u8 *aOld;
170074 int nNew;
170075 u8 *aNew;
170076
170077 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170078 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170079 if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
170080 if( pTab->abPK[i]==0 ) bRequired = 1;
170081 memcpy(aOut, aOld, nOld);
170082 aOut += nOld;
170083 }else{
170084 *(aOut++) = '\0';
170085 }
170086 }
170087
170088 if( !bRequired ) return 0;
170089 }
170090
170091 /* Write the new.* vector */
170092 aOld1 = aOldRecord1;
170093 aOld2 = aOldRecord2;
170094 aNew1 = aNewRecord1;
170095 aNew2 = aNewRecord2;
170096 for(i=0; i<pTab->nCol; i++){
170097 int nOld;
170098 u8 *aOld;
170099 int nNew;
170100 u8 *aNew;
170101
170102 aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170103 aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170104 if( bPatchset==0
170105 && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
170106 ){
170107 *(aOut++) = '\0';
170108 }else{
170109 memcpy(aOut, aNew, nNew);
170110 aOut += nNew;
170111 }
170112 }
170113
170114 *paOut = aOut;
170115 return 1;
170116 }
170117
170118 /*
170119 ** This function is only called from within a pre-update-hook callback.
170120 ** It determines if the current pre-update-hook change affects the same row
170121 ** as the change stored in argument pChange. If so, it returns true. Otherwise
170122 ** if the pre-update-hook does not affect the same row as pChange, it returns
170123 ** false.
170124 */
170125 static int sessionPreupdateEqual(
170126 sqlite3_session *pSession, /* Session object that owns SessionTable */
170127 SessionTable *pTab, /* Table associated with change */
170128 SessionChange *pChange, /* Change to compare to */
170129 int op /* Current pre-update operation */
170130 ){
170131 int iCol; /* Used to iterate through columns */
170132 u8 *a = pChange->aRecord; /* Cursor used to scan change record */
170133
170134 assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
170135 for(iCol=0; iCol<pTab->nCol; iCol++){
170136 if( !pTab->abPK[iCol] ){
170137 a += sessionSerialLen(a);
170138 }else{
170139 sqlite3_value *pVal; /* Value returned by preupdate_new/old */
170140 int rc; /* Error code from preupdate_new/old */
170141 int eType = *a++; /* Type of value from change record */
170142
170143 /* The following calls to preupdate_new() and preupdate_old() can not
170144 ** fail. This is because they cache their return values, and by the
170145 ** time control flows to here they have already been called once from
170146 ** within sessionPreupdateHash(). The first two asserts below verify
170147 ** this (that the method has already been called). */
170148 if( op==SQLITE_INSERT ){
170149 /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
170150 rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
170151 }else{
170152 /* assert( db->pPreUpdate->pUnpacked ); */
170153 rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
170154 }
170155 assert( rc==SQLITE_OK );
170156 if( sqlite3_value_type(pVal)!=eType ) return 0;
170157
170158 /* A SessionChange object never has a NULL value in a PK column */
170159 assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
170160 || eType==SQLITE_BLOB || eType==SQLITE_TEXT
170161 );
170162
170163 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170164 i64 iVal = sessionGetI64(a);
170165 a += 8;
170166 if( eType==SQLITE_INTEGER ){
170167 if( sqlite3_value_int64(pVal)!=iVal ) return 0;
170168 }else{
170169 double rVal;
170170 assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170171 memcpy(&rVal, &iVal, 8);
170172 if( sqlite3_value_double(pVal)!=rVal ) return 0;
170173 }
170174 }else{
170175 int n;
170176 const u8 *z;
170177 a += sessionVarintGet(a, &n);
170178 if( sqlite3_value_bytes(pVal)!=n ) return 0;
170179 if( eType==SQLITE_TEXT ){
170180 z = sqlite3_value_text(pVal);
170181 }else{
170182 z = sqlite3_value_blob(pVal);
170183 }
170184 if( memcmp(a, z, n) ) return 0;
170185 a += n;
170186 break;
170187 }
170188 }
170189 }
170190
170191 return 1;
170192 }
170193
170194 /*
170195 ** If required, grow the hash table used to store changes on table pTab
170196 ** (part of the session pSession). If a fatal OOM error occurs, set the
170197 ** session object to failed and return SQLITE_ERROR. Otherwise, return
170198 ** SQLITE_OK.
170199 **
170200 ** It is possible that a non-fatal OOM error occurs in this function. In
170201 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
170202 ** Growing the hash table in this case is a performance optimization only,
170203 ** it is not required for correct operation.
170204 */
170205 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
170206 if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
170207 int i;
170208 SessionChange **apNew;
170209 int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
170210
170211 apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
170212 if( apNew==0 ){
170213 if( pTab->nChange==0 ){
170214 return SQLITE_ERROR;
170215 }
170216 return SQLITE_OK;
170217 }
170218 memset(apNew, 0, sizeof(SessionChange *) * nNew);
170219
170220 for(i=0; i<pTab->nChange; i++){
170221 SessionChange *p;
170222 SessionChange *pNext;
170223 for(p=pTab->apChange[i]; p; p=pNext){
170224 int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
170225 int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
170226 pNext = p->pNext;
170227 p->pNext = apNew[iHash];
170228 apNew[iHash] = p;
170229 }
170230 }
170231
170232 sqlite3_free(pTab->apChange);
170233 pTab->nChange = nNew;
170234 pTab->apChange = apNew;
170235 }
170236
170237 return SQLITE_OK;
170238 }
170239
170240 /*
170241 ** This function queries the database for the names of the columns of table
170242 ** zThis, in schema zDb. It is expected that the table has nCol columns. If
170243 ** not, SQLITE_SCHEMA is returned and none of the output variables are
170244 ** populated.
170245 **
170246 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
170247 ** of columns in the database table and variable *pzTab is set to point to a
170248 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
170249 ** point to an array of pointers to column names. And *pabPK (again, if not
170250 ** NULL) is set to point to an array of booleans - true if the corresponding
170251 ** column is part of the primary key.
170252 **
170253 ** For example, if the table is declared as:
170254 **
170255 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
170256 **
170257 ** Then the four output variables are populated as follows:
170258 **
170259 ** *pnCol = 4
170260 ** *pzTab = "tbl1"
170261 ** *pazCol = {"w", "x", "y", "z"}
170262 ** *pabPK = {1, 0, 0, 1}
170263 **
170264 ** All returned buffers are part of the same single allocation, which must
170265 ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
170266 ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
170267 ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
170268 */
170269 static int sessionTableInfo(
170270 sqlite3 *db, /* Database connection */
170271 const char *zDb, /* Name of attached database (e.g. "main") */
170272 const char *zThis, /* Table name */
170273 int *pnCol, /* OUT: number of columns */
170274 const char **pzTab, /* OUT: Copy of zThis */
170275 const char ***pazCol, /* OUT: Array of column names for table */
170276 u8 **pabPK /* OUT: Array of booleans - true for PK col */
170277 ){
170278 char *zPragma;
170279 sqlite3_stmt *pStmt;
170280 int rc;
170281 int nByte;
170282 int nDbCol = 0;
170283 int nThis;
170284 int i;
170285 u8 *pAlloc = 0;
170286 char **azCol = 0;
170287 u8 *abPK = 0;
170288
170289 assert( pazCol && pabPK );
170290
170291 nThis = sqlite3Strlen30(zThis);
170292 zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
170293 if( !zPragma ) return SQLITE_NOMEM;
170294
170295 rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
170296 sqlite3_free(zPragma);
170297 if( rc!=SQLITE_OK ) return rc;
170298
170299 nByte = nThis + 1;
170300 while( SQLITE_ROW==sqlite3_step(pStmt) ){
170301 nByte += sqlite3_column_bytes(pStmt, 1);
170302 nDbCol++;
170303 }
170304 rc = sqlite3_reset(pStmt);
170305
170306 if( rc==SQLITE_OK ){
170307 nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
170308 pAlloc = sqlite3_malloc(nByte);
170309 if( pAlloc==0 ){
170310 rc = SQLITE_NOMEM;
170311 }
170312 }
170313 if( rc==SQLITE_OK ){
170314 azCol = (char **)pAlloc;
170315 pAlloc = (u8 *)&azCol[nDbCol];
170316 abPK = (u8 *)pAlloc;
170317 pAlloc = &abPK[nDbCol];
170318 if( pzTab ){
170319 memcpy(pAlloc, zThis, nThis+1);
170320 *pzTab = (char *)pAlloc;
170321 pAlloc += nThis+1;
170322 }
170323
170324 i = 0;
170325 while( SQLITE_ROW==sqlite3_step(pStmt) ){
170326 int nName = sqlite3_column_bytes(pStmt, 1);
170327 const unsigned char *zName = sqlite3_column_text(pStmt, 1);
170328 if( zName==0 ) break;
170329 memcpy(pAlloc, zName, nName+1);
170330 azCol[i] = (char *)pAlloc;
170331 pAlloc += nName+1;
170332 abPK[i] = sqlite3_column_int(pStmt, 5);
170333 i++;
170334 }
170335 rc = sqlite3_reset(pStmt);
170336
170337 }
170338
170339 /* If successful, populate the output variables. Otherwise, zero them and
170340 ** free any allocation made. An error code will be returned in this case.
170341 */
170342 if( rc==SQLITE_OK ){
170343 *pazCol = (const char **)azCol;
170344 *pabPK = abPK;
170345 *pnCol = nDbCol;
170346 }else{
170347 *pazCol = 0;
170348 *pabPK = 0;
170349 *pnCol = 0;
170350 if( pzTab ) *pzTab = 0;
170351 sqlite3_free(azCol);
170352 }
170353 sqlite3_finalize(pStmt);
170354 return rc;
170355 }
170356
170357 /*
170358 ** This function is only called from within a pre-update handler for a
170359 ** write to table pTab, part of session pSession. If this is the first
170360 ** write to this table, initalize the SessionTable.nCol, azCol[] and
170361 ** abPK[] arrays accordingly.
170362 **
170363 ** If an error occurs, an error code is stored in sqlite3_session.rc and
170364 ** non-zero returned. Or, if no error occurs but the table has no primary
170365 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
170366 ** indicate that updates on this table should be ignored. SessionTable.abPK
170367 ** is set to NULL in this case.
170368 */
170369 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
170370 if( pTab->nCol==0 ){
170371 u8 *abPK;
170372 assert( pTab->azCol==0 || pTab->abPK==0 );
170373 pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
170374 pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
170375 );
170376 if( pSession->rc==SQLITE_OK ){
170377 int i;
170378 for(i=0; i<pTab->nCol; i++){
170379 if( abPK[i] ){
170380 pTab->abPK = abPK;
170381 break;
170382 }
170383 }
170384 }
170385 }
170386 return (pSession->rc || pTab->abPK==0);
170387 }
170388
170389 /*
170390 ** This function is only called from with a pre-update-hook reporting a
170391 ** change on table pTab (attached to session pSession). The type of change
170392 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
170393 **
170394 ** Unless one is already present or an error occurs, an entry is added
170395 ** to the changed-rows hash table associated with table pTab.
170396 */
170397 static void sessionPreupdateOneChange(
170398 int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
170399 sqlite3_session *pSession, /* Session object pTab is attached to */
170400 SessionTable *pTab /* Table that change applies to */
170401 ){
170402 int iHash;
170403 int bNull = 0;
170404 int rc = SQLITE_OK;
170405
170406 if( pSession->rc ) return;
170407
170408 /* Load table details if required */
170409 if( sessionInitTable(pSession, pTab) ) return;
170410
170411 /* Check the number of columns in this xPreUpdate call matches the
170412 ** number of columns in the table. */
170413 if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
170414 pSession->rc = SQLITE_SCHEMA;
170415 return;
170416 }
170417
170418 /* Grow the hash table if required */
170419 if( sessionGrowHash(0, pTab) ){
170420 pSession->rc = SQLITE_NOMEM;
170421 return;
170422 }
170423
170424 /* Calculate the hash-key for this change. If the primary key of the row
170425 ** includes a NULL value, exit early. Such changes are ignored by the
170426 ** session module. */
170427 rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
170428 if( rc!=SQLITE_OK ) goto error_out;
170429
170430 if( bNull==0 ){
170431 /* Search the hash table for an existing record for this row. */
170432 SessionChange *pC;
170433 for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
170434 if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
170435 }
170436
170437 if( pC==0 ){
170438 /* Create a new change object containing all the old values (if
170439 ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
170440 ** values (if this is an INSERT). */
170441 SessionChange *pChange; /* New change object */
170442 int nByte; /* Number of bytes to allocate */
170443 int i; /* Used to iterate through columns */
170444
170445 assert( rc==SQLITE_OK );
170446 pTab->nEntry++;
170447
170448 /* Figure out how large an allocation is required */
170449 nByte = sizeof(SessionChange);
170450 for(i=0; i<pTab->nCol; i++){
170451 sqlite3_value *p = 0;
170452 if( op!=SQLITE_INSERT ){
170453 TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170454 assert( trc==SQLITE_OK );
170455 }else if( pTab->abPK[i] ){
170456 TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170457 assert( trc==SQLITE_OK );
170458 }
170459
170460 /* This may fail if SQLite value p contains a utf-16 string that must
170461 ** be converted to utf-8 and an OOM error occurs while doing so. */
170462 rc = sessionSerializeValue(0, p, &nByte);
170463 if( rc!=SQLITE_OK ) goto error_out;
170464 }
170465
170466 /* Allocate the change object */
170467 pChange = (SessionChange *)sqlite3_malloc(nByte);
170468 if( !pChange ){
170469 rc = SQLITE_NOMEM;
170470 goto error_out;
170471 }else{
170472 memset(pChange, 0, sizeof(SessionChange));
170473 pChange->aRecord = (u8 *)&pChange[1];
170474 }
170475
170476 /* Populate the change object. None of the preupdate_old(),
170477 ** preupdate_new() or SerializeValue() calls below may fail as all
170478 ** required values and encodings have already been cached in memory.
170479 ** It is not possible for an OOM to occur in this block. */
170480 nByte = 0;
170481 for(i=0; i<pTab->nCol; i++){
170482 sqlite3_value *p = 0;
170483 if( op!=SQLITE_INSERT ){
170484 pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170485 }else if( pTab->abPK[i] ){
170486 pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170487 }
170488 sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
170489 }
170490
170491 /* Add the change to the hash-table */
170492 if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
170493 pChange->bIndirect = 1;
170494 }
170495 pChange->nRecord = nByte;
170496 pChange->op = op;
170497 pChange->pNext = pTab->apChange[iHash];
170498 pTab->apChange[iHash] = pChange;
170499
170500 }else if( pC->bIndirect ){
170501 /* If the existing change is considered "indirect", but this current
170502 ** change is "direct", mark the change object as direct. */
170503 if( pSession->hook.xDepth(pSession->hook.pCtx)==0
170504 && pSession->bIndirect==0
170505 ){
170506 pC->bIndirect = 0;
170507 }
170508 }
170509 }
170510
170511 /* If an error has occurred, mark the session object as failed. */
170512 error_out:
170513 if( rc!=SQLITE_OK ){
170514 pSession->rc = rc;
170515 }
170516 }
170517
170518 static int sessionFindTable(
170519 sqlite3_session *pSession,
170520 const char *zName,
170521 SessionTable **ppTab
170522 ){
170523 int rc = SQLITE_OK;
170524 int nName = sqlite3Strlen30(zName);
170525 SessionTable *pRet;
170526
170527 /* Search for an existing table */
170528 for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
170529 if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
170530 }
170531
170532 if( pRet==0 && pSession->bAutoAttach ){
170533 /* If there is a table-filter configured, invoke it. If it returns 0,
170534 ** do not automatically add the new table. */
170535 if( pSession->xTableFilter==0
170536 || pSession->xTableFilter(pSession->pFilterCtx, zName)
170537 ){
170538 rc = sqlite3session_attach(pSession, zName);
170539 if( rc==SQLITE_OK ){
170540 for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
170541 assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
170542 }
170543 }
170544 }
170545
170546 assert( rc==SQLITE_OK || pRet==0 );
170547 *ppTab = pRet;
170548 return rc;
170549 }
170550
170551 /*
170552 ** The 'pre-update' hook registered by this module with SQLite databases.
170553 */
170554 static void xPreUpdate(
170555 void *pCtx, /* Copy of third arg to preupdate_hook() */
170556 sqlite3 *db, /* Database handle */
170557 int op, /* SQLITE_UPDATE, DELETE or INSERT */
170558 char const *zDb, /* Database name */
170559 char const *zName, /* Table name */
170560 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
170561 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
170562 ){
170563 sqlite3_session *pSession;
170564 int nDb = sqlite3Strlen30(zDb);
170565
170566 assert( sqlite3_mutex_held(db->mutex) );
170567
170568 for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
170569 SessionTable *pTab;
170570
170571 /* If this session is attached to a different database ("main", "temp"
170572 ** etc.), or if it is not currently enabled, there is nothing to do. Skip
170573 ** to the next session object attached to this database. */
170574 if( pSession->bEnable==0 ) continue;
170575 if( pSession->rc ) continue;
170576 if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
170577
170578 pSession->rc = sessionFindTable(pSession, zName, &pTab);
170579 if( pTab ){
170580 assert( pSession->rc==SQLITE_OK );
170581 sessionPreupdateOneChange(op, pSession, pTab);
170582 if( op==SQLITE_UPDATE ){
170583 sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
170584 }
170585 }
170586 }
170587 }
170588
170589 /*
170590 ** The pre-update hook implementations.
170591 */
170592 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170593 return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
170594 }
170595 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170596 return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
170597 }
170598 static int sessionPreupdateCount(void *pCtx){
170599 return sqlite3_preupdate_count((sqlite3*)pCtx);
170600 }
170601 static int sessionPreupdateDepth(void *pCtx){
170602 return sqlite3_preupdate_depth((sqlite3*)pCtx);
170603 }
170604
170605 /*
170606 ** Install the pre-update hooks on the session object passed as the only
170607 ** argument.
170608 */
170609 static void sessionPreupdateHooks(
170610 sqlite3_session *pSession
170611 ){
170612 pSession->hook.pCtx = (void*)pSession->db;
170613 pSession->hook.xOld = sessionPreupdateOld;
170614 pSession->hook.xNew = sessionPreupdateNew;
170615 pSession->hook.xCount = sessionPreupdateCount;
170616 pSession->hook.xDepth = sessionPreupdateDepth;
170617 }
170618
170619 typedef struct SessionDiffCtx SessionDiffCtx;
170620 struct SessionDiffCtx {
170621 sqlite3_stmt *pStmt;
170622 int nOldOff;
170623 };
170624
170625 /*
170626 ** The diff hook implementations.
170627 */
170628 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170629 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170630 *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
170631 return SQLITE_OK;
170632 }
170633 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170634 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170635 *ppVal = sqlite3_column_value(p->pStmt, iVal);
170636 return SQLITE_OK;
170637 }
170638 static int sessionDiffCount(void *pCtx){
170639 SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170640 return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
170641 }
170642 static int sessionDiffDepth(void *pCtx){
170643 return 0;
170644 }
170645
170646 /*
170647 ** Install the diff hooks on the session object passed as the only
170648 ** argument.
170649 */
170650 static void sessionDiffHooks(
170651 sqlite3_session *pSession,
170652 SessionDiffCtx *pDiffCtx
170653 ){
170654 pSession->hook.pCtx = (void*)pDiffCtx;
170655 pSession->hook.xOld = sessionDiffOld;
170656 pSession->hook.xNew = sessionDiffNew;
170657 pSession->hook.xCount = sessionDiffCount;
170658 pSession->hook.xDepth = sessionDiffDepth;
170659 }
170660
170661 static char *sessionExprComparePK(
170662 int nCol,
170663 const char *zDb1, const char *zDb2,
170664 const char *zTab,
170665 const char **azCol, u8 *abPK
170666 ){
170667 int i;
170668 const char *zSep = "";
170669 char *zRet = 0;
170670
170671 for(i=0; i<nCol; i++){
170672 if( abPK[i] ){
170673 zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
170674 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170675 );
170676 zSep = " AND ";
170677 if( zRet==0 ) break;
170678 }
170679 }
170680
170681 return zRet;
170682 }
170683
170684 static char *sessionExprCompareOther(
170685 int nCol,
170686 const char *zDb1, const char *zDb2,
170687 const char *zTab,
170688 const char **azCol, u8 *abPK
170689 ){
170690 int i;
170691 const char *zSep = "";
170692 char *zRet = 0;
170693 int bHave = 0;
170694
170695 for(i=0; i<nCol; i++){
170696 if( abPK[i]==0 ){
170697 bHave = 1;
170698 zRet = sqlite3_mprintf(
170699 "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
170700 zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170701 );
170702 zSep = " OR ";
170703 if( zRet==0 ) break;
170704 }
170705 }
170706
170707 if( bHave==0 ){
170708 assert( zRet==0 );
170709 zRet = sqlite3_mprintf("0");
170710 }
170711
170712 return zRet;
170713 }
170714
170715 static char *sessionSelectFindNew(
170716 int nCol,
170717 const char *zDb1, /* Pick rows in this db only */
170718 const char *zDb2, /* But not in this one */
170719 const char *zTbl, /* Table name */
170720 const char *zExpr
170721 ){
170722 char *zRet = sqlite3_mprintf(
170723 "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
170724 " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
170725 ")",
170726 zDb1, zTbl, zDb2, zTbl, zExpr
170727 );
170728 return zRet;
170729 }
170730
170731 static int sessionDiffFindNew(
170732 int op,
170733 sqlite3_session *pSession,
170734 SessionTable *pTab,
170735 const char *zDb1,
170736 const char *zDb2,
170737 char *zExpr
170738 ){
170739 int rc = SQLITE_OK;
170740 char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
170741
170742 if( zStmt==0 ){
170743 rc = SQLITE_NOMEM;
170744 }else{
170745 sqlite3_stmt *pStmt;
170746 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170747 if( rc==SQLITE_OK ){
170748 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170749 pDiffCtx->pStmt = pStmt;
170750 pDiffCtx->nOldOff = 0;
170751 while( SQLITE_ROW==sqlite3_step(pStmt) ){
170752 sessionPreupdateOneChange(op, pSession, pTab);
170753 }
170754 rc = sqlite3_finalize(pStmt);
170755 }
170756 sqlite3_free(zStmt);
170757 }
170758
170759 return rc;
170760 }
170761
170762 static int sessionDiffFindModified(
170763 sqlite3_session *pSession,
170764 SessionTable *pTab,
170765 const char *zFrom,
170766 const char *zExpr
170767 ){
170768 int rc = SQLITE_OK;
170769
170770 char *zExpr2 = sessionExprCompareOther(pTab->nCol,
170771 pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
170772 );
170773 if( zExpr2==0 ){
170774 rc = SQLITE_NOMEM;
170775 }else{
170776 char *zStmt = sqlite3_mprintf(
170777 "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
170778 pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
170779 );
170780 if( zStmt==0 ){
170781 rc = SQLITE_NOMEM;
170782 }else{
170783 sqlite3_stmt *pStmt;
170784 rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170785
170786 if( rc==SQLITE_OK ){
170787 SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170788 pDiffCtx->pStmt = pStmt;
170789 pDiffCtx->nOldOff = pTab->nCol;
170790 while( SQLITE_ROW==sqlite3_step(pStmt) ){
170791 sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
170792 }
170793 rc = sqlite3_finalize(pStmt);
170794 }
170795 sqlite3_free(zStmt);
170796 }
170797 }
170798
170799 return rc;
170800 }
170801
170802 SQLITE_API int SQLITE_STDCALL sqlite3session_diff(
170803 sqlite3_session *pSession,
170804 const char *zFrom,
170805 const char *zTbl,
170806 char **pzErrMsg
170807 ){
170808 const char *zDb = pSession->zDb;
170809 int rc = pSession->rc;
170810 SessionDiffCtx d;
170811
170812 memset(&d, 0, sizeof(d));
170813 sessionDiffHooks(pSession, &d);
170814
170815 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
170816 if( pzErrMsg ) *pzErrMsg = 0;
170817 if( rc==SQLITE_OK ){
170818 char *zExpr = 0;
170819 sqlite3 *db = pSession->db;
170820 SessionTable *pTo; /* Table zTbl */
170821
170822 /* Locate and if necessary initialize the target table object */
170823 rc = sessionFindTable(pSession, zTbl, &pTo);
170824 if( pTo==0 ) goto diff_out;
170825 if( sessionInitTable(pSession, pTo) ){
170826 rc = pSession->rc;
170827 goto diff_out;
170828 }
170829
170830 /* Check the table schemas match */
170831 if( rc==SQLITE_OK ){
170832 int bHasPk = 0;
170833 int bMismatch = 0;
170834 int nCol; /* Columns in zFrom.zTbl */
170835 u8 *abPK;
170836 const char **azCol = 0;
170837 rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
170838 if( rc==SQLITE_OK ){
170839 if( pTo->nCol!=nCol ){
170840 bMismatch = 1;
170841 }else{
170842 int i;
170843 for(i=0; i<nCol; i++){
170844 if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
170845 if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
170846 if( abPK[i] ) bHasPk = 1;
170847 }
170848 }
170849
170850 }
170851 sqlite3_free((char*)azCol);
170852 if( bMismatch ){
170853 *pzErrMsg = sqlite3_mprintf("table schemas do not match");
170854 rc = SQLITE_SCHEMA;
170855 }
170856 if( bHasPk==0 ){
170857 /* Ignore tables with no primary keys */
170858 goto diff_out;
170859 }
170860 }
170861
170862 if( rc==SQLITE_OK ){
170863 zExpr = sessionExprComparePK(pTo->nCol,
170864 zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
170865 );
170866 }
170867
170868 /* Find new rows */
170869 if( rc==SQLITE_OK ){
170870 rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
170871 }
170872
170873 /* Find old rows */
170874 if( rc==SQLITE_OK ){
170875 rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
170876 }
170877
170878 /* Find modified rows */
170879 if( rc==SQLITE_OK ){
170880 rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
170881 }
170882
170883 sqlite3_free(zExpr);
170884 }
170885
170886 diff_out:
170887 sessionPreupdateHooks(pSession);
170888 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
170889 return rc;
170890 }
170891
170892 /*
170893 ** Create a session object. This session object will record changes to
170894 ** database zDb attached to connection db.
170895 */
170896 SQLITE_API int SQLITE_STDCALL sqlite3session_create(
170897 sqlite3 *db, /* Database handle */
170898 const char *zDb, /* Name of db (e.g. "main") */
170899 sqlite3_session **ppSession /* OUT: New session object */
170900 ){
170901 sqlite3_session *pNew; /* Newly allocated session object */
170902 sqlite3_session *pOld; /* Session object already attached to db */
170903 int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
170904
170905 /* Zero the output value in case an error occurs. */
170906 *ppSession = 0;
170907
170908 /* Allocate and populate the new session object. */
170909 pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
170910 if( !pNew ) return SQLITE_NOMEM;
170911 memset(pNew, 0, sizeof(sqlite3_session));
170912 pNew->db = db;
170913 pNew->zDb = (char *)&pNew[1];
170914 pNew->bEnable = 1;
170915 memcpy(pNew->zDb, zDb, nDb+1);
170916 sessionPreupdateHooks(pNew);
170917
170918 /* Add the new session object to the linked list of session objects
170919 ** attached to database handle $db. Do this under the cover of the db
170920 ** handle mutex. */
170921 sqlite3_mutex_enter(sqlite3_db_mutex(db));
170922 pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
170923 pNew->pNext = pOld;
170924 sqlite3_mutex_leave(sqlite3_db_mutex(db));
170925
170926 *ppSession = pNew;
170927 return SQLITE_OK;
170928 }
170929
170930 /*
170931 ** Free the list of table objects passed as the first argument. The contents
170932 ** of the changed-rows hash tables are also deleted.
170933 */
170934 static void sessionDeleteTable(SessionTable *pList){
170935 SessionTable *pNext;
170936 SessionTable *pTab;
170937
170938 for(pTab=pList; pTab; pTab=pNext){
170939 int i;
170940 pNext = pTab->pNext;
170941 for(i=0; i<pTab->nChange; i++){
170942 SessionChange *p;
170943 SessionChange *pNextChange;
170944 for(p=pTab->apChange[i]; p; p=pNextChange){
170945 pNextChange = p->pNext;
170946 sqlite3_free(p);
170947 }
170948 }
170949 sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
170950 sqlite3_free(pTab->apChange);
170951 sqlite3_free(pTab);
170952 }
170953 }
170954
170955 /*
170956 ** Delete a session object previously allocated using sqlite3session_create().
170957 */
170958 SQLITE_API void SQLITE_STDCALL sqlite3session_delete(sqlite3_session *pSession){
170959 sqlite3 *db = pSession->db;
170960 sqlite3_session *pHead;
170961 sqlite3_session **pp;
170962
170963 /* Unlink the session from the linked list of sessions attached to the
170964 ** database handle. Hold the db mutex while doing so. */
170965 sqlite3_mutex_enter(sqlite3_db_mutex(db));
170966 pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
170967 for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
170968 if( (*pp)==pSession ){
170969 *pp = (*pp)->pNext;
170970 if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
170971 break;
170972 }
170973 }
170974 sqlite3_mutex_leave(sqlite3_db_mutex(db));
170975
170976 /* Delete all attached table objects. And the contents of their
170977 ** associated hash-tables. */
170978 sessionDeleteTable(pSession->pTable);
170979
170980 /* Free the session object itself. */
170981 sqlite3_free(pSession);
170982 }
170983
170984 /*
170985 ** Set a table filter on a Session Object.
170986 */
170987 SQLITE_API void SQLITE_STDCALL sqlite3session_table_filter(
170988 sqlite3_session *pSession,
170989 int(*xFilter)(void*, const char*),
170990 void *pCtx /* First argument passed to xFilter */
170991 ){
170992 pSession->bAutoAttach = 1;
170993 pSession->pFilterCtx = pCtx;
170994 pSession->xTableFilter = xFilter;
170995 }
170996
170997 /*
170998 ** Attach a table to a session. All subsequent changes made to the table
170999 ** while the session object is enabled will be recorded.
171000 **
171001 ** Only tables that have a PRIMARY KEY defined may be attached. It does
171002 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
171003 ** or not.
171004 */
171005 SQLITE_API int SQLITE_STDCALL sqlite3session_attach(
171006 sqlite3_session *pSession, /* Session object */
171007 const char *zName /* Table name */
171008 ){
171009 int rc = SQLITE_OK;
171010 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171011
171012 if( !zName ){
171013 pSession->bAutoAttach = 1;
171014 }else{
171015 SessionTable *pTab; /* New table object (if required) */
171016 int nName; /* Number of bytes in string zName */
171017
171018 /* First search for an existing entry. If one is found, this call is
171019 ** a no-op. Return early. */
171020 nName = sqlite3Strlen30(zName);
171021 for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
171022 if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
171023 }
171024
171025 if( !pTab ){
171026 /* Allocate new SessionTable object. */
171027 pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
171028 if( !pTab ){
171029 rc = SQLITE_NOMEM;
171030 }else{
171031 /* Populate the new SessionTable object and link it into the list.
171032 ** The new object must be linked onto the end of the list, not
171033 ** simply added to the start of it in order to ensure that tables
171034 ** appear in the correct order when a changeset or patchset is
171035 ** eventually generated. */
171036 SessionTable **ppTab;
171037 memset(pTab, 0, sizeof(SessionTable));
171038 pTab->zName = (char *)&pTab[1];
171039 memcpy(pTab->zName, zName, nName+1);
171040 for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
171041 *ppTab = pTab;
171042 }
171043 }
171044 }
171045
171046 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171047 return rc;
171048 }
171049
171050 /*
171051 ** Ensure that there is room in the buffer to append nByte bytes of data.
171052 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
171053 **
171054 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
171055 ** set *pRc to SQLITE_NOMEM and return non-zero.
171056 */
171057 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
171058 if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
171059 u8 *aNew;
171060 int nNew = p->nAlloc ? p->nAlloc : 128;
171061 do {
171062 nNew = nNew*2;
171063 }while( nNew<(p->nBuf+nByte) );
171064
171065 aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
171066 if( 0==aNew ){
171067 *pRc = SQLITE_NOMEM;
171068 }else{
171069 p->aBuf = aNew;
171070 p->nAlloc = nNew;
171071 }
171072 }
171073 return (*pRc!=SQLITE_OK);
171074 }
171075
171076 /*
171077 ** Append the value passed as the second argument to the buffer passed
171078 ** as the first.
171079 **
171080 ** This function is a no-op if *pRc is non-zero when it is called.
171081 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
171082 ** before returning.
171083 */
171084 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
171085 int rc = *pRc;
171086 if( rc==SQLITE_OK ){
171087 int nByte = 0;
171088 rc = sessionSerializeValue(0, pVal, &nByte);
171089 sessionBufferGrow(p, nByte, &rc);
171090 if( rc==SQLITE_OK ){
171091 rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
171092 p->nBuf += nByte;
171093 }else{
171094 *pRc = rc;
171095 }
171096 }
171097 }
171098
171099 /*
171100 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171101 ** called. Otherwise, append a single byte to the buffer.
171102 **
171103 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171104 ** returning.
171105 */
171106 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
171107 if( 0==sessionBufferGrow(p, 1, pRc) ){
171108 p->aBuf[p->nBuf++] = v;
171109 }
171110 }
171111
171112 /*
171113 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171114 ** called. Otherwise, append a single varint to the buffer.
171115 **
171116 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171117 ** returning.
171118 */
171119 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
171120 if( 0==sessionBufferGrow(p, 9, pRc) ){
171121 p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
171122 }
171123 }
171124
171125 /*
171126 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171127 ** called. Otherwise, append a blob of data to the buffer.
171128 **
171129 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171130 ** returning.
171131 */
171132 static void sessionAppendBlob(
171133 SessionBuffer *p,
171134 const u8 *aBlob,
171135 int nBlob,
171136 int *pRc
171137 ){
171138 if( 0==sessionBufferGrow(p, nBlob, pRc) ){
171139 memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
171140 p->nBuf += nBlob;
171141 }
171142 }
171143
171144 /*
171145 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171146 ** called. Otherwise, append a string to the buffer. All bytes in the string
171147 ** up to (but not including) the nul-terminator are written to the buffer.
171148 **
171149 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171150 ** returning.
171151 */
171152 static void sessionAppendStr(
171153 SessionBuffer *p,
171154 const char *zStr,
171155 int *pRc
171156 ){
171157 int nStr = sqlite3Strlen30(zStr);
171158 if( 0==sessionBufferGrow(p, nStr, pRc) ){
171159 memcpy(&p->aBuf[p->nBuf], zStr, nStr);
171160 p->nBuf += nStr;
171161 }
171162 }
171163
171164 /*
171165 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171166 ** called. Otherwise, append the string representation of integer iVal
171167 ** to the buffer. No nul-terminator is written.
171168 **
171169 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171170 ** returning.
171171 */
171172 static void sessionAppendInteger(
171173 SessionBuffer *p, /* Buffer to append to */
171174 int iVal, /* Value to write the string rep. of */
171175 int *pRc /* IN/OUT: Error code */
171176 ){
171177 char aBuf[24];
171178 sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
171179 sessionAppendStr(p, aBuf, pRc);
171180 }
171181
171182 /*
171183 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171184 ** called. Otherwise, append the string zStr enclosed in quotes (") and
171185 ** with any embedded quote characters escaped to the buffer. No
171186 ** nul-terminator byte is written.
171187 **
171188 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171189 ** returning.
171190 */
171191 static void sessionAppendIdent(
171192 SessionBuffer *p, /* Buffer to a append to */
171193 const char *zStr, /* String to quote, escape and append */
171194 int *pRc /* IN/OUT: Error code */
171195 ){
171196 int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
171197 if( 0==sessionBufferGrow(p, nStr, pRc) ){
171198 char *zOut = (char *)&p->aBuf[p->nBuf];
171199 const char *zIn = zStr;
171200 *zOut++ = '"';
171201 while( *zIn ){
171202 if( *zIn=='"' ) *zOut++ = '"';
171203 *zOut++ = *(zIn++);
171204 }
171205 *zOut++ = '"';
171206 p->nBuf = (int)((u8 *)zOut - p->aBuf);
171207 }
171208 }
171209
171210 /*
171211 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171212 ** called. Otherwse, it appends the serialized version of the value stored
171213 ** in column iCol of the row that SQL statement pStmt currently points
171214 ** to to the buffer.
171215 */
171216 static void sessionAppendCol(
171217 SessionBuffer *p, /* Buffer to append to */
171218 sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
171219 int iCol, /* Column to read value from */
171220 int *pRc /* IN/OUT: Error code */
171221 ){
171222 if( *pRc==SQLITE_OK ){
171223 int eType = sqlite3_column_type(pStmt, iCol);
171224 sessionAppendByte(p, (u8)eType, pRc);
171225 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171226 sqlite3_int64 i;
171227 u8 aBuf[8];
171228 if( eType==SQLITE_INTEGER ){
171229 i = sqlite3_column_int64(pStmt, iCol);
171230 }else{
171231 double r = sqlite3_column_double(pStmt, iCol);
171232 memcpy(&i, &r, 8);
171233 }
171234 sessionPutI64(aBuf, i);
171235 sessionAppendBlob(p, aBuf, 8, pRc);
171236 }
171237 if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
171238 u8 *z;
171239 int nByte;
171240 if( eType==SQLITE_BLOB ){
171241 z = (u8 *)sqlite3_column_blob(pStmt, iCol);
171242 }else{
171243 z = (u8 *)sqlite3_column_text(pStmt, iCol);
171244 }
171245 nByte = sqlite3_column_bytes(pStmt, iCol);
171246 if( z || (eType==SQLITE_BLOB && nByte==0) ){
171247 sessionAppendVarint(p, nByte, pRc);
171248 sessionAppendBlob(p, z, nByte, pRc);
171249 }else{
171250 *pRc = SQLITE_NOMEM;
171251 }
171252 }
171253 }
171254 }
171255
171256 /*
171257 **
171258 ** This function appends an update change to the buffer (see the comments
171259 ** under "CHANGESET FORMAT" at the top of the file). An update change
171260 ** consists of:
171261 **
171262 ** 1 byte: SQLITE_UPDATE (0x17)
171263 ** n bytes: old.* record (see RECORD FORMAT)
171264 ** m bytes: new.* record (see RECORD FORMAT)
171265 **
171266 ** The SessionChange object passed as the third argument contains the
171267 ** values that were stored in the row when the session began (the old.*
171268 ** values). The statement handle passed as the second argument points
171269 ** at the current version of the row (the new.* values).
171270 **
171271 ** If all of the old.* values are equal to their corresponding new.* value
171272 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
171273 **
171274 ** Otherwise, the old.* record contains all primary key values and the
171275 ** original values of any fields that have been modified. The new.* record
171276 ** contains the new values of only those fields that have been modified.
171277 */
171278 static int sessionAppendUpdate(
171279 SessionBuffer *pBuf, /* Buffer to append to */
171280 int bPatchset, /* True for "patchset", 0 for "changeset" */
171281 sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
171282 SessionChange *p, /* Object containing old values */
171283 u8 *abPK /* Boolean array - true for PK columns */
171284 ){
171285 int rc = SQLITE_OK;
171286 SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
171287 int bNoop = 1; /* Set to zero if any values are modified */
171288 int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
171289 int i; /* Used to iterate through columns */
171290 u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
171291
171292 sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
171293 sessionAppendByte(pBuf, p->bIndirect, &rc);
171294 for(i=0; i<sqlite3_column_count(pStmt); i++){
171295 int bChanged = 0;
171296 int nAdvance;
171297 int eType = *pCsr;
171298 switch( eType ){
171299 case SQLITE_NULL:
171300 nAdvance = 1;
171301 if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
171302 bChanged = 1;
171303 }
171304 break;
171305
171306 case SQLITE_FLOAT:
171307 case SQLITE_INTEGER: {
171308 nAdvance = 9;
171309 if( eType==sqlite3_column_type(pStmt, i) ){
171310 sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
171311 if( eType==SQLITE_INTEGER ){
171312 if( iVal==sqlite3_column_int64(pStmt, i) ) break;
171313 }else{
171314 double dVal;
171315 memcpy(&dVal, &iVal, 8);
171316 if( dVal==sqlite3_column_double(pStmt, i) ) break;
171317 }
171318 }
171319 bChanged = 1;
171320 break;
171321 }
171322
171323 default: {
171324 int nByte;
171325 int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
171326 assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
171327 nAdvance = nHdr + nByte;
171328 if( eType==sqlite3_column_type(pStmt, i)
171329 && nByte==sqlite3_column_bytes(pStmt, i)
171330 && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
171331 ){
171332 break;
171333 }
171334 bChanged = 1;
171335 }
171336 }
171337
171338 /* If at least one field has been modified, this is not a no-op. */
171339 if( bChanged ) bNoop = 0;
171340
171341 /* Add a field to the old.* record. This is omitted if this modules is
171342 ** currently generating a patchset. */
171343 if( bPatchset==0 ){
171344 if( bChanged || abPK[i] ){
171345 sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
171346 }else{
171347 sessionAppendByte(pBuf, 0, &rc);
171348 }
171349 }
171350
171351 /* Add a field to the new.* record. Or the only record if currently
171352 ** generating a patchset. */
171353 if( bChanged || (bPatchset && abPK[i]) ){
171354 sessionAppendCol(&buf2, pStmt, i, &rc);
171355 }else{
171356 sessionAppendByte(&buf2, 0, &rc);
171357 }
171358
171359 pCsr += nAdvance;
171360 }
171361
171362 if( bNoop ){
171363 pBuf->nBuf = nRewind;
171364 }else{
171365 sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
171366 }
171367 sqlite3_free(buf2.aBuf);
171368
171369 return rc;
171370 }
171371
171372 /*
171373 ** Append a DELETE change to the buffer passed as the first argument. Use
171374 ** the changeset format if argument bPatchset is zero, or the patchset
171375 ** format otherwise.
171376 */
171377 static int sessionAppendDelete(
171378 SessionBuffer *pBuf, /* Buffer to append to */
171379 int bPatchset, /* True for "patchset", 0 for "changeset" */
171380 SessionChange *p, /* Object containing old values */
171381 int nCol, /* Number of columns in table */
171382 u8 *abPK /* Boolean array - true for PK columns */
171383 ){
171384 int rc = SQLITE_OK;
171385
171386 sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
171387 sessionAppendByte(pBuf, p->bIndirect, &rc);
171388
171389 if( bPatchset==0 ){
171390 sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
171391 }else{
171392 int i;
171393 u8 *a = p->aRecord;
171394 for(i=0; i<nCol; i++){
171395 u8 *pStart = a;
171396 int eType = *a++;
171397
171398 switch( eType ){
171399 case 0:
171400 case SQLITE_NULL:
171401 assert( abPK[i]==0 );
171402 break;
171403
171404 case SQLITE_FLOAT:
171405 case SQLITE_INTEGER:
171406 a += 8;
171407 break;
171408
171409 default: {
171410 int n;
171411 a += sessionVarintGet(a, &n);
171412 a += n;
171413 break;
171414 }
171415 }
171416 if( abPK[i] ){
171417 sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
171418 }
171419 }
171420 assert( (a - p->aRecord)==p->nRecord );
171421 }
171422
171423 return rc;
171424 }
171425
171426 /*
171427 ** Formulate and prepare a SELECT statement to retrieve a row from table
171428 ** zTab in database zDb based on its primary key. i.e.
171429 **
171430 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
171431 */
171432 static int sessionSelectStmt(
171433 sqlite3 *db, /* Database handle */
171434 const char *zDb, /* Database name */
171435 const char *zTab, /* Table name */
171436 int nCol, /* Number of columns in table */
171437 const char **azCol, /* Names of table columns */
171438 u8 *abPK, /* PRIMARY KEY array */
171439 sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
171440 ){
171441 int rc = SQLITE_OK;
171442 int i;
171443 const char *zSep = "";
171444 SessionBuffer buf = {0, 0, 0};
171445
171446 sessionAppendStr(&buf, "SELECT * FROM ", &rc);
171447 sessionAppendIdent(&buf, zDb, &rc);
171448 sessionAppendStr(&buf, ".", &rc);
171449 sessionAppendIdent(&buf, zTab, &rc);
171450 sessionAppendStr(&buf, " WHERE ", &rc);
171451 for(i=0; i<nCol; i++){
171452 if( abPK[i] ){
171453 sessionAppendStr(&buf, zSep, &rc);
171454 sessionAppendIdent(&buf, azCol[i], &rc);
171455 sessionAppendStr(&buf, " = ?", &rc);
171456 sessionAppendInteger(&buf, i+1, &rc);
171457 zSep = " AND ";
171458 }
171459 }
171460 if( rc==SQLITE_OK ){
171461 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
171462 }
171463 sqlite3_free(buf.aBuf);
171464 return rc;
171465 }
171466
171467 /*
171468 ** Bind the PRIMARY KEY values from the change passed in argument pChange
171469 ** to the SELECT statement passed as the first argument. The SELECT statement
171470 ** is as prepared by function sessionSelectStmt().
171471 **
171472 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
171473 ** error code (e.g. SQLITE_NOMEM) otherwise.
171474 */
171475 static int sessionSelectBind(
171476 sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
171477 int nCol, /* Number of columns in table */
171478 u8 *abPK, /* PRIMARY KEY array */
171479 SessionChange *pChange /* Change structure */
171480 ){
171481 int i;
171482 int rc = SQLITE_OK;
171483 u8 *a = pChange->aRecord;
171484
171485 for(i=0; i<nCol && rc==SQLITE_OK; i++){
171486 int eType = *a++;
171487
171488 switch( eType ){
171489 case 0:
171490 case SQLITE_NULL:
171491 assert( abPK[i]==0 );
171492 break;
171493
171494 case SQLITE_INTEGER: {
171495 if( abPK[i] ){
171496 i64 iVal = sessionGetI64(a);
171497 rc = sqlite3_bind_int64(pSelect, i+1, iVal);
171498 }
171499 a += 8;
171500 break;
171501 }
171502
171503 case SQLITE_FLOAT: {
171504 if( abPK[i] ){
171505 double rVal;
171506 i64 iVal = sessionGetI64(a);
171507 memcpy(&rVal, &iVal, 8);
171508 rc = sqlite3_bind_double(pSelect, i+1, rVal);
171509 }
171510 a += 8;
171511 break;
171512 }
171513
171514 case SQLITE_TEXT: {
171515 int n;
171516 a += sessionVarintGet(a, &n);
171517 if( abPK[i] ){
171518 rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
171519 }
171520 a += n;
171521 break;
171522 }
171523
171524 default: {
171525 int n;
171526 assert( eType==SQLITE_BLOB );
171527 a += sessionVarintGet(a, &n);
171528 if( abPK[i] ){
171529 rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
171530 }
171531 a += n;
171532 break;
171533 }
171534 }
171535 }
171536
171537 return rc;
171538 }
171539
171540 /*
171541 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
171542 ** is called. Otherwise, append a serialized table header (part of the binary
171543 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
171544 ** SQLite error code before returning.
171545 */
171546 static void sessionAppendTableHdr(
171547 SessionBuffer *pBuf, /* Append header to this buffer */
171548 int bPatchset, /* Use the patchset format if true */
171549 SessionTable *pTab, /* Table object to append header for */
171550 int *pRc /* IN/OUT: Error code */
171551 ){
171552 /* Write a table header */
171553 sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
171554 sessionAppendVarint(pBuf, pTab->nCol, pRc);
171555 sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
171556 sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
171557 }
171558
171559 /*
171560 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
171561 ** (if it is non-zero) based on the current contents of the session object
171562 ** passed as the first argument.
171563 **
171564 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
171565 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
171566 ** occurs, an SQLite error code is returned and both output variables set
171567 ** to 0.
171568 */
171569 static int sessionGenerateChangeset(
171570 sqlite3_session *pSession, /* Session object */
171571 int bPatchset, /* True for patchset, false for changeset */
171572 int (*xOutput)(void *pOut, const void *pData, int nData),
171573 void *pOut, /* First argument for xOutput */
171574 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171575 void **ppChangeset /* OUT: Buffer containing changeset */
171576 ){
171577 sqlite3 *db = pSession->db; /* Source database handle */
171578 SessionTable *pTab; /* Used to iterate through attached tables */
171579 SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
171580 int rc; /* Return code */
171581
171582 assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
171583
171584 /* Zero the output variables in case an error occurs. If this session
171585 ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
171586 ** this call will be a no-op. */
171587 if( xOutput==0 ){
171588 *pnChangeset = 0;
171589 *ppChangeset = 0;
171590 }
171591
171592 if( pSession->rc ) return pSession->rc;
171593 rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
171594 if( rc!=SQLITE_OK ) return rc;
171595
171596 sqlite3_mutex_enter(sqlite3_db_mutex(db));
171597
171598 for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
171599 if( pTab->nEntry ){
171600 const char *zName = pTab->zName;
171601 int nCol; /* Number of columns in table */
171602 u8 *abPK; /* Primary key array */
171603 const char **azCol = 0; /* Table columns */
171604 int i; /* Used to iterate through hash buckets */
171605 sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
171606 int nRewind = buf.nBuf; /* Initial size of write buffer */
171607 int nNoop; /* Size of buffer after writing tbl header */
171608
171609 /* Check the table schema is still Ok. */
171610 rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
171611 if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
171612 rc = SQLITE_SCHEMA;
171613 }
171614
171615 /* Write a table header */
171616 sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
171617
171618 /* Build and compile a statement to execute: */
171619 if( rc==SQLITE_OK ){
171620 rc = sessionSelectStmt(
171621 db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
171622 }
171623
171624 nNoop = buf.nBuf;
171625 for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
171626 SessionChange *p; /* Used to iterate through changes */
171627
171628 for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
171629 rc = sessionSelectBind(pSel, nCol, abPK, p);
171630 if( rc!=SQLITE_OK ) continue;
171631 if( sqlite3_step(pSel)==SQLITE_ROW ){
171632 if( p->op==SQLITE_INSERT ){
171633 int iCol;
171634 sessionAppendByte(&buf, SQLITE_INSERT, &rc);
171635 sessionAppendByte(&buf, p->bIndirect, &rc);
171636 for(iCol=0; iCol<nCol; iCol++){
171637 sessionAppendCol(&buf, pSel, iCol, &rc);
171638 }
171639 }else{
171640 rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
171641 }
171642 }else if( p->op!=SQLITE_INSERT ){
171643 rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
171644 }
171645 if( rc==SQLITE_OK ){
171646 rc = sqlite3_reset(pSel);
171647 }
171648
171649 /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
171650 ** its contents to the xOutput() callback. */
171651 if( xOutput
171652 && rc==SQLITE_OK
171653 && buf.nBuf>nNoop
171654 && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
171655 ){
171656 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171657 nNoop = -1;
171658 buf.nBuf = 0;
171659 }
171660
171661 }
171662 }
171663
171664 sqlite3_finalize(pSel);
171665 if( buf.nBuf==nNoop ){
171666 buf.nBuf = nRewind;
171667 }
171668 sqlite3_free((char*)azCol); /* cast works around VC++ bug */
171669 }
171670 }
171671
171672 if( rc==SQLITE_OK ){
171673 if( xOutput==0 ){
171674 *pnChangeset = buf.nBuf;
171675 *ppChangeset = buf.aBuf;
171676 buf.aBuf = 0;
171677 }else if( buf.nBuf>0 ){
171678 rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171679 }
171680 }
171681
171682 sqlite3_free(buf.aBuf);
171683 sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
171684 sqlite3_mutex_leave(sqlite3_db_mutex(db));
171685 return rc;
171686 }
171687
171688 /*
171689 ** Obtain a changeset object containing all changes recorded by the
171690 ** session object passed as the first argument.
171691 **
171692 ** It is the responsibility of the caller to eventually free the buffer
171693 ** using sqlite3_free().
171694 */
171695 SQLITE_API int SQLITE_STDCALL sqlite3session_changeset(
171696 sqlite3_session *pSession, /* Session object */
171697 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171698 void **ppChangeset /* OUT: Buffer containing changeset */
171699 ){
171700 return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
171701 }
171702
171703 /*
171704 ** Streaming version of sqlite3session_changeset().
171705 */
171706 SQLITE_API int SQLITE_STDCALL sqlite3session_changeset_strm(
171707 sqlite3_session *pSession,
171708 int (*xOutput)(void *pOut, const void *pData, int nData),
171709 void *pOut
171710 ){
171711 return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
171712 }
171713
171714 /*
171715 ** Streaming version of sqlite3session_patchset().
171716 */
171717 SQLITE_API int SQLITE_STDCALL sqlite3session_patchset_strm(
171718 sqlite3_session *pSession,
171719 int (*xOutput)(void *pOut, const void *pData, int nData),
171720 void *pOut
171721 ){
171722 return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
171723 }
171724
171725 /*
171726 ** Obtain a patchset object containing all changes recorded by the
171727 ** session object passed as the first argument.
171728 **
171729 ** It is the responsibility of the caller to eventually free the buffer
171730 ** using sqlite3_free().
171731 */
171732 SQLITE_API int SQLITE_STDCALL sqlite3session_patchset(
171733 sqlite3_session *pSession, /* Session object */
171734 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
171735 void **ppPatchset /* OUT: Buffer containing changeset */
171736 ){
171737 return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
171738 }
171739
171740 /*
171741 ** Enable or disable the session object passed as the first argument.
171742 */
171743 SQLITE_API int SQLITE_STDCALL sqlite3session_enable(sqlite3_session *pSession, int bEnable){
171744 int ret;
171745 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171746 if( bEnable>=0 ){
171747 pSession->bEnable = bEnable;
171748 }
171749 ret = pSession->bEnable;
171750 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171751 return ret;
171752 }
171753
171754 /*
171755 ** Enable or disable the session object passed as the first argument.
171756 */
171757 SQLITE_API int SQLITE_STDCALL sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
171758 int ret;
171759 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171760 if( bIndirect>=0 ){
171761 pSession->bIndirect = bIndirect;
171762 }
171763 ret = pSession->bIndirect;
171764 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171765 return ret;
171766 }
171767
171768 /*
171769 ** Return true if there have been no changes to monitored tables recorded
171770 ** by the session object passed as the only argument.
171771 */
171772 SQLITE_API int SQLITE_STDCALL sqlite3session_isempty(sqlite3_session *pSession){
171773 int ret = 0;
171774 SessionTable *pTab;
171775
171776 sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171777 for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
171778 ret = (pTab->nEntry>0);
171779 }
171780 sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171781
171782 return (ret==0);
171783 }
171784
171785 /*
171786 ** Do the work for either sqlite3changeset_start() or start_strm().
171787 */
171788 static int sessionChangesetStart(
171789 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171790 int (*xInput)(void *pIn, void *pData, int *pnData),
171791 void *pIn,
171792 int nChangeset, /* Size of buffer pChangeset in bytes */
171793 void *pChangeset /* Pointer to buffer containing changeset */
171794 ){
171795 sqlite3_changeset_iter *pRet; /* Iterator to return */
171796 int nByte; /* Number of bytes to allocate for iterator */
171797
171798 assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
171799
171800 /* Zero the output variable in case an error occurs. */
171801 *pp = 0;
171802
171803 /* Allocate and initialize the iterator structure. */
171804 nByte = sizeof(sqlite3_changeset_iter);
171805 pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
171806 if( !pRet ) return SQLITE_NOMEM;
171807 memset(pRet, 0, sizeof(sqlite3_changeset_iter));
171808 pRet->in.aData = (u8 *)pChangeset;
171809 pRet->in.nData = nChangeset;
171810 pRet->in.xInput = xInput;
171811 pRet->in.pIn = pIn;
171812 pRet->in.bEof = (xInput ? 0 : 1);
171813
171814 /* Populate the output variable and return success. */
171815 *pp = pRet;
171816 return SQLITE_OK;
171817 }
171818
171819 /*
171820 ** Create an iterator used to iterate through the contents of a changeset.
171821 */
171822 SQLITE_API int SQLITE_STDCALL sqlite3changeset_start(
171823 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171824 int nChangeset, /* Size of buffer pChangeset in bytes */
171825 void *pChangeset /* Pointer to buffer containing changeset */
171826 ){
171827 return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
171828 }
171829
171830 /*
171831 ** Streaming version of sqlite3changeset_start().
171832 */
171833 SQLITE_API int SQLITE_STDCALL sqlite3changeset_start_strm(
171834 sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171835 int (*xInput)(void *pIn, void *pData, int *pnData),
171836 void *pIn
171837 ){
171838 return sessionChangesetStart(pp, xInput, pIn, 0, 0);
171839 }
171840
171841 /*
171842 ** If the SessionInput object passed as the only argument is a streaming
171843 ** object and the buffer is full, discard some data to free up space.
171844 */
171845 static void sessionDiscardData(SessionInput *pIn){
171846 if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
171847 int nMove = pIn->buf.nBuf - pIn->iNext;
171848 assert( nMove>=0 );
171849 if( nMove>0 ){
171850 memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
171851 }
171852 pIn->buf.nBuf -= pIn->iNext;
171853 pIn->iNext = 0;
171854 pIn->nData = pIn->buf.nBuf;
171855 }
171856 }
171857
171858 /*
171859 ** Ensure that there are at least nByte bytes available in the buffer. Or,
171860 ** if there are not nByte bytes remaining in the input, that all available
171861 ** data is in the buffer.
171862 **
171863 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
171864 */
171865 static int sessionInputBuffer(SessionInput *pIn, int nByte){
171866 int rc = SQLITE_OK;
171867 if( pIn->xInput ){
171868 while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
171869 int nNew = SESSIONS_STRM_CHUNK_SIZE;
171870
171871 if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
171872 if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
171873 rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
171874 if( nNew==0 ){
171875 pIn->bEof = 1;
171876 }else{
171877 pIn->buf.nBuf += nNew;
171878 }
171879 }
171880
171881 pIn->aData = pIn->buf.aBuf;
171882 pIn->nData = pIn->buf.nBuf;
171883 }
171884 }
171885 return rc;
171886 }
171887
171888 /*
171889 ** When this function is called, *ppRec points to the start of a record
171890 ** that contains nCol values. This function advances the pointer *ppRec
171891 ** until it points to the byte immediately following that record.
171892 */
171893 static void sessionSkipRecord(
171894 u8 **ppRec, /* IN/OUT: Record pointer */
171895 int nCol /* Number of values in record */
171896 ){
171897 u8 *aRec = *ppRec;
171898 int i;
171899 for(i=0; i<nCol; i++){
171900 int eType = *aRec++;
171901 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171902 int nByte;
171903 aRec += sessionVarintGet((u8*)aRec, &nByte);
171904 aRec += nByte;
171905 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171906 aRec += 8;
171907 }
171908 }
171909
171910 *ppRec = aRec;
171911 }
171912
171913 /*
171914 ** This function sets the value of the sqlite3_value object passed as the
171915 ** first argument to a copy of the string or blob held in the aData[]
171916 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
171917 ** error occurs.
171918 */
171919 static int sessionValueSetStr(
171920 sqlite3_value *pVal, /* Set the value of this object */
171921 u8 *aData, /* Buffer containing string or blob data */
171922 int nData, /* Size of buffer aData[] in bytes */
171923 u8 enc /* String encoding (0 for blobs) */
171924 ){
171925 /* In theory this code could just pass SQLITE_TRANSIENT as the final
171926 ** argument to sqlite3ValueSetStr() and have the copy created
171927 ** automatically. But doing so makes it difficult to detect any OOM
171928 ** error. Hence the code to create the copy externally. */
171929 u8 *aCopy = sqlite3_malloc(nData+1);
171930 if( aCopy==0 ) return SQLITE_NOMEM;
171931 memcpy(aCopy, aData, nData);
171932 sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
171933 return SQLITE_OK;
171934 }
171935
171936 /*
171937 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
171938 ** for details.
171939 **
171940 ** When this function is called, *paChange points to the start of the record
171941 ** to deserialize. Assuming no error occurs, *paChange is set to point to
171942 ** one byte after the end of the same record before this function returns.
171943 ** If the argument abPK is NULL, then the record contains nCol values. Or,
171944 ** if abPK is other than NULL, then the record contains only the PK fields
171945 ** (in other words, it is a patchset DELETE record).
171946 **
171947 ** If successful, each element of the apOut[] array (allocated by the caller)
171948 ** is set to point to an sqlite3_value object containing the value read
171949 ** from the corresponding position in the record. If that value is not
171950 ** included in the record (i.e. because the record is part of an UPDATE change
171951 ** and the field was not modified), the corresponding element of apOut[] is
171952 ** set to NULL.
171953 **
171954 ** It is the responsibility of the caller to free all sqlite_value structures
171955 ** using sqlite3_free().
171956 **
171957 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
171958 ** The apOut[] array may have been partially populated in this case.
171959 */
171960 static int sessionReadRecord(
171961 SessionInput *pIn, /* Input data */
171962 int nCol, /* Number of values in record */
171963 u8 *abPK, /* Array of primary key flags, or NULL */
171964 sqlite3_value **apOut /* Write values to this array */
171965 ){
171966 int i; /* Used to iterate through columns */
171967 int rc = SQLITE_OK;
171968
171969 for(i=0; i<nCol && rc==SQLITE_OK; i++){
171970 int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
171971 if( abPK && abPK[i]==0 ) continue;
171972 rc = sessionInputBuffer(pIn, 9);
171973 if( rc==SQLITE_OK ){
171974 eType = pIn->aData[pIn->iNext++];
171975 }
171976
171977 assert( apOut[i]==0 );
171978 if( eType ){
171979 apOut[i] = sqlite3ValueNew(0);
171980 if( !apOut[i] ) rc = SQLITE_NOMEM;
171981 }
171982
171983 if( rc==SQLITE_OK ){
171984 u8 *aVal = &pIn->aData[pIn->iNext];
171985 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171986 int nByte;
171987 pIn->iNext += sessionVarintGet(aVal, &nByte);
171988 rc = sessionInputBuffer(pIn, nByte);
171989 if( rc==SQLITE_OK ){
171990 u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
171991 rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
171992 }
171993 pIn->iNext += nByte;
171994 }
171995 if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171996 sqlite3_int64 v = sessionGetI64(aVal);
171997 if( eType==SQLITE_INTEGER ){
171998 sqlite3VdbeMemSetInt64(apOut[i], v);
171999 }else{
172000 double d;
172001 memcpy(&d, &v, 8);
172002 sqlite3VdbeMemSetDouble(apOut[i], d);
172003 }
172004 pIn->iNext += 8;
172005 }
172006 }
172007 }
172008
172009 return rc;
172010 }
172011
172012 /*
172013 ** The input pointer currently points to the second byte of a table-header.
172014 ** Specifically, to the following:
172015 **
172016 ** + number of columns in table (varint)
172017 ** + array of PK flags (1 byte per column),
172018 ** + table name (nul terminated).
172019 **
172020 ** This function ensures that all of the above is present in the input
172021 ** buffer (i.e. that it can be accessed without any calls to xInput()).
172022 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
172023 ** The input pointer is not moved.
172024 */
172025 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
172026 int rc = SQLITE_OK;
172027 int nCol = 0;
172028 int nRead = 0;
172029
172030 rc = sessionInputBuffer(pIn, 9);
172031 if( rc==SQLITE_OK ){
172032 nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
172033 rc = sessionInputBuffer(pIn, nRead+nCol+100);
172034 nRead += nCol;
172035 }
172036
172037 while( rc==SQLITE_OK ){
172038 while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
172039 nRead++;
172040 }
172041 if( (pIn->iNext + nRead)<pIn->nData ) break;
172042 rc = sessionInputBuffer(pIn, nRead + 100);
172043 }
172044 *pnByte = nRead+1;
172045 return rc;
172046 }
172047
172048 /*
172049 ** The input pointer currently points to the first byte of the first field
172050 ** of a record consisting of nCol columns. This function ensures the entire
172051 ** record is buffered. It does not move the input pointer.
172052 **
172053 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
172054 ** the record in bytes. Otherwise, an SQLite error code is returned. The
172055 ** final value of *pnByte is undefined in this case.
172056 */
172057 static int sessionChangesetBufferRecord(
172058 SessionInput *pIn, /* Input data */
172059 int nCol, /* Number of columns in record */
172060 int *pnByte /* OUT: Size of record in bytes */
172061 ){
172062 int rc = SQLITE_OK;
172063 int nByte = 0;
172064 int i;
172065 for(i=0; rc==SQLITE_OK && i<nCol; i++){
172066 int eType;
172067 rc = sessionInputBuffer(pIn, nByte + 10);
172068 if( rc==SQLITE_OK ){
172069 eType = pIn->aData[pIn->iNext + nByte++];
172070 if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172071 int n;
172072 nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
172073 nByte += n;
172074 rc = sessionInputBuffer(pIn, nByte);
172075 }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172076 nByte += 8;
172077 }
172078 }
172079 }
172080 *pnByte = nByte;
172081 return rc;
172082 }
172083
172084 /*
172085 ** The input pointer currently points to the second byte of a table-header.
172086 ** Specifically, to the following:
172087 **
172088 ** + number of columns in table (varint)
172089 ** + array of PK flags (1 byte per column),
172090 ** + table name (nul terminated).
172091 **
172092 ** This function decodes the table-header and populates the p->nCol,
172093 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
172094 ** also allocated or resized according to the new value of p->nCol. The
172095 ** input pointer is left pointing to the byte following the table header.
172096 **
172097 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
172098 ** is returned and the final values of the various fields enumerated above
172099 ** are undefined.
172100 */
172101 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
172102 int rc;
172103 int nCopy;
172104 assert( p->rc==SQLITE_OK );
172105
172106 rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
172107 if( rc==SQLITE_OK ){
172108 int nByte;
172109 int nVarint;
172110 nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
172111 nCopy -= nVarint;
172112 p->in.iNext += nVarint;
172113 nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
172114 p->tblhdr.nBuf = 0;
172115 sessionBufferGrow(&p->tblhdr, nByte, &rc);
172116 }
172117
172118 if( rc==SQLITE_OK ){
172119 int iPK = sizeof(sqlite3_value*)*p->nCol*2;
172120 memset(p->tblhdr.aBuf, 0, iPK);
172121 memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
172122 p->in.iNext += nCopy;
172123 }
172124
172125 p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
172126 p->abPK = (u8*)&p->apValue[p->nCol*2];
172127 p->zTab = (char*)&p->abPK[p->nCol];
172128 return (p->rc = rc);
172129 }
172130
172131 /*
172132 ** Advance the changeset iterator to the next change.
172133 **
172134 ** If both paRec and pnRec are NULL, then this function works like the public
172135 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
172136 ** sqlite3changeset_new() and old() APIs may be used to query for values.
172137 **
172138 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
172139 ** record is written to *paRec before returning and the number of bytes in
172140 ** the record to *pnRec.
172141 **
172142 ** Either way, this function returns SQLITE_ROW if the iterator is
172143 ** successfully advanced to the next change in the changeset, an SQLite
172144 ** error code if an error occurs, or SQLITE_DONE if there are no further
172145 ** changes in the changeset.
172146 */
172147 static int sessionChangesetNext(
172148 sqlite3_changeset_iter *p, /* Changeset iterator */
172149 u8 **paRec, /* If non-NULL, store record pointer here */
172150 int *pnRec /* If non-NULL, store size of record here */
172151 ){
172152 int i;
172153 u8 op;
172154
172155 assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
172156
172157 /* If the iterator is in the error-state, return immediately. */
172158 if( p->rc!=SQLITE_OK ) return p->rc;
172159
172160 /* Free the current contents of p->apValue[], if any. */
172161 if( p->apValue ){
172162 for(i=0; i<p->nCol*2; i++){
172163 sqlite3ValueFree(p->apValue[i]);
172164 }
172165 memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
172166 }
172167
172168 /* Make sure the buffer contains at least 10 bytes of input data, or all
172169 ** remaining data if there are less than 10 bytes available. This is
172170 ** sufficient either for the 'T' or 'P' byte and the varint that follows
172171 ** it, or for the two single byte values otherwise. */
172172 p->rc = sessionInputBuffer(&p->in, 2);
172173 if( p->rc!=SQLITE_OK ) return p->rc;
172174
172175 /* If the iterator is already at the end of the changeset, return DONE. */
172176 if( p->in.iNext>=p->in.nData ){
172177 return SQLITE_DONE;
172178 }
172179
172180 sessionDiscardData(&p->in);
172181 p->in.iCurrent = p->in.iNext;
172182
172183 op = p->in.aData[p->in.iNext++];
172184 if( op=='T' || op=='P' ){
172185 p->bPatchset = (op=='P');
172186 if( sessionChangesetReadTblhdr(p) ) return p->rc;
172187 if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
172188 p->in.iCurrent = p->in.iNext;
172189 op = p->in.aData[p->in.iNext++];
172190 }
172191
172192 p->op = op;
172193 p->bIndirect = p->in.aData[p->in.iNext++];
172194 if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
172195 return (p->rc = SQLITE_CORRUPT_BKPT);
172196 }
172197
172198 if( paRec ){
172199 int nVal; /* Number of values to buffer */
172200 if( p->bPatchset==0 && op==SQLITE_UPDATE ){
172201 nVal = p->nCol * 2;
172202 }else if( p->bPatchset && op==SQLITE_DELETE ){
172203 nVal = 0;
172204 for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
172205 }else{
172206 nVal = p->nCol;
172207 }
172208 p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
172209 if( p->rc!=SQLITE_OK ) return p->rc;
172210 *paRec = &p->in.aData[p->in.iNext];
172211 p->in.iNext += *pnRec;
172212 }else{
172213
172214 /* If this is an UPDATE or DELETE, read the old.* record. */
172215 if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
172216 u8 *abPK = p->bPatchset ? p->abPK : 0;
172217 p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
172218 if( p->rc!=SQLITE_OK ) return p->rc;
172219 }
172220
172221 /* If this is an INSERT or UPDATE, read the new.* record. */
172222 if( p->op!=SQLITE_DELETE ){
172223 p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
172224 if( p->rc!=SQLITE_OK ) return p->rc;
172225 }
172226
172227 if( p->bPatchset && p->op==SQLITE_UPDATE ){
172228 /* If this is an UPDATE that is part of a patchset, then all PK and
172229 ** modified fields are present in the new.* record. The old.* record
172230 ** is currently completely empty. This block shifts the PK fields from
172231 ** new.* to old.*, to accommodate the code that reads these arrays. */
172232 for(i=0; i<p->nCol; i++){
172233 assert( p->apValue[i]==0 );
172234 assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
172235 if( p->abPK[i] ){
172236 p->apValue[i] = p->apValue[i+p->nCol];
172237 p->apValue[i+p->nCol] = 0;
172238 }
172239 }
172240 }
172241 }
172242
172243 return SQLITE_ROW;
172244 }
172245
172246 /*
172247 ** Advance an iterator created by sqlite3changeset_start() to the next
172248 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
172249 ** or SQLITE_CORRUPT.
172250 **
172251 ** This function may not be called on iterators passed to a conflict handler
172252 ** callback by changeset_apply().
172253 */
172254 SQLITE_API int SQLITE_STDCALL sqlite3changeset_next(sqlite3_changeset_iter *p){
172255 return sessionChangesetNext(p, 0, 0);
172256 }
172257
172258 /*
172259 ** The following function extracts information on the current change
172260 ** from a changeset iterator. It may only be called after changeset_next()
172261 ** has returned SQLITE_ROW.
172262 */
172263 SQLITE_API int SQLITE_STDCALL sqlite3changeset_op(
172264 sqlite3_changeset_iter *pIter, /* Iterator handle */
172265 const char **pzTab, /* OUT: Pointer to table name */
172266 int *pnCol, /* OUT: Number of columns in table */
172267 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
172268 int *pbIndirect /* OUT: True if change is indirect */
172269 ){
172270 *pOp = pIter->op;
172271 *pnCol = pIter->nCol;
172272 *pzTab = pIter->zTab;
172273 if( pbIndirect ) *pbIndirect = pIter->bIndirect;
172274 return SQLITE_OK;
172275 }
172276
172277 /*
172278 ** Return information regarding the PRIMARY KEY and number of columns in
172279 ** the database table affected by the change that pIter currently points
172280 ** to. This function may only be called after changeset_next() returns
172281 ** SQLITE_ROW.
172282 */
172283 SQLITE_API int SQLITE_STDCALL sqlite3changeset_pk(
172284 sqlite3_changeset_iter *pIter, /* Iterator object */
172285 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
172286 int *pnCol /* OUT: Number of entries in output array */
172287 ){
172288 *pabPK = pIter->abPK;
172289 if( pnCol ) *pnCol = pIter->nCol;
172290 return SQLITE_OK;
172291 }
172292
172293 /*
172294 ** This function may only be called while the iterator is pointing to an
172295 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
172296 ** Otherwise, SQLITE_MISUSE is returned.
172297 **
172298 ** It sets *ppValue to point to an sqlite3_value structure containing the
172299 ** iVal'th value in the old.* record. Or, if that particular value is not
172300 ** included in the record (because the change is an UPDATE and the field
172301 ** was not modified and is not a PK column), set *ppValue to NULL.
172302 **
172303 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172304 ** not modified. Otherwise, SQLITE_OK.
172305 */
172306 SQLITE_API int SQLITE_STDCALL sqlite3changeset_old(
172307 sqlite3_changeset_iter *pIter, /* Changeset iterator */
172308 int iVal, /* Index of old.* value to retrieve */
172309 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
172310 ){
172311 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
172312 return SQLITE_MISUSE;
172313 }
172314 if( iVal<0 || iVal>=pIter->nCol ){
172315 return SQLITE_RANGE;
172316 }
172317 *ppValue = pIter->apValue[iVal];
172318 return SQLITE_OK;
172319 }
172320
172321 /*
172322 ** This function may only be called while the iterator is pointing to an
172323 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
172324 ** Otherwise, SQLITE_MISUSE is returned.
172325 **
172326 ** It sets *ppValue to point to an sqlite3_value structure containing the
172327 ** iVal'th value in the new.* record. Or, if that particular value is not
172328 ** included in the record (because the change is an UPDATE and the field
172329 ** was not modified), set *ppValue to NULL.
172330 **
172331 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172332 ** not modified. Otherwise, SQLITE_OK.
172333 */
172334 SQLITE_API int SQLITE_STDCALL sqlite3changeset_new(
172335 sqlite3_changeset_iter *pIter, /* Changeset iterator */
172336 int iVal, /* Index of new.* value to retrieve */
172337 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
172338 ){
172339 if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
172340 return SQLITE_MISUSE;
172341 }
172342 if( iVal<0 || iVal>=pIter->nCol ){
172343 return SQLITE_RANGE;
172344 }
172345 *ppValue = pIter->apValue[pIter->nCol+iVal];
172346 return SQLITE_OK;
172347 }
172348
172349 /*
172350 ** The following two macros are used internally. They are similar to the
172351 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
172352 ** they omit all error checking and return a pointer to the requested value.
172353 */
172354 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
172355 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
172356
172357 /*
172358 ** This function may only be called with a changeset iterator that has been
172359 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
172360 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
172361 **
172362 ** If successful, *ppValue is set to point to an sqlite3_value structure
172363 ** containing the iVal'th value of the conflicting record.
172364 **
172365 ** If value iVal is out-of-range or some other error occurs, an SQLite error
172366 ** code is returned. Otherwise, SQLITE_OK.
172367 */
172368 SQLITE_API int SQLITE_STDCALL sqlite3changeset_conflict(
172369 sqlite3_changeset_iter *pIter, /* Changeset iterator */
172370 int iVal, /* Index of conflict record value to fetch */
172371 sqlite3_value **ppValue /* OUT: Value from conflicting row */
172372 ){
172373 if( !pIter->pConflict ){
172374 return SQLITE_MISUSE;
172375 }
172376 if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
172377 return SQLITE_RANGE;
172378 }
172379 *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
172380 return SQLITE_OK;
172381 }
172382
172383 /*
172384 ** This function may only be called with an iterator passed to an
172385 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
172386 ** it sets the output variable to the total number of known foreign key
172387 ** violations in the destination database and returns SQLITE_OK.
172388 **
172389 ** In all other cases this function returns SQLITE_MISUSE.
172390 */
172391 SQLITE_API int SQLITE_STDCALL sqlite3changeset_fk_conflicts(
172392 sqlite3_changeset_iter *pIter, /* Changeset iterator */
172393 int *pnOut /* OUT: Number of FK violations */
172394 ){
172395 if( pIter->pConflict || pIter->apValue ){
172396 return SQLITE_MISUSE;
172397 }
172398 *pnOut = pIter->nCol;
172399 return SQLITE_OK;
172400 }
172401
172402
172403 /*
172404 ** Finalize an iterator allocated with sqlite3changeset_start().
172405 **
172406 ** This function may not be called on iterators passed to a conflict handler
172407 ** callback by changeset_apply().
172408 */
172409 SQLITE_API int SQLITE_STDCALL sqlite3changeset_finalize(sqlite3_changeset_iter *p){
172410 int rc = SQLITE_OK;
172411 if( p ){
172412 int i; /* Used to iterate through p->apValue[] */
172413 rc = p->rc;
172414 if( p->apValue ){
172415 for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
172416 }
172417 sqlite3_free(p->tblhdr.aBuf);
172418 sqlite3_free(p->in.buf.aBuf);
172419 sqlite3_free(p);
172420 }
172421 return rc;
172422 }
172423
172424 static int sessionChangesetInvert(
172425 SessionInput *pInput, /* Input changeset */
172426 int (*xOutput)(void *pOut, const void *pData, int nData),
172427 void *pOut,
172428 int *pnInverted, /* OUT: Number of bytes in output changeset */
172429 void **ppInverted /* OUT: Inverse of pChangeset */
172430 ){
172431 int rc = SQLITE_OK; /* Return value */
172432 SessionBuffer sOut; /* Output buffer */
172433 int nCol = 0; /* Number of cols in current table */
172434 u8 *abPK = 0; /* PK array for current table */
172435 sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
172436 SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
172437
172438 /* Initialize the output buffer */
172439 memset(&sOut, 0, sizeof(SessionBuffer));
172440
172441 /* Zero the output variables in case an error occurs. */
172442 if( ppInverted ){
172443 *ppInverted = 0;
172444 *pnInverted = 0;
172445 }
172446
172447 while( 1 ){
172448 u8 eType;
172449
172450 /* Test for EOF. */
172451 if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
172452 if( pInput->iNext>=pInput->nData ) break;
172453 eType = pInput->aData[pInput->iNext];
172454
172455 switch( eType ){
172456 case 'T': {
172457 /* A 'table' record consists of:
172458 **
172459 ** * A constant 'T' character,
172460 ** * Number of columns in said table (a varint),
172461 ** * An array of nCol bytes (sPK),
172462 ** * A nul-terminated table name.
172463 */
172464 int nByte;
172465 int nVar;
172466 pInput->iNext++;
172467 if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
172468 goto finished_invert;
172469 }
172470 nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
172471 sPK.nBuf = 0;
172472 sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
172473 sessionAppendByte(&sOut, eType, &rc);
172474 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172475 if( rc ) goto finished_invert;
172476
172477 pInput->iNext += nByte;
172478 sqlite3_free(apVal);
172479 apVal = 0;
172480 abPK = sPK.aBuf;
172481 break;
172482 }
172483
172484 case SQLITE_INSERT:
172485 case SQLITE_DELETE: {
172486 int nByte;
172487 int bIndirect = pInput->aData[pInput->iNext+1];
172488 int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
172489 pInput->iNext += 2;
172490 assert( rc==SQLITE_OK );
172491 rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
172492 sessionAppendByte(&sOut, eType2, &rc);
172493 sessionAppendByte(&sOut, bIndirect, &rc);
172494 sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172495 pInput->iNext += nByte;
172496 if( rc ) goto finished_invert;
172497 break;
172498 }
172499
172500 case SQLITE_UPDATE: {
172501 int iCol;
172502
172503 if( 0==apVal ){
172504 apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
172505 if( 0==apVal ){
172506 rc = SQLITE_NOMEM;
172507 goto finished_invert;
172508 }
172509 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172510 }
172511
172512 /* Write the header for the new UPDATE change. Same as the original. */
172513 sessionAppendByte(&sOut, eType, &rc);
172514 sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
172515
172516 /* Read the old.* and new.* records for the update change. */
172517 pInput->iNext += 2;
172518 rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
172519 if( rc==SQLITE_OK ){
172520 rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
172521 }
172522
172523 /* Write the new old.* record. Consists of the PK columns from the
172524 ** original old.* record, and the other values from the original
172525 ** new.* record. */
172526 for(iCol=0; iCol<nCol; iCol++){
172527 sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
172528 sessionAppendValue(&sOut, pVal, &rc);
172529 }
172530
172531 /* Write the new new.* record. Consists of a copy of all values
172532 ** from the original old.* record, except for the PK columns, which
172533 ** are set to "undefined". */
172534 for(iCol=0; iCol<nCol; iCol++){
172535 sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
172536 sessionAppendValue(&sOut, pVal, &rc);
172537 }
172538
172539 for(iCol=0; iCol<nCol*2; iCol++){
172540 sqlite3ValueFree(apVal[iCol]);
172541 }
172542 memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172543 if( rc!=SQLITE_OK ){
172544 goto finished_invert;
172545 }
172546
172547 break;
172548 }
172549
172550 default:
172551 rc = SQLITE_CORRUPT_BKPT;
172552 goto finished_invert;
172553 }
172554
172555 assert( rc==SQLITE_OK );
172556 if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
172557 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172558 sOut.nBuf = 0;
172559 if( rc!=SQLITE_OK ) goto finished_invert;
172560 }
172561 }
172562
172563 assert( rc==SQLITE_OK );
172564 if( pnInverted ){
172565 *pnInverted = sOut.nBuf;
172566 *ppInverted = sOut.aBuf;
172567 sOut.aBuf = 0;
172568 }else if( sOut.nBuf>0 ){
172569 rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172570 }
172571
172572 finished_invert:
172573 sqlite3_free(sOut.aBuf);
172574 sqlite3_free(apVal);
172575 sqlite3_free(sPK.aBuf);
172576 return rc;
172577 }
172578
172579
172580 /*
172581 ** Invert a changeset object.
172582 */
172583 SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert(
172584 int nChangeset, /* Number of bytes in input */
172585 const void *pChangeset, /* Input changeset */
172586 int *pnInverted, /* OUT: Number of bytes in output changeset */
172587 void **ppInverted /* OUT: Inverse of pChangeset */
172588 ){
172589 SessionInput sInput;
172590
172591 /* Set up the input stream */
172592 memset(&sInput, 0, sizeof(SessionInput));
172593 sInput.nData = nChangeset;
172594 sInput.aData = (u8*)pChangeset;
172595
172596 return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
172597 }
172598
172599 /*
172600 ** Streaming version of sqlite3changeset_invert().
172601 */
172602 SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert_strm(
172603 int (*xInput)(void *pIn, void *pData, int *pnData),
172604 void *pIn,
172605 int (*xOutput)(void *pOut, const void *pData, int nData),
172606 void *pOut
172607 ){
172608 SessionInput sInput;
172609 int rc;
172610
172611 /* Set up the input stream */
172612 memset(&sInput, 0, sizeof(SessionInput));
172613 sInput.xInput = xInput;
172614 sInput.pIn = pIn;
172615
172616 rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
172617 sqlite3_free(sInput.buf.aBuf);
172618 return rc;
172619 }
172620
172621 typedef struct SessionApplyCtx SessionApplyCtx;
172622 struct SessionApplyCtx {
172623 sqlite3 *db;
172624 sqlite3_stmt *pDelete; /* DELETE statement */
172625 sqlite3_stmt *pUpdate; /* UPDATE statement */
172626 sqlite3_stmt *pInsert; /* INSERT statement */
172627 sqlite3_stmt *pSelect; /* SELECT statement */
172628 int nCol; /* Size of azCol[] and abPK[] arrays */
172629 const char **azCol; /* Array of column names */
172630 u8 *abPK; /* Boolean array - true if column is in PK */
172631
172632 int bDeferConstraints; /* True to defer constraints */
172633 SessionBuffer constraints; /* Deferred constraints are stored here */
172634 };
172635
172636 /*
172637 ** Formulate a statement to DELETE a row from database db. Assuming a table
172638 ** structure like this:
172639 **
172640 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172641 **
172642 ** The DELETE statement looks like this:
172643 **
172644 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
172645 **
172646 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
172647 ** matching b and d values, or 1 otherwise. The second case comes up if the
172648 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
172649 **
172650 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
172651 ** pointing to the prepared version of the SQL statement.
172652 */
172653 static int sessionDeleteRow(
172654 sqlite3 *db, /* Database handle */
172655 const char *zTab, /* Table name */
172656 SessionApplyCtx *p /* Session changeset-apply context */
172657 ){
172658 int i;
172659 const char *zSep = "";
172660 int rc = SQLITE_OK;
172661 SessionBuffer buf = {0, 0, 0};
172662 int nPk = 0;
172663
172664 sessionAppendStr(&buf, "DELETE FROM ", &rc);
172665 sessionAppendIdent(&buf, zTab, &rc);
172666 sessionAppendStr(&buf, " WHERE ", &rc);
172667
172668 for(i=0; i<p->nCol; i++){
172669 if( p->abPK[i] ){
172670 nPk++;
172671 sessionAppendStr(&buf, zSep, &rc);
172672 sessionAppendIdent(&buf, p->azCol[i], &rc);
172673 sessionAppendStr(&buf, " = ?", &rc);
172674 sessionAppendInteger(&buf, i+1, &rc);
172675 zSep = " AND ";
172676 }
172677 }
172678
172679 if( nPk<p->nCol ){
172680 sessionAppendStr(&buf, " AND (?", &rc);
172681 sessionAppendInteger(&buf, p->nCol+1, &rc);
172682 sessionAppendStr(&buf, " OR ", &rc);
172683
172684 zSep = "";
172685 for(i=0; i<p->nCol; i++){
172686 if( !p->abPK[i] ){
172687 sessionAppendStr(&buf, zSep, &rc);
172688 sessionAppendIdent(&buf, p->azCol[i], &rc);
172689 sessionAppendStr(&buf, " IS ?", &rc);
172690 sessionAppendInteger(&buf, i+1, &rc);
172691 zSep = "AND ";
172692 }
172693 }
172694 sessionAppendStr(&buf, ")", &rc);
172695 }
172696
172697 if( rc==SQLITE_OK ){
172698 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
172699 }
172700 sqlite3_free(buf.aBuf);
172701
172702 return rc;
172703 }
172704
172705 /*
172706 ** Formulate and prepare a statement to UPDATE a row from database db.
172707 ** Assuming a table structure like this:
172708 **
172709 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172710 **
172711 ** The UPDATE statement looks like this:
172712 **
172713 ** UPDATE x SET
172714 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
172715 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
172716 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
172717 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
172718 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
172719 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
172720 ** )
172721 **
172722 ** For each column in the table, there are three variables to bind:
172723 **
172724 ** ?(i*3+1) The old.* value of the column, if any.
172725 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
172726 ** ?(i*3+3) The new.* value of the column, if any.
172727 **
172728 ** Also, a boolean flag that, if set to true, causes the statement to update
172729 ** a row even if the non-PK values do not match. This is required if the
172730 ** conflict-handler is invoked with CHANGESET_DATA and returns
172731 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
172732 **
172733 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
172734 ** pointing to the prepared version of the SQL statement.
172735 */
172736 static int sessionUpdateRow(
172737 sqlite3 *db, /* Database handle */
172738 const char *zTab, /* Table name */
172739 SessionApplyCtx *p /* Session changeset-apply context */
172740 ){
172741 int rc = SQLITE_OK;
172742 int i;
172743 const char *zSep = "";
172744 SessionBuffer buf = {0, 0, 0};
172745
172746 /* Append "UPDATE tbl SET " */
172747 sessionAppendStr(&buf, "UPDATE ", &rc);
172748 sessionAppendIdent(&buf, zTab, &rc);
172749 sessionAppendStr(&buf, " SET ", &rc);
172750
172751 /* Append the assignments */
172752 for(i=0; i<p->nCol; i++){
172753 sessionAppendStr(&buf, zSep, &rc);
172754 sessionAppendIdent(&buf, p->azCol[i], &rc);
172755 sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
172756 sessionAppendInteger(&buf, i*3+2, &rc);
172757 sessionAppendStr(&buf, " THEN ?", &rc);
172758 sessionAppendInteger(&buf, i*3+3, &rc);
172759 sessionAppendStr(&buf, " ELSE ", &rc);
172760 sessionAppendIdent(&buf, p->azCol[i], &rc);
172761 sessionAppendStr(&buf, " END", &rc);
172762 zSep = ", ";
172763 }
172764
172765 /* Append the PK part of the WHERE clause */
172766 sessionAppendStr(&buf, " WHERE ", &rc);
172767 for(i=0; i<p->nCol; i++){
172768 if( p->abPK[i] ){
172769 sessionAppendIdent(&buf, p->azCol[i], &rc);
172770 sessionAppendStr(&buf, " = ?", &rc);
172771 sessionAppendInteger(&buf, i*3+1, &rc);
172772 sessionAppendStr(&buf, " AND ", &rc);
172773 }
172774 }
172775
172776 /* Append the non-PK part of the WHERE clause */
172777 sessionAppendStr(&buf, " (?", &rc);
172778 sessionAppendInteger(&buf, p->nCol*3+1, &rc);
172779 sessionAppendStr(&buf, " OR 1", &rc);
172780 for(i=0; i<p->nCol; i++){
172781 if( !p->abPK[i] ){
172782 sessionAppendStr(&buf, " AND (?", &rc);
172783 sessionAppendInteger(&buf, i*3+2, &rc);
172784 sessionAppendStr(&buf, "=0 OR ", &rc);
172785 sessionAppendIdent(&buf, p->azCol[i], &rc);
172786 sessionAppendStr(&buf, " IS ?", &rc);
172787 sessionAppendInteger(&buf, i*3+1, &rc);
172788 sessionAppendStr(&buf, ")", &rc);
172789 }
172790 }
172791 sessionAppendStr(&buf, ")", &rc);
172792
172793 if( rc==SQLITE_OK ){
172794 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
172795 }
172796 sqlite3_free(buf.aBuf);
172797
172798 return rc;
172799 }
172800
172801 /*
172802 ** Formulate and prepare an SQL statement to query table zTab by primary
172803 ** key. Assuming the following table structure:
172804 **
172805 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172806 **
172807 ** The SELECT statement looks like this:
172808 **
172809 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
172810 **
172811 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
172812 ** pointing to the prepared version of the SQL statement.
172813 */
172814 static int sessionSelectRow(
172815 sqlite3 *db, /* Database handle */
172816 const char *zTab, /* Table name */
172817 SessionApplyCtx *p /* Session changeset-apply context */
172818 ){
172819 return sessionSelectStmt(
172820 db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
172821 }
172822
172823 /*
172824 ** Formulate and prepare an INSERT statement to add a record to table zTab.
172825 ** For example:
172826 **
172827 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
172828 **
172829 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
172830 ** pointing to the prepared version of the SQL statement.
172831 */
172832 static int sessionInsertRow(
172833 sqlite3 *db, /* Database handle */
172834 const char *zTab, /* Table name */
172835 SessionApplyCtx *p /* Session changeset-apply context */
172836 ){
172837 int rc = SQLITE_OK;
172838 int i;
172839 SessionBuffer buf = {0, 0, 0};
172840
172841 sessionAppendStr(&buf, "INSERT INTO main.", &rc);
172842 sessionAppendIdent(&buf, zTab, &rc);
172843 sessionAppendStr(&buf, " VALUES(?", &rc);
172844 for(i=1; i<p->nCol; i++){
172845 sessionAppendStr(&buf, ", ?", &rc);
172846 }
172847 sessionAppendStr(&buf, ")", &rc);
172848
172849 if( rc==SQLITE_OK ){
172850 rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
172851 }
172852 sqlite3_free(buf.aBuf);
172853 return rc;
172854 }
172855
172856 /*
172857 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
172858 ** See comments in the body of this function for details.
172859 */
172860 static int sessionBindValue(
172861 sqlite3_stmt *pStmt, /* Statement to bind value to */
172862 int i, /* Parameter number to bind to */
172863 sqlite3_value *pVal /* Value to bind */
172864 ){
172865 int eType = sqlite3_value_type(pVal);
172866 /* COVERAGE: The (pVal->z==0) branch is never true using current versions
172867 ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
172868 ** the (pVal->z) variable remains as it was or the type of the value is
172869 ** set to SQLITE_NULL. */
172870 if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
172871 /* This condition occurs when an earlier OOM in a call to
172872 ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
172873 ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
172874 return SQLITE_NOMEM;
172875 }
172876 return sqlite3_bind_value(pStmt, i, pVal);
172877 }
172878
172879 /*
172880 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
172881 ** transfers new.* values from the current iterator entry to statement
172882 ** pStmt. The table being inserted into has nCol columns.
172883 **
172884 ** New.* value $i from the iterator is bound to variable ($i+1) of
172885 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
172886 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
172887 ** to an array nCol elements in size. In this case only those values for
172888 ** which abPK[$i] is true are read from the iterator and bound to the
172889 ** statement.
172890 **
172891 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
172892 */
172893 static int sessionBindRow(
172894 sqlite3_changeset_iter *pIter, /* Iterator to read values from */
172895 int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
172896 int nCol, /* Number of columns */
172897 u8 *abPK, /* If not NULL, bind only if true */
172898 sqlite3_stmt *pStmt /* Bind values to this statement */
172899 ){
172900 int i;
172901 int rc = SQLITE_OK;
172902
172903 /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
172904 ** argument iterator points to a suitable entry. Make sure that xValue
172905 ** is one of these to guarantee that it is safe to ignore the return
172906 ** in the code below. */
172907 assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
172908
172909 for(i=0; rc==SQLITE_OK && i<nCol; i++){
172910 if( !abPK || abPK[i] ){
172911 sqlite3_value *pVal;
172912 (void)xValue(pIter, i, &pVal);
172913 rc = sessionBindValue(pStmt, i+1, pVal);
172914 }
172915 }
172916 return rc;
172917 }
172918
172919 /*
172920 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
172921 ** This function binds the primary key values from the change that changeset
172922 ** iterator pIter points to to the SELECT and attempts to seek to the table
172923 ** entry. If a row is found, the SELECT statement left pointing at the row
172924 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
172925 ** has occured, the statement is reset and SQLITE_OK is returned. If an
172926 ** error occurs, the statement is reset and an SQLite error code is returned.
172927 **
172928 ** If this function returns SQLITE_ROW, the caller must eventually reset()
172929 ** statement pSelect. If any other value is returned, the statement does
172930 ** not require a reset().
172931 **
172932 ** If the iterator currently points to an INSERT record, bind values from the
172933 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
172934 ** UPDATE, bind values from the old.* record.
172935 */
172936 static int sessionSeekToRow(
172937 sqlite3 *db, /* Database handle */
172938 sqlite3_changeset_iter *pIter, /* Changeset iterator */
172939 u8 *abPK, /* Primary key flags array */
172940 sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
172941 ){
172942 int rc; /* Return code */
172943 int nCol; /* Number of columns in table */
172944 int op; /* Changset operation (SQLITE_UPDATE etc.) */
172945 const char *zDummy; /* Unused */
172946
172947 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
172948 rc = sessionBindRow(pIter,
172949 op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
172950 nCol, abPK, pSelect
172951 );
172952
172953 if( rc==SQLITE_OK ){
172954 rc = sqlite3_step(pSelect);
172955 if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
172956 }
172957
172958 return rc;
172959 }
172960
172961 /*
172962 ** Invoke the conflict handler for the change that the changeset iterator
172963 ** currently points to.
172964 **
172965 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
172966 ** If argument pbReplace is NULL, then the type of conflict handler invoked
172967 ** depends solely on eType, as follows:
172968 **
172969 ** eType value Value passed to xConflict
172970 ** -------------------------------------------------
172971 ** CHANGESET_DATA CHANGESET_NOTFOUND
172972 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
172973 **
172974 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
172975 ** record with the same primary key as the record about to be deleted, updated
172976 ** or inserted. If such a record can be found, it is available to the conflict
172977 ** handler as the "conflicting" record. In this case the type of conflict
172978 ** handler invoked is as follows:
172979 **
172980 ** eType value PK Record found? Value passed to xConflict
172981 ** ----------------------------------------------------------------
172982 ** CHANGESET_DATA Yes CHANGESET_DATA
172983 ** CHANGESET_DATA No CHANGESET_NOTFOUND
172984 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
172985 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
172986 **
172987 ** If pbReplace is not NULL, and a record with a matching PK is found, and
172988 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
172989 ** is set to non-zero before returning SQLITE_OK.
172990 **
172991 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
172992 ** returned. Or, if the conflict handler returns an invalid value,
172993 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
172994 ** this function returns SQLITE_OK.
172995 */
172996 static int sessionConflictHandler(
172997 int eType, /* Either CHANGESET_DATA or CONFLICT */
172998 SessionApplyCtx *p, /* changeset_apply() context */
172999 sqlite3_changeset_iter *pIter, /* Changeset iterator */
173000 int(*xConflict)(void *, int, sqlite3_changeset_iter*),
173001 void *pCtx, /* First argument for conflict handler */
173002 int *pbReplace /* OUT: Set to true if PK row is found */
173003 ){
173004 int res = 0; /* Value returned by conflict handler */
173005 int rc;
173006 int nCol;
173007 int op;
173008 const char *zDummy;
173009
173010 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173011
173012 assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
173013 assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
173014 assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
173015
173016 /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
173017 if( pbReplace ){
173018 rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
173019 }else{
173020 rc = SQLITE_OK;
173021 }
173022
173023 if( rc==SQLITE_ROW ){
173024 /* There exists another row with the new.* primary key. */
173025 pIter->pConflict = p->pSelect;
173026 res = xConflict(pCtx, eType, pIter);
173027 pIter->pConflict = 0;
173028 rc = sqlite3_reset(p->pSelect);
173029 }else if( rc==SQLITE_OK ){
173030 if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
173031 /* Instead of invoking the conflict handler, append the change blob
173032 ** to the SessionApplyCtx.constraints buffer. */
173033 u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
173034 int nBlob = pIter->in.iNext - pIter->in.iCurrent;
173035 sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
173036 res = SQLITE_CHANGESET_OMIT;
173037 }else{
173038 /* No other row with the new.* primary key. */
173039 res = xConflict(pCtx, eType+1, pIter);
173040 if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
173041 }
173042 }
173043
173044 if( rc==SQLITE_OK ){
173045 switch( res ){
173046 case SQLITE_CHANGESET_REPLACE:
173047 assert( pbReplace );
173048 *pbReplace = 1;
173049 break;
173050
173051 case SQLITE_CHANGESET_OMIT:
173052 break;
173053
173054 case SQLITE_CHANGESET_ABORT:
173055 rc = SQLITE_ABORT;
173056 break;
173057
173058 default:
173059 rc = SQLITE_MISUSE;
173060 break;
173061 }
173062 }
173063
173064 return rc;
173065 }
173066
173067 /*
173068 ** Attempt to apply the change that the iterator passed as the first argument
173069 ** currently points to to the database. If a conflict is encountered, invoke
173070 ** the conflict handler callback.
173071 **
173072 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
173073 ** one is encountered, update or delete the row with the matching primary key
173074 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
173075 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
173076 ** to true before returning. In this case the caller will invoke this function
173077 ** again, this time with pbRetry set to NULL.
173078 **
173079 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
173080 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
173081 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
173082 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
173083 ** before retrying. In this case the caller attempts to remove the conflicting
173084 ** row before invoking this function again, this time with pbReplace set
173085 ** to NULL.
173086 **
173087 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
173088 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
173089 ** returned.
173090 */
173091 static int sessionApplyOneOp(
173092 sqlite3_changeset_iter *pIter, /* Changeset iterator */
173093 SessionApplyCtx *p, /* changeset_apply() context */
173094 int(*xConflict)(void *, int, sqlite3_changeset_iter *),
173095 void *pCtx, /* First argument for the conflict handler */
173096 int *pbReplace, /* OUT: True to remove PK row and retry */
173097 int *pbRetry /* OUT: True to retry. */
173098 ){
173099 const char *zDummy;
173100 int op;
173101 int nCol;
173102 int rc = SQLITE_OK;
173103
173104 assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
173105 assert( p->azCol && p->abPK );
173106 assert( !pbReplace || *pbReplace==0 );
173107
173108 sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173109
173110 if( op==SQLITE_DELETE ){
173111
173112 /* Bind values to the DELETE statement. If conflict handling is required,
173113 ** bind values for all columns and set bound variable (nCol+1) to true.
173114 ** Or, if conflict handling is not required, bind just the PK column
173115 ** values and, if it exists, set (nCol+1) to false. Conflict handling
173116 ** is not required if:
173117 **
173118 ** * this is a patchset, or
173119 ** * (pbRetry==0), or
173120 ** * all columns of the table are PK columns (in this case there is
173121 ** no (nCol+1) variable to bind to).
173122 */
173123 u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
173124 rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
173125 if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
173126 rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
173127 }
173128 if( rc!=SQLITE_OK ) return rc;
173129
173130 sqlite3_step(p->pDelete);
173131 rc = sqlite3_reset(p->pDelete);
173132 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173133 rc = sessionConflictHandler(
173134 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173135 );
173136 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173137 rc = sessionConflictHandler(
173138 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173139 );
173140 }
173141
173142 }else if( op==SQLITE_UPDATE ){
173143 int i;
173144
173145 /* Bind values to the UPDATE statement. */
173146 for(i=0; rc==SQLITE_OK && i<nCol; i++){
173147 sqlite3_value *pOld = sessionChangesetOld(pIter, i);
173148 sqlite3_value *pNew = sessionChangesetNew(pIter, i);
173149
173150 sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
173151 if( pOld ){
173152 rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
173153 }
173154 if( rc==SQLITE_OK && pNew ){
173155 rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
173156 }
173157 }
173158 if( rc==SQLITE_OK ){
173159 sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
173160 }
173161 if( rc!=SQLITE_OK ) return rc;
173162
173163 /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
173164 ** the result will be SQLITE_OK with 0 rows modified. */
173165 sqlite3_step(p->pUpdate);
173166 rc = sqlite3_reset(p->pUpdate);
173167
173168 if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173169 /* A NOTFOUND or DATA error. Search the table to see if it contains
173170 ** a row with a matching primary key. If so, this is a DATA conflict.
173171 ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
173172
173173 rc = sessionConflictHandler(
173174 SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173175 );
173176
173177 }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173178 /* This is always a CONSTRAINT conflict. */
173179 rc = sessionConflictHandler(
173180 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173181 );
173182 }
173183
173184 }else{
173185 assert( op==SQLITE_INSERT );
173186 rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
173187 if( rc!=SQLITE_OK ) return rc;
173188
173189 sqlite3_step(p->pInsert);
173190 rc = sqlite3_reset(p->pInsert);
173191 if( (rc&0xff)==SQLITE_CONSTRAINT ){
173192 rc = sessionConflictHandler(
173193 SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
173194 );
173195 }
173196 }
173197
173198 return rc;
173199 }
173200
173201 /*
173202 ** Attempt to apply the change that the iterator passed as the first argument
173203 ** currently points to to the database. If a conflict is encountered, invoke
173204 ** the conflict handler callback.
173205 **
173206 ** The difference between this function and sessionApplyOne() is that this
173207 ** function handles the case where the conflict-handler is invoked and
173208 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
173209 ** retried in some manner.
173210 */
173211 static int sessionApplyOneWithRetry(
173212 sqlite3 *db, /* Apply change to "main" db of this handle */
173213 sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
173214 SessionApplyCtx *pApply, /* Apply context */
173215 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173216 void *pCtx /* First argument passed to xConflict */
173217 ){
173218 int bReplace = 0;
173219 int bRetry = 0;
173220 int rc;
173221
173222 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
173223 assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
173224
173225 /* If the bRetry flag is set, the change has not been applied due to an
173226 ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
173227 ** a row with the correct PK is present in the db, but one or more other
173228 ** fields do not contain the expected values) and the conflict handler
173229 ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
173230 ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
173231 ** the SQLITE_CHANGESET_DATA problem. */
173232 if( bRetry ){
173233 assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
173234 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173235 }
173236
173237 /* If the bReplace flag is set, the change is an INSERT that has not
173238 ** been performed because the database already contains a row with the
173239 ** specified primary key and the conflict handler returned
173240 ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
173241 ** before reattempting the INSERT. */
173242 else if( bReplace ){
173243 assert( pIter->op==SQLITE_INSERT );
173244 rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
173245 if( rc==SQLITE_OK ){
173246 rc = sessionBindRow(pIter,
173247 sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
173248 sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
173249 }
173250 if( rc==SQLITE_OK ){
173251 sqlite3_step(pApply->pDelete);
173252 rc = sqlite3_reset(pApply->pDelete);
173253 }
173254 if( rc==SQLITE_OK ){
173255 rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173256 }
173257 if( rc==SQLITE_OK ){
173258 rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
173259 }
173260 }
173261
173262 return rc;
173263 }
173264
173265 /*
173266 ** Retry the changes accumulated in the pApply->constraints buffer.
173267 */
173268 static int sessionRetryConstraints(
173269 sqlite3 *db,
173270 int bPatchset,
173271 const char *zTab,
173272 SessionApplyCtx *pApply,
173273 int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173274 void *pCtx /* First argument passed to xConflict */
173275 ){
173276 int rc = SQLITE_OK;
173277
173278 while( pApply->constraints.nBuf ){
173279 sqlite3_changeset_iter *pIter2 = 0;
173280 SessionBuffer cons = pApply->constraints;
173281 memset(&pApply->constraints, 0, sizeof(SessionBuffer));
173282
173283 rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
173284 if( rc==SQLITE_OK ){
173285 int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
173286 int rc2;
173287 pIter2->bPatchset = bPatchset;
173288 pIter2->zTab = (char*)zTab;
173289 pIter2->nCol = pApply->nCol;
173290 pIter2->abPK = pApply->abPK;
173291 sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
173292 pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
173293 if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
173294
173295 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
173296 rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
173297 }
173298
173299 rc2 = sqlite3changeset_finalize(pIter2);
173300 if( rc==SQLITE_OK ) rc = rc2;
173301 }
173302 assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
173303
173304 sqlite3_free(cons.aBuf);
173305 if( rc!=SQLITE_OK ) break;
173306 if( pApply->constraints.nBuf>=cons.nBuf ){
173307 /* No progress was made on the last round. */
173308 pApply->bDeferConstraints = 0;
173309 }
173310 }
173311
173312 return rc;
173313 }
173314
173315 /*
173316 ** Argument pIter is a changeset iterator that has been initialized, but
173317 ** not yet passed to sqlite3changeset_next(). This function applies the
173318 ** changeset to the main database attached to handle "db". The supplied
173319 ** conflict handler callback is invoked to resolve any conflicts encountered
173320 ** while applying the change.
173321 */
173322 static int sessionChangesetApply(
173323 sqlite3 *db, /* Apply change to "main" db of this handle */
173324 sqlite3_changeset_iter *pIter, /* Changeset to apply */
173325 int(*xFilter)(
173326 void *pCtx, /* Copy of sixth arg to _apply() */
173327 const char *zTab /* Table name */
173328 ),
173329 int(*xConflict)(
173330 void *pCtx, /* Copy of fifth arg to _apply() */
173331 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173332 sqlite3_changeset_iter *p /* Handle describing change and conflict */
173333 ),
173334 void *pCtx /* First argument passed to xConflict */
173335 ){
173336 int schemaMismatch = 0;
173337 int rc; /* Return code */
173338 const char *zTab = 0; /* Name of current table */
173339 int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
173340 SessionApplyCtx sApply; /* changeset_apply() context object */
173341 int bPatchset;
173342
173343 assert( xConflict!=0 );
173344
173345 pIter->in.bNoDiscard = 1;
173346 memset(&sApply, 0, sizeof(sApply));
173347 sqlite3_mutex_enter(sqlite3_db_mutex(db));
173348 rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
173349 if( rc==SQLITE_OK ){
173350 rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
173351 }
173352 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
173353 int nCol;
173354 int op;
173355 const char *zNew;
173356
173357 sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
173358
173359 if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
173360 u8 *abPK;
173361
173362 rc = sessionRetryConstraints(
173363 db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
173364 );
173365 if( rc!=SQLITE_OK ) break;
173366
173367 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173368 sqlite3_finalize(sApply.pDelete);
173369 sqlite3_finalize(sApply.pUpdate);
173370 sqlite3_finalize(sApply.pInsert);
173371 sqlite3_finalize(sApply.pSelect);
173372 memset(&sApply, 0, sizeof(sApply));
173373 sApply.db = db;
173374 sApply.bDeferConstraints = 1;
173375
173376 /* If an xFilter() callback was specified, invoke it now. If the
173377 ** xFilter callback returns zero, skip this table. If it returns
173378 ** non-zero, proceed. */
173379 schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
173380 if( schemaMismatch ){
173381 zTab = sqlite3_mprintf("%s", zNew);
173382 if( zTab==0 ){
173383 rc = SQLITE_NOMEM;
173384 break;
173385 }
173386 nTab = (int)strlen(zTab);
173387 sApply.azCol = (const char **)zTab;
173388 }else{
173389 sqlite3changeset_pk(pIter, &abPK, 0);
173390 rc = sessionTableInfo(
173391 db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
173392 );
173393 if( rc!=SQLITE_OK ) break;
173394
173395 if( sApply.nCol==0 ){
173396 schemaMismatch = 1;
173397 sqlite3_log(SQLITE_SCHEMA,
173398 "sqlite3changeset_apply(): no such table: %s", zTab
173399 );
173400 }
173401 else if( sApply.nCol!=nCol ){
173402 schemaMismatch = 1;
173403 sqlite3_log(SQLITE_SCHEMA,
173404 "sqlite3changeset_apply(): table %s has %d columns, expected %d",
173405 zTab, sApply.nCol, nCol
173406 );
173407 }
173408 else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
173409 schemaMismatch = 1;
173410 sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
173411 "primary key mismatch for table %s", zTab
173412 );
173413 }
173414 else if(
173415 (rc = sessionSelectRow(db, zTab, &sApply))
173416 || (rc = sessionUpdateRow(db, zTab, &sApply))
173417 || (rc = sessionDeleteRow(db, zTab, &sApply))
173418 || (rc = sessionInsertRow(db, zTab, &sApply))
173419 ){
173420 break;
173421 }
173422 nTab = sqlite3Strlen30(zTab);
173423 }
173424 }
173425
173426 /* If there is a schema mismatch on the current table, proceed to the
173427 ** next change. A log message has already been issued. */
173428 if( schemaMismatch ) continue;
173429
173430 rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
173431 }
173432
173433 bPatchset = pIter->bPatchset;
173434 if( rc==SQLITE_OK ){
173435 rc = sqlite3changeset_finalize(pIter);
173436 }else{
173437 sqlite3changeset_finalize(pIter);
173438 }
173439
173440 if( rc==SQLITE_OK ){
173441 rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
173442 }
173443
173444 if( rc==SQLITE_OK ){
173445 int nFk, notUsed;
173446 sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
173447 if( nFk!=0 ){
173448 int res = SQLITE_CHANGESET_ABORT;
173449 sqlite3_changeset_iter sIter;
173450 memset(&sIter, 0, sizeof(sIter));
173451 sIter.nCol = nFk;
173452 res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
173453 if( res!=SQLITE_CHANGESET_OMIT ){
173454 rc = SQLITE_CONSTRAINT;
173455 }
173456 }
173457 }
173458 sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
173459
173460 if( rc==SQLITE_OK ){
173461 rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173462 }else{
173463 sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
173464 sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173465 }
173466
173467 sqlite3_finalize(sApply.pInsert);
173468 sqlite3_finalize(sApply.pDelete);
173469 sqlite3_finalize(sApply.pUpdate);
173470 sqlite3_finalize(sApply.pSelect);
173471 sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173472 sqlite3_free((char*)sApply.constraints.aBuf);
173473 sqlite3_mutex_leave(sqlite3_db_mutex(db));
173474 return rc;
173475 }
173476
173477 /*
173478 ** Apply the changeset passed via pChangeset/nChangeset to the main database
173479 ** attached to handle "db". Invoke the supplied conflict handler callback
173480 ** to resolve any conflicts encountered while applying the change.
173481 */
173482 SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply(
173483 sqlite3 *db, /* Apply change to "main" db of this handle */
173484 int nChangeset, /* Size of changeset in bytes */
173485 void *pChangeset, /* Changeset blob */
173486 int(*xFilter)(
173487 void *pCtx, /* Copy of sixth arg to _apply() */
173488 const char *zTab /* Table name */
173489 ),
173490 int(*xConflict)(
173491 void *pCtx, /* Copy of fifth arg to _apply() */
173492 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173493 sqlite3_changeset_iter *p /* Handle describing change and conflict */
173494 ),
173495 void *pCtx /* First argument passed to xConflict */
173496 ){
173497 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173498 int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
173499 if( rc==SQLITE_OK ){
173500 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173501 }
173502 return rc;
173503 }
173504
173505 /*
173506 ** Apply the changeset passed via xInput/pIn to the main database
173507 ** attached to handle "db". Invoke the supplied conflict handler callback
173508 ** to resolve any conflicts encountered while applying the change.
173509 */
173510 SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply_strm(
173511 sqlite3 *db, /* Apply change to "main" db of this handle */
173512 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
173513 void *pIn, /* First arg for xInput */
173514 int(*xFilter)(
173515 void *pCtx, /* Copy of sixth arg to _apply() */
173516 const char *zTab /* Table name */
173517 ),
173518 int(*xConflict)(
173519 void *pCtx, /* Copy of sixth arg to _apply() */
173520 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173521 sqlite3_changeset_iter *p /* Handle describing change and conflict */
173522 ),
173523 void *pCtx /* First argument passed to xConflict */
173524 ){
173525 sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173526 int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173527 if( rc==SQLITE_OK ){
173528 rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173529 }
173530 return rc;
173531 }
173532
173533 /*
173534 ** sqlite3_changegroup handle.
173535 */
173536 struct sqlite3_changegroup {
173537 int rc; /* Error code */
173538 int bPatch; /* True to accumulate patchsets */
173539 SessionTable *pList; /* List of tables in current patch */
173540 };
173541
173542 /*
173543 ** This function is called to merge two changes to the same row together as
173544 ** part of an sqlite3changeset_concat() operation. A new change object is
173545 ** allocated and a pointer to it stored in *ppNew.
173546 */
173547 static int sessionChangeMerge(
173548 SessionTable *pTab, /* Table structure */
173549 int bPatchset, /* True for patchsets */
173550 SessionChange *pExist, /* Existing change */
173551 int op2, /* Second change operation */
173552 int bIndirect, /* True if second change is indirect */
173553 u8 *aRec, /* Second change record */
173554 int nRec, /* Number of bytes in aRec */
173555 SessionChange **ppNew /* OUT: Merged change */
173556 ){
173557 SessionChange *pNew = 0;
173558
173559 if( !pExist ){
173560 pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
173561 if( !pNew ){
173562 return SQLITE_NOMEM;
173563 }
173564 memset(pNew, 0, sizeof(SessionChange));
173565 pNew->op = op2;
173566 pNew->bIndirect = bIndirect;
173567 pNew->nRecord = nRec;
173568 pNew->aRecord = (u8*)&pNew[1];
173569 memcpy(pNew->aRecord, aRec, nRec);
173570 }else{
173571 int op1 = pExist->op;
173572
173573 /*
173574 ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
173575 ** op1=INSERT, op2=UPDATE -> INSERT.
173576 ** op1=INSERT, op2=DELETE -> (none)
173577 **
173578 ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
173579 ** op1=UPDATE, op2=UPDATE -> UPDATE.
173580 ** op1=UPDATE, op2=DELETE -> DELETE.
173581 **
173582 ** op1=DELETE, op2=INSERT -> UPDATE.
173583 ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
173584 ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
173585 */
173586 if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
173587 || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
173588 || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
173589 || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
173590 ){
173591 pNew = pExist;
173592 }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
173593 sqlite3_free(pExist);
173594 assert( pNew==0 );
173595 }else{
173596 u8 *aExist = pExist->aRecord;
173597 int nByte;
173598 u8 *aCsr;
173599
173600 /* Allocate a new SessionChange object. Ensure that the aRecord[]
173601 ** buffer of the new object is large enough to hold any record that
173602 ** may be generated by combining the input records. */
173603 nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
173604 pNew = (SessionChange *)sqlite3_malloc(nByte);
173605 if( !pNew ){
173606 sqlite3_free(pExist);
173607 return SQLITE_NOMEM;
173608 }
173609 memset(pNew, 0, sizeof(SessionChange));
173610 pNew->bIndirect = (bIndirect && pExist->bIndirect);
173611 aCsr = pNew->aRecord = (u8 *)&pNew[1];
173612
173613 if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
173614 u8 *a1 = aRec;
173615 assert( op2==SQLITE_UPDATE );
173616 pNew->op = SQLITE_INSERT;
173617 if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
173618 sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
173619 }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
173620 assert( op2==SQLITE_INSERT );
173621 pNew->op = SQLITE_UPDATE;
173622 if( bPatchset ){
173623 memcpy(aCsr, aRec, nRec);
173624 aCsr += nRec;
173625 }else{
173626 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
173627 sqlite3_free(pNew);
173628 pNew = 0;
173629 }
173630 }
173631 }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
173632 u8 *a1 = aExist;
173633 u8 *a2 = aRec;
173634 assert( op1==SQLITE_UPDATE );
173635 if( bPatchset==0 ){
173636 sessionSkipRecord(&a1, pTab->nCol);
173637 sessionSkipRecord(&a2, pTab->nCol);
173638 }
173639 pNew->op = SQLITE_UPDATE;
173640 if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
173641 sqlite3_free(pNew);
173642 pNew = 0;
173643 }
173644 }else{ /* UPDATE + DELETE */
173645 assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
173646 pNew->op = SQLITE_DELETE;
173647 if( bPatchset ){
173648 memcpy(aCsr, aRec, nRec);
173649 aCsr += nRec;
173650 }else{
173651 sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
173652 }
173653 }
173654
173655 if( pNew ){
173656 pNew->nRecord = (int)(aCsr - pNew->aRecord);
173657 }
173658 sqlite3_free(pExist);
173659 }
173660 }
173661
173662 *ppNew = pNew;
173663 return SQLITE_OK;
173664 }
173665
173666 /*
173667 ** Add all changes in the changeset traversed by the iterator passed as
173668 ** the first argument to the changegroup hash tables.
173669 */
173670 static int sessionChangesetToHash(
173671 sqlite3_changeset_iter *pIter, /* Iterator to read from */
173672 sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
173673 ){
173674 u8 *aRec;
173675 int nRec;
173676 int rc = SQLITE_OK;
173677 SessionTable *pTab = 0;
173678
173679
173680 while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
173681 const char *zNew;
173682 int nCol;
173683 int op;
173684 int iHash;
173685 int bIndirect;
173686 SessionChange *pChange;
173687 SessionChange *pExist = 0;
173688 SessionChange **pp;
173689
173690 if( pGrp->pList==0 ){
173691 pGrp->bPatch = pIter->bPatchset;
173692 }else if( pIter->bPatchset!=pGrp->bPatch ){
173693 rc = SQLITE_ERROR;
173694 break;
173695 }
173696
173697 sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
173698 if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
173699 /* Search the list for a matching table */
173700 int nNew = (int)strlen(zNew);
173701 u8 *abPK;
173702
173703 sqlite3changeset_pk(pIter, &abPK, 0);
173704 for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
173705 if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
173706 }
173707 if( !pTab ){
173708 SessionTable **ppTab;
173709
173710 pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
173711 if( !pTab ){
173712 rc = SQLITE_NOMEM;
173713 break;
173714 }
173715 memset(pTab, 0, sizeof(SessionTable));
173716 pTab->nCol = nCol;
173717 pTab->abPK = (u8*)&pTab[1];
173718 memcpy(pTab->abPK, abPK, nCol);
173719 pTab->zName = (char*)&pTab->abPK[nCol];
173720 memcpy(pTab->zName, zNew, nNew+1);
173721
173722 /* The new object must be linked on to the end of the list, not
173723 ** simply added to the start of it. This is to ensure that the
173724 ** tables within the output of sqlite3changegroup_output() are in
173725 ** the right order. */
173726 for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
173727 *ppTab = pTab;
173728 }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
173729 rc = SQLITE_SCHEMA;
173730 break;
173731 }
173732 }
173733
173734 if( sessionGrowHash(pIter->bPatchset, pTab) ){
173735 rc = SQLITE_NOMEM;
173736 break;
173737 }
173738 iHash = sessionChangeHash(
173739 pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
173740 );
173741
173742 /* Search for existing entry. If found, remove it from the hash table.
173743 ** Code below may link it back in.
173744 */
173745 for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
173746 int bPkOnly1 = 0;
173747 int bPkOnly2 = 0;
173748 if( pIter->bPatchset ){
173749 bPkOnly1 = (*pp)->op==SQLITE_DELETE;
173750 bPkOnly2 = op==SQLITE_DELETE;
173751 }
173752 if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
173753 pExist = *pp;
173754 *pp = (*pp)->pNext;
173755 pTab->nEntry--;
173756 break;
173757 }
173758 }
173759
173760 rc = sessionChangeMerge(pTab,
173761 pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
173762 );
173763 if( rc ) break;
173764 if( pChange ){
173765 pChange->pNext = pTab->apChange[iHash];
173766 pTab->apChange[iHash] = pChange;
173767 pTab->nEntry++;
173768 }
173769 }
173770
173771 if( rc==SQLITE_OK ) rc = pIter->rc;
173772 return rc;
173773 }
173774
173775 /*
173776 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
173777 ** added to the changegroup object passed as the first argument.
173778 **
173779 ** If xOutput is not NULL, then the changeset/patchset is returned to the
173780 ** user via one or more calls to xOutput, as with the other streaming
173781 ** interfaces.
173782 **
173783 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
173784 ** buffer containing the output changeset before this function returns. In
173785 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
173786 ** is the responsibility of the caller to free the output buffer using
173787 ** sqlite3_free() when it is no longer required.
173788 **
173789 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
173790 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
173791 ** are both set to 0 before returning.
173792 */
173793 static int sessionChangegroupOutput(
173794 sqlite3_changegroup *pGrp,
173795 int (*xOutput)(void *pOut, const void *pData, int nData),
173796 void *pOut,
173797 int *pnOut,
173798 void **ppOut
173799 ){
173800 int rc = SQLITE_OK;
173801 SessionBuffer buf = {0, 0, 0};
173802 SessionTable *pTab;
173803 assert( xOutput==0 || (ppOut==0 && pnOut==0) );
173804
173805 /* Create the serialized output changeset based on the contents of the
173806 ** hash tables attached to the SessionTable objects in list p->pList.
173807 */
173808 for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
173809 int i;
173810 if( pTab->nEntry==0 ) continue;
173811
173812 sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
173813 for(i=0; i<pTab->nChange; i++){
173814 SessionChange *p;
173815 for(p=pTab->apChange[i]; p; p=p->pNext){
173816 sessionAppendByte(&buf, p->op, &rc);
173817 sessionAppendByte(&buf, p->bIndirect, &rc);
173818 sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
173819 }
173820 }
173821
173822 if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173823 rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173824 buf.nBuf = 0;
173825 }
173826 }
173827
173828 if( rc==SQLITE_OK ){
173829 if( xOutput ){
173830 if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173831 }else{
173832 *ppOut = buf.aBuf;
173833 *pnOut = buf.nBuf;
173834 buf.aBuf = 0;
173835 }
173836 }
173837 sqlite3_free(buf.aBuf);
173838
173839 return rc;
173840 }
173841
173842 /*
173843 ** Allocate a new, empty, sqlite3_changegroup.
173844 */
173845 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_new(sqlite3_changegroup **pp){
173846 int rc = SQLITE_OK; /* Return code */
173847 sqlite3_changegroup *p; /* New object */
173848 p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
173849 if( p==0 ){
173850 rc = SQLITE_NOMEM;
173851 }else{
173852 memset(p, 0, sizeof(sqlite3_changegroup));
173853 }
173854 *pp = p;
173855 return rc;
173856 }
173857
173858 /*
173859 ** Add the changeset currently stored in buffer pData, size nData bytes,
173860 ** to changeset-group p.
173861 */
173862 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
173863 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173864 int rc; /* Return code */
173865
173866 rc = sqlite3changeset_start(&pIter, nData, pData);
173867 if( rc==SQLITE_OK ){
173868 rc = sessionChangesetToHash(pIter, pGrp);
173869 }
173870 sqlite3changeset_finalize(pIter);
173871 return rc;
173872 }
173873
173874 /*
173875 ** Obtain a buffer containing a changeset representing the concatenation
173876 ** of all changesets added to the group so far.
173877 */
173878 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output(
173879 sqlite3_changegroup *pGrp,
173880 int *pnData,
173881 void **ppData
173882 ){
173883 return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
173884 }
173885
173886 /*
173887 ** Streaming versions of changegroup_add().
173888 */
173889 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add_strm(
173890 sqlite3_changegroup *pGrp,
173891 int (*xInput)(void *pIn, void *pData, int *pnData),
173892 void *pIn
173893 ){
173894 sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173895 int rc; /* Return code */
173896
173897 rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173898 if( rc==SQLITE_OK ){
173899 rc = sessionChangesetToHash(pIter, pGrp);
173900 }
173901 sqlite3changeset_finalize(pIter);
173902 return rc;
173903 }
173904
173905 /*
173906 ** Streaming versions of changegroup_output().
173907 */
173908 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output_strm(
173909 sqlite3_changegroup *pGrp,
173910 int (*xOutput)(void *pOut, const void *pData, int nData),
173911 void *pOut
173912 ){
173913 return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
173914 }
173915
173916 /*
173917 ** Delete a changegroup object.
173918 */
173919 SQLITE_API void SQLITE_STDCALL sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
173920 if( pGrp ){
173921 sessionDeleteTable(pGrp->pList);
173922 sqlite3_free(pGrp);
173923 }
173924 }
173925
173926 /*
173927 ** Combine two changesets together.
173928 */
173929 SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat(
173930 int nLeft, /* Number of bytes in lhs input */
173931 void *pLeft, /* Lhs input changeset */
173932 int nRight /* Number of bytes in rhs input */,
173933 void *pRight, /* Rhs input changeset */
173934 int *pnOut, /* OUT: Number of bytes in output changeset */
173935 void **ppOut /* OUT: changeset (left <concat> right) */
173936 ){
173937 sqlite3_changegroup *pGrp;
173938 int rc;
173939
173940 rc = sqlite3changegroup_new(&pGrp);
173941 if( rc==SQLITE_OK ){
173942 rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
173943 }
173944 if( rc==SQLITE_OK ){
173945 rc = sqlite3changegroup_add(pGrp, nRight, pRight);
173946 }
173947 if( rc==SQLITE_OK ){
173948 rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
173949 }
173950 sqlite3changegroup_delete(pGrp);
173951
173952 return rc;
173953 }
173954
173955 /*
173956 ** Streaming version of sqlite3changeset_concat().
173957 */
173958 SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat_strm(
173959 int (*xInputA)(void *pIn, void *pData, int *pnData),
173960 void *pInA,
173961 int (*xInputB)(void *pIn, void *pData, int *pnData),
173962 void *pInB,
173963 int (*xOutput)(void *pOut, const void *pData, int nData),
173964 void *pOut
173965 ){
173966 sqlite3_changegroup *pGrp;
173967 int rc;
173968
173969 rc = sqlite3changegroup_new(&pGrp);
173970 if( rc==SQLITE_OK ){
173971 rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
173972 }
173973 if( rc==SQLITE_OK ){
173974 rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
173975 }
173976 if( rc==SQLITE_OK ){
173977 rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
173978 }
173979 sqlite3changegroup_delete(pGrp);
173980
173981 return rc;
173982 }
173983
173984 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
173985
173986 /************** End of sqlite3session.c **************************************/
173987 /************** Begin file json1.c *******************************************/
173988 /*
173989 ** 2015-08-12
173990 **
173991 ** The author disclaims copyright to this source code. In place of
@@ -168809,15 +176334,17 @@
176334 ** of the current query. Specifically, a query equivalent to:
176335 **
176336 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
176337 **
176338 ** with $p set to a phrase equivalent to the phrase iPhrase of the
176339 ** current query is executed. Any column filter that applies to
176340 ** phrase iPhrase of the current query is included in $p. For each
176341 ** row visited, the callback function passed as the fourth argument
176342 ** is invoked. The context and API objects passed to the callback
176343 ** function may be used to access the properties of each matched row.
176344 ** Invoking Api.xUserData() returns a copy of the pointer passed as
176345 ** the third argument to pUserData.
176346 **
176347 ** If the callback function returns any value other than SQLITE_OK, the
176348 ** query is abandoned and the xQueryPhrase function returns immediately.
176349 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
176350 ** Otherwise, the error code is propagated upwards.
@@ -174848,10 +182375,21 @@
182375 }
182376 if( rc==SQLITE_OK ){
182377 pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
182378 sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
182379 }
182380 if( rc==SQLITE_OK ){
182381 Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
182382 if( pColsetOrig ){
182383 int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
182384 Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
182385 if( pColset ){
182386 memcpy(pColset, pColsetOrig, nByte);
182387 }
182388 pNew->pRoot->pNear->pColset = pColset;
182389 }
182390 }
182391
182392 for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
182393 int tflags = 0;
182394 Fts5ExprTerm *p;
182395 for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
@@ -176196,15 +183734,15 @@
183734 assert( iCol>=p->iCol );
183735 if( iCol!=p->iCol ){
183736 if( pHash->eDetail==FTS5_DETAIL_FULL ){
183737 pPtr[p->nData++] = 0x01;
183738 p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
183739 p->iCol = (i16)iCol;
183740 p->iPos = 0;
183741 }else{
183742 bNew = 1;
183743 p->iCol = (i16)(iPos = iCol);
183744 }
183745 }
183746
183747 /* Append the new position offset, if necessary */
183748 if( bNew ){
@@ -179623,11 +187161,11 @@
187161 while( *aiCol<iPrev ){
187162 aiCol++;
187163 if( aiCol==aiColEnd ) goto setoutputs_col_out;
187164 }
187165 if( *aiCol==iPrev ){
187166 *aOut++ = (u8)((iPrev - iPrevOut) + 2);
187167 iPrevOut = iPrev;
187168 }
187169 }
187170
187171 setoutputs_col_out:
@@ -185456,11 +192994,11 @@
192994 int nArg, /* Number of args */
192995 sqlite3_value **apUnused /* Function arguments */
192996 ){
192997 assert( nArg==0 );
192998 UNUSED_PARAM2(nArg, apUnused);
192999 sqlite3_result_text(pCtx, "fts5: 2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2", -1, SQLITE_TRANSIENT);
193000 }
193001
193002 static int fts5Init(sqlite3 *db){
193003 static const sqlite3_module fts5Mod = {
193004 /* iVersion */ 2,
193005
+1478 -23
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -109,13 +109,13 @@
109109
**
110110
** See also: [sqlite3_libversion()],
111111
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
112112
** [sqlite_version()] and [sqlite_source_id()].
113113
*/
114
-#define SQLITE_VERSION "3.12.1"
115
-#define SQLITE_VERSION_NUMBER 3012001
116
-#define SQLITE_SOURCE_ID "2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d"
114
+#define SQLITE_VERSION "3.13.0"
115
+#define SQLITE_VERSION_NUMBER 3013000
116
+#define SQLITE_SOURCE_ID "2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2"
117117
118118
/*
119119
** CAPI3REF: Run-Time Library Version Numbers
120120
** KEYWORDS: sqlite3_version, sqlite3_sourceid
121121
**
@@ -1930,16 +1930,34 @@
19301930
** The second parameter is a pointer to an integer into which
19311931
** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
19321932
** following this call. The second parameter may be a NULL pointer, in
19331933
** which case the new setting is not reported back. </dd>
19341934
**
1935
+** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
1936
+** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
1937
+** interface independently of the [load_extension()] SQL function.
1938
+** The [sqlite3_enable_load_extension()] API enables or disables both the
1939
+** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
1940
+** There should be two additional arguments.
1941
+** When the first argument to this interface is 1, then only the C-API is
1942
+** enabled and the SQL function remains disabled. If the first argment to
1943
+** this interface is 0, then both the C-API and the SQL function are disabled.
1944
+** If the first argument is -1, then no changes are made to state of either the
1945
+** C-API or the SQL function.
1946
+** The second parameter is a pointer to an integer into which
1947
+** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
1948
+** is disabled or enabled following this call. The second parameter may
1949
+** be a NULL pointer, in which case the new setting is not reported back.
1950
+** </dd>
1951
+**
19351952
** </dl>
19361953
*/
19371954
#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
19381955
#define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
19391956
#define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
19401957
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
1958
+#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
19411959
19421960
19431961
/*
19441962
** CAPI3REF: Enable Or Disable Extended Result Codes
19451963
** METHOD: sqlite3
@@ -5185,11 +5203,11 @@
51855203
** METHOD: sqlite3
51865204
**
51875205
** ^The sqlite3_update_hook() interface registers a callback function
51885206
** with the [database connection] identified by the first argument
51895207
** to be invoked whenever a row is updated, inserted or deleted in
5190
-** a rowid table.
5208
+** a [rowid table].
51915209
** ^Any callback set by a previous call to this function
51925210
** for the same database connection is overridden.
51935211
**
51945212
** ^The second argument is a pointer to the function to invoke when a
51955213
** row is updated, inserted or deleted in a rowid table.
@@ -5224,12 +5242,12 @@
52245242
** ^The sqlite3_update_hook(D,C,P) function
52255243
** returns the P argument from the previous call
52265244
** on the same [database connection] D, or NULL for
52275245
** the first call on D.
52285246
**
5229
-** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5230
-** interfaces.
5247
+** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5248
+** and [sqlite3_preupdate_hook()] interfaces.
52315249
*/
52325250
SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
52335251
sqlite3*,
52345252
void(*)(void *,int ,char const *,char const *,sqlite3_int64),
52355253
void*
@@ -5472,12 +5490,21 @@
54725490
** fill *pzErrMsg with error message text stored in memory
54735491
** obtained from [sqlite3_malloc()]. The calling function
54745492
** should free this memory by calling [sqlite3_free()].
54755493
**
54765494
** ^Extension loading must be enabled using
5477
-** [sqlite3_enable_load_extension()] prior to calling this API,
5495
+** [sqlite3_enable_load_extension()] or
5496
+** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5497
+** prior to calling this API,
54785498
** otherwise an error will be returned.
5499
+**
5500
+** <b>Security warning:</b> It is recommended that the
5501
+** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5502
+** interface. The use of the [sqlite3_enable_load_extension()] interface
5503
+** should be avoided. This will keep the SQL function [load_extension()]
5504
+** disabled and prevent SQL injections from giving attackers
5505
+** access to extension loading capabilities.
54795506
**
54805507
** See also the [load_extension() SQL function].
54815508
*/
54825509
SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
54835510
sqlite3 *db, /* Load the extension into this database connection */
@@ -5497,10 +5524,21 @@
54975524
**
54985525
** ^Extension loading is off by default.
54995526
** ^Call the sqlite3_enable_load_extension() routine with onoff==1
55005527
** to turn extension loading on and call it with onoff==0 to turn
55015528
** it back off again.
5529
+**
5530
+** ^This interface enables or disables both the C-API
5531
+** [sqlite3_load_extension()] and the SQL function [load_extension()].
5532
+** Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5533
+** to enable or disable only the C-API.
5534
+**
5535
+** <b>Security warning:</b> It is recommended that extension loading
5536
+** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5537
+** rather than this interface, so the [load_extension()] SQL function
5538
+** remains disabled. This will prevent SQL injections from giving attackers
5539
+** access to extension loading capabilities.
55025540
*/
55035541
SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
55045542
55055543
/*
55065544
** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7135,11 +7173,11 @@
71357173
** and database name of the source database, respectively.
71367174
** ^The source and destination [database connections] (parameters S and D)
71377175
** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
71387176
** an error.
71397177
**
7140
-** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7178
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
71417179
** there is already a read or read-write transaction open on the
71427180
** destination database.
71437181
**
71447182
** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
71457183
** returned and an error code and error message are stored in the
@@ -7913,15 +7951,111 @@
79137951
** ^This function does not set the database handle error code or message
79147952
** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
79157953
*/
79167954
SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
79177955
7956
+/*
7957
+** CAPI3REF: The pre-update hook.
7958
+**
7959
+** ^These interfaces are only available if SQLite is compiled using the
7960
+** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
7961
+**
7962
+** ^The [sqlite3_preupdate_hook()] interface registers a callback function
7963
+** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
7964
+** on a [rowid table].
7965
+** ^At most one preupdate hook may be registered at a time on a single
7966
+** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
7967
+** the previous setting.
7968
+** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
7969
+** with a NULL pointer as the second parameter.
7970
+** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
7971
+** the first parameter to callbacks.
7972
+**
7973
+** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
7974
+** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
7975
+** tables.
7976
+**
7977
+** ^The second parameter to the preupdate callback is a pointer to
7978
+** the [database connection] that registered the preupdate hook.
7979
+** ^The third parameter to the preupdate callback is one of the constants
7980
+** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to indentify the
7981
+** kind of update operation that is about to occur.
7982
+** ^(The fourth parameter to the preupdate callback is the name of the
7983
+** database within the database connection that is being modified. This
7984
+** will be "main" for the main database or "temp" for TEMP tables or
7985
+** the name given after the AS keyword in the [ATTACH] statement for attached
7986
+** databases.)^
7987
+** ^The fifth parameter to the preupdate callback is the name of the
7988
+** table that is being modified.
7989
+** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
7990
+** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
7991
+** undefined for SQLITE_INSERT changes.
7992
+** ^The seventh parameter to the preupdate callback is the final [rowid] of
7993
+** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
7994
+** undefined for SQLITE_DELETE changes.
7995
+**
7996
+** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
7997
+** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
7998
+** provide additional information about a preupdate event. These routines
7999
+** may only be called from within a preupdate callback. Invoking any of
8000
+** these routines from outside of a preupdate callback or with a
8001
+** [database connection] pointer that is different from the one supplied
8002
+** to the preupdate callback results in undefined and probably undesirable
8003
+** behavior.
8004
+**
8005
+** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8006
+** in the row that is being inserted, updated, or deleted.
8007
+**
8008
+** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8009
+** a [protected sqlite3_value] that contains the value of the Nth column of
8010
+** the table row before it is updated. The N parameter must be between 0
8011
+** and one less than the number of columns or the behavior will be
8012
+** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8013
+** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8014
+** behavior is undefined. The [sqlite3_value] that P points to
8015
+** will be destroyed when the preupdate callback returns.
8016
+**
8017
+** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8018
+** a [protected sqlite3_value] that contains the value of the Nth column of
8019
+** the table row after it is updated. The N parameter must be between 0
8020
+** and one less than the number of columns or the behavior will be
8021
+** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8022
+** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8023
+** behavior is undefined. The [sqlite3_value] that P points to
8024
+** will be destroyed when the preupdate callback returns.
8025
+**
8026
+** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8027
+** callback was invoked as a result of a direct insert, update, or delete
8028
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
8029
+** triggers; or 2 for changes resulting from triggers called by top-level
8030
+** triggers; and so forth.
8031
+**
8032
+** See also: [sqlite3_update_hook()]
8033
+*/
8034
+SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8035
+ sqlite3 *db,
8036
+ void(*xPreUpdate)(
8037
+ void *pCtx, /* Copy of third arg to preupdate_hook() */
8038
+ sqlite3 *db, /* Database handle */
8039
+ int op, /* SQLITE_UPDATE, DELETE or INSERT */
8040
+ char const *zDb, /* Database name */
8041
+ char const *zName, /* Table name */
8042
+ sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8043
+ sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8044
+ ),
8045
+ void*
8046
+);
8047
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8048
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8049
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8050
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8051
+
79188052
/*
79198053
** CAPI3REF: Low-level system error code
79208054
**
79218055
** ^Attempt to return the underlying operating system error code or error
7922
-** number that caused the most reason I/O error or failure to open a file.
8056
+** number that caused the most recent I/O error or failure to open a file.
79238057
** The return value is OS-dependent. For example, on unix systems, after
79248058
** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
79258059
** called to get back the underlying "errno" that caused the problem, such
79268060
** as ENOSPC, EAUTH, EISDIR, and so forth.
79278061
*/
@@ -7983,24 +8117,33 @@
79838117
79848118
/*
79858119
** CAPI3REF: Start a read transaction on an historical snapshot
79868120
** EXPERIMENTAL
79878121
**
7988
-** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
7989
-** read transaction that is currently open on schema S of
7990
-** [database connection] D so that it refers to historical [snapshot] P.
8122
+** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8123
+** read transaction for schema S of
8124
+** [database connection] D such that the read transaction
8125
+** refers to historical [snapshot] P, rather than the most
8126
+** recent change to the database.
79918127
** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
79928128
** or an appropriate [error code] if it fails.
79938129
**
79948130
** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
7995
-** the first operation, apart from other sqlite3_snapshot_open() calls,
7996
-** following the [BEGIN] that starts a new read transaction.
7997
-** ^A [snapshot] will fail to open if it has been overwritten by a
8131
+** the first operation following the [BEGIN] that takes the schema S
8132
+** out of [autocommit mode].
8133
+** ^In other words, schema S must not currently be in
8134
+** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8135
+** database connection D must be out of [autocommit mode].
8136
+** ^A [snapshot] will fail to open if it has been overwritten by a
79988137
** [checkpoint].
7999
-** ^A [snapshot] will fail to open if the database connection D has not
8000
-** previously completed at least one read operation against the database
8001
-** file. (Hint: Run "[PRAGMA application_id]" against a newly opened
8138
+** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8139
+** database connection D does not know that the database file for
8140
+** schema S is in [WAL mode]. A database connection might not know
8141
+** that the database file is in [WAL mode] if there has been no prior
8142
+** I/O on that database connection, or if the database entered [WAL mode]
8143
+** after the most recent I/O on the database connection.)^
8144
+** (Hint: Run "[PRAGMA application_id]" against a newly opened
80028145
** database connection in order to make it ready to use snapshots.)
80038146
**
80048147
** The [sqlite3_snapshot_open()] interface is only available when the
80058148
** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
80068149
*/
@@ -8021,10 +8164,37 @@
80218164
** The [sqlite3_snapshot_free()] interface is only available when the
80228165
** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
80238166
*/
80248167
SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
80258168
8169
+/*
8170
+** CAPI3REF: Compare the ages of two snapshot handles.
8171
+** EXPERIMENTAL
8172
+**
8173
+** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8174
+** of two valid snapshot handles.
8175
+**
8176
+** If the two snapshot handles are not associated with the same database
8177
+** file, the result of the comparison is undefined.
8178
+**
8179
+** Additionally, the result of the comparison is only valid if both of the
8180
+** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8181
+** last time the wal file was deleted. The wal file is deleted when the
8182
+** database is changed back to rollback mode or when the number of database
8183
+** clients drops to zero. If either snapshot handle was obtained before the
8184
+** wal file was last deleted, the value returned by this function
8185
+** is undefined.
8186
+**
8187
+** Otherwise, this API returns a negative value if P1 refers to an older
8188
+** snapshot than P2, zero if the two handles refer to the same database
8189
+** snapshot, and a positive value if P1 is a newer snapshot than P2.
8190
+*/
8191
+SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8192
+ sqlite3_snapshot *p1,
8193
+ sqlite3_snapshot *p2
8194
+);
8195
+
80268196
/*
80278197
** Undo the hack that converts floating point types to integer for
80288198
** builds on processors without floating point support.
80298199
*/
80308200
#ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8034,10 +8204,11 @@
80348204
#ifdef __cplusplus
80358205
} /* End of the 'extern "C"' block */
80368206
#endif
80378207
#endif /* _SQLITE3_H_ */
80388208
8209
+/******** Begin file sqlite3rtree.h *********/
80398210
/*
80408211
** 2010 August 30
80418212
**
80428213
** The author disclaims copyright to this source code. In place of
80438214
** a legal notice, here is a blessing:
@@ -8151,10 +8322,1291 @@
81518322
} /* end of the 'extern "C"' block */
81528323
#endif
81538324
81548325
#endif /* ifndef _SQLITE3RTREE_H_ */
81558326
8327
+/******** End of sqlite3rtree.h *********/
8328
+/******** Begin file sqlite3session.h *********/
8329
+
8330
+#if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8331
+#define __SQLITESESSION_H_ 1
8332
+
8333
+/*
8334
+** Make sure we can call this stuff from C++.
8335
+*/
8336
+#ifdef __cplusplus
8337
+extern "C" {
8338
+#endif
8339
+
8340
+
8341
+/*
8342
+** CAPI3REF: Session Object Handle
8343
+*/
8344
+typedef struct sqlite3_session sqlite3_session;
8345
+
8346
+/*
8347
+** CAPI3REF: Changeset Iterator Handle
8348
+*/
8349
+typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8350
+
8351
+/*
8352
+** CAPI3REF: Create A New Session Object
8353
+**
8354
+** Create a new session object attached to database handle db. If successful,
8355
+** a pointer to the new object is written to *ppSession and SQLITE_OK is
8356
+** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8357
+** error code (e.g. SQLITE_NOMEM) is returned.
8358
+**
8359
+** It is possible to create multiple session objects attached to a single
8360
+** database handle.
8361
+**
8362
+** Session objects created using this function should be deleted using the
8363
+** [sqlite3session_delete()] function before the database handle that they
8364
+** are attached to is itself closed. If the database handle is closed before
8365
+** the session object is deleted, then the results of calling any session
8366
+** module function, including [sqlite3session_delete()] on the session object
8367
+** are undefined.
8368
+**
8369
+** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8370
+** is not possible for an application to register a pre-update hook on a
8371
+** database handle that has one or more session objects attached. Nor is
8372
+** it possible to create a session object attached to a database handle for
8373
+** which a pre-update hook is already defined. The results of attempting
8374
+** either of these things are undefined.
8375
+**
8376
+** The session object will be used to create changesets for tables in
8377
+** database zDb, where zDb is either "main", or "temp", or the name of an
8378
+** attached database. It is not an error if database zDb is not attached
8379
+** to the database when the session object is created.
8380
+*/
8381
+int sqlite3session_create(
8382
+ sqlite3 *db, /* Database handle */
8383
+ const char *zDb, /* Name of db (e.g. "main") */
8384
+ sqlite3_session **ppSession /* OUT: New session object */
8385
+);
8386
+
8387
+/*
8388
+** CAPI3REF: Delete A Session Object
8389
+**
8390
+** Delete a session object previously allocated using
8391
+** [sqlite3session_create()]. Once a session object has been deleted, the
8392
+** results of attempting to use pSession with any other session module
8393
+** function are undefined.
8394
+**
8395
+** Session objects must be deleted before the database handle to which they
8396
+** are attached is closed. Refer to the documentation for
8397
+** [sqlite3session_create()] for details.
8398
+*/
8399
+void sqlite3session_delete(sqlite3_session *pSession);
8400
+
8401
+
8402
+/*
8403
+** CAPI3REF: Enable Or Disable A Session Object
8404
+**
8405
+** Enable or disable the recording of changes by a session object. When
8406
+** enabled, a session object records changes made to the database. When
8407
+** disabled - it does not. A newly created session object is enabled.
8408
+** Refer to the documentation for [sqlite3session_changeset()] for further
8409
+** details regarding how enabling and disabling a session object affects
8410
+** the eventual changesets.
8411
+**
8412
+** Passing zero to this function disables the session. Passing a value
8413
+** greater than zero enables it. Passing a value less than zero is a
8414
+** no-op, and may be used to query the current state of the session.
8415
+**
8416
+** The return value indicates the final state of the session object: 0 if
8417
+** the session is disabled, or 1 if it is enabled.
8418
+*/
8419
+int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8420
+
8421
+/*
8422
+** CAPI3REF: Set Or Clear the Indirect Change Flag
8423
+**
8424
+** Each change recorded by a session object is marked as either direct or
8425
+** indirect. A change is marked as indirect if either:
8426
+**
8427
+** <ul>
8428
+** <li> The session object "indirect" flag is set when the change is
8429
+** made, or
8430
+** <li> The change is made by an SQL trigger or foreign key action
8431
+** instead of directly as a result of a users SQL statement.
8432
+** </ul>
8433
+**
8434
+** If a single row is affected by more than one operation within a session,
8435
+** then the change is considered indirect if all operations meet the criteria
8436
+** for an indirect change above, or direct otherwise.
8437
+**
8438
+** This function is used to set, clear or query the session object indirect
8439
+** flag. If the second argument passed to this function is zero, then the
8440
+** indirect flag is cleared. If it is greater than zero, the indirect flag
8441
+** is set. Passing a value less than zero does not modify the current value
8442
+** of the indirect flag, and may be used to query the current state of the
8443
+** indirect flag for the specified session object.
8444
+**
8445
+** The return value indicates the final state of the indirect flag: 0 if
8446
+** it is clear, or 1 if it is set.
8447
+*/
8448
+int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8449
+
8450
+/*
8451
+** CAPI3REF: Attach A Table To A Session Object
8452
+**
8453
+** If argument zTab is not NULL, then it is the name of a table to attach
8454
+** to the session object passed as the first argument. All subsequent changes
8455
+** made to the table while the session object is enabled will be recorded. See
8456
+** documentation for [sqlite3session_changeset()] for further details.
8457
+**
8458
+** Or, if argument zTab is NULL, then changes are recorded for all tables
8459
+** in the database. If additional tables are added to the database (by
8460
+** executing "CREATE TABLE" statements) after this call is made, changes for
8461
+** the new tables are also recorded.
8462
+**
8463
+** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8464
+** defined as part of their CREATE TABLE statement. It does not matter if the
8465
+** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8466
+** KEY may consist of a single column, or may be a composite key.
8467
+**
8468
+** It is not an error if the named table does not exist in the database. Nor
8469
+** is it an error if the named table does not have a PRIMARY KEY. However,
8470
+** no changes will be recorded in either of these scenarios.
8471
+**
8472
+** Changes are not recorded for individual rows that have NULL values stored
8473
+** in one or more of their PRIMARY KEY columns.
8474
+**
8475
+** SQLITE_OK is returned if the call completes without error. Or, if an error
8476
+** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8477
+*/
8478
+int sqlite3session_attach(
8479
+ sqlite3_session *pSession, /* Session object */
8480
+ const char *zTab /* Table name */
8481
+);
8482
+
8483
+/*
8484
+** CAPI3REF: Set a table filter on a Session Object.
8485
+**
8486
+** The second argument (xFilter) is the "filter callback". For changes to rows
8487
+** in tables that are not attached to the Session oject, the filter is called
8488
+** to determine whether changes to the table's rows should be tracked or not.
8489
+** If xFilter returns 0, changes is not tracked. Note that once a table is
8490
+** attached, xFilter will not be called again.
8491
+*/
8492
+void sqlite3session_table_filter(
8493
+ sqlite3_session *pSession, /* Session object */
8494
+ int(*xFilter)(
8495
+ void *pCtx, /* Copy of third arg to _filter_table() */
8496
+ const char *zTab /* Table name */
8497
+ ),
8498
+ void *pCtx /* First argument passed to xFilter */
8499
+);
8500
+
8501
+/*
8502
+** CAPI3REF: Generate A Changeset From A Session Object
8503
+**
8504
+** Obtain a changeset containing changes to the tables attached to the
8505
+** session object passed as the first argument. If successful,
8506
+** set *ppChangeset to point to a buffer containing the changeset
8507
+** and *pnChangeset to the size of the changeset in bytes before returning
8508
+** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8509
+** zero and return an SQLite error code.
8510
+**
8511
+** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8512
+** each representing a change to a single row of an attached table. An INSERT
8513
+** change contains the values of each field of a new database row. A DELETE
8514
+** contains the original values of each field of a deleted database row. An
8515
+** UPDATE change contains the original values of each field of an updated
8516
+** database row along with the updated values for each updated non-primary-key
8517
+** column. It is not possible for an UPDATE change to represent a change that
8518
+** modifies the values of primary key columns. If such a change is made, it
8519
+** is represented in a changeset as a DELETE followed by an INSERT.
8520
+**
8521
+** Changes are not recorded for rows that have NULL values stored in one or
8522
+** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8523
+** no corresponding change is present in the changesets returned by this
8524
+** function. If an existing row with one or more NULL values stored in
8525
+** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8526
+** only an INSERT is appears in the changeset. Similarly, if an existing row
8527
+** with non-NULL PRIMARY KEY values is updated so that one or more of its
8528
+** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8529
+** DELETE change only.
8530
+**
8531
+** The contents of a changeset may be traversed using an iterator created
8532
+** using the [sqlite3changeset_start()] API. A changeset may be applied to
8533
+** a database with a compatible schema using the [sqlite3changeset_apply()]
8534
+** API.
8535
+**
8536
+** Within a changeset generated by this function, all changes related to a
8537
+** single table are grouped together. In other words, when iterating through
8538
+** a changeset or when applying a changeset to a database, all changes related
8539
+** to a single table are processed before moving on to the next table. Tables
8540
+** are sorted in the same order in which they were attached (or auto-attached)
8541
+** to the sqlite3_session object. The order in which the changes related to
8542
+** a single table are stored is undefined.
8543
+**
8544
+** Following a successful call to this function, it is the responsibility of
8545
+** the caller to eventually free the buffer that *ppChangeset points to using
8546
+** [sqlite3_free()].
8547
+**
8548
+** <h3>Changeset Generation</h3>
8549
+**
8550
+** Once a table has been attached to a session object, the session object
8551
+** records the primary key values of all new rows inserted into the table.
8552
+** It also records the original primary key and other column values of any
8553
+** deleted or updated rows. For each unique primary key value, data is only
8554
+** recorded once - the first time a row with said primary key is inserted,
8555
+** updated or deleted in the lifetime of the session.
8556
+**
8557
+** There is one exception to the previous paragraph: when a row is inserted,
8558
+** updated or deleted, if one or more of its primary key columns contain a
8559
+** NULL value, no record of the change is made.
8560
+**
8561
+** The session object therefore accumulates two types of records - those
8562
+** that consist of primary key values only (created when the user inserts
8563
+** a new record) and those that consist of the primary key values and the
8564
+** original values of other table columns (created when the users deletes
8565
+** or updates a record).
8566
+**
8567
+** When this function is called, the requested changeset is created using
8568
+** both the accumulated records and the current contents of the database
8569
+** file. Specifically:
8570
+**
8571
+** <ul>
8572
+** <li> For each record generated by an insert, the database is queried
8573
+** for a row with a matching primary key. If one is found, an INSERT
8574
+** change is added to the changeset. If no such row is found, no change
8575
+** is added to the changeset.
8576
+**
8577
+** <li> For each record generated by an update or delete, the database is
8578
+** queried for a row with a matching primary key. If such a row is
8579
+** found and one or more of the non-primary key fields have been
8580
+** modified from their original values, an UPDATE change is added to
8581
+** the changeset. Or, if no such row is found in the table, a DELETE
8582
+** change is added to the changeset. If there is a row with a matching
8583
+** primary key in the database, but all fields contain their original
8584
+** values, no change is added to the changeset.
8585
+** </ul>
8586
+**
8587
+** This means, amongst other things, that if a row is inserted and then later
8588
+** deleted while a session object is active, neither the insert nor the delete
8589
+** will be present in the changeset. Or if a row is deleted and then later a
8590
+** row with the same primary key values inserted while a session object is
8591
+** active, the resulting changeset will contain an UPDATE change instead of
8592
+** a DELETE and an INSERT.
8593
+**
8594
+** When a session object is disabled (see the [sqlite3session_enable()] API),
8595
+** it does not accumulate records when rows are inserted, updated or deleted.
8596
+** This may appear to have some counter-intuitive effects if a single row
8597
+** is written to more than once during a session. For example, if a row
8598
+** is inserted while a session object is enabled, then later deleted while
8599
+** the same session object is disabled, no INSERT record will appear in the
8600
+** changeset, even though the delete took place while the session was disabled.
8601
+** Or, if one field of a row is updated while a session is disabled, and
8602
+** another field of the same row is updated while the session is enabled, the
8603
+** resulting changeset will contain an UPDATE change that updates both fields.
8604
+*/
8605
+int sqlite3session_changeset(
8606
+ sqlite3_session *pSession, /* Session object */
8607
+ int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
8608
+ void **ppChangeset /* OUT: Buffer containing changeset */
8609
+);
8610
+
8611
+/*
8612
+** CAPI3REF: Load The Difference Between Tables Into A Session
8613
+**
8614
+** If it is not already attached to the session object passed as the first
8615
+** argument, this function attaches table zTbl in the same manner as the
8616
+** [sqlite3session_attach()] function. If zTbl does not exist, or if it
8617
+** does not have a primary key, this function is a no-op (but does not return
8618
+** an error).
8619
+**
8620
+** Argument zFromDb must be the name of a database ("main", "temp" etc.)
8621
+** attached to the same database handle as the session object that contains
8622
+** a table compatible with the table attached to the session by this function.
8623
+** A table is considered compatible if it:
8624
+**
8625
+** <ul>
8626
+** <li> Has the same name,
8627
+** <li> Has the same set of columns declared in the same order, and
8628
+** <li> Has the same PRIMARY KEY definition.
8629
+** </ul>
8630
+**
8631
+** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
8632
+** are compatible but do not have any PRIMARY KEY columns, it is not an error
8633
+** but no changes are added to the session object. As with other session
8634
+** APIs, tables without PRIMARY KEYs are simply ignored.
8635
+**
8636
+** This function adds a set of changes to the session object that could be
8637
+** used to update the table in database zFrom (call this the "from-table")
8638
+** so that its content is the same as the table attached to the session
8639
+** object (call this the "to-table"). Specifically:
8640
+**
8641
+** <ul>
8642
+** <li> For each row (primary key) that exists in the to-table but not in
8643
+** the from-table, an INSERT record is added to the session object.
8644
+**
8645
+** <li> For each row (primary key) that exists in the to-table but not in
8646
+** the from-table, a DELETE record is added to the session object.
8647
+**
8648
+** <li> For each row (primary key) that exists in both tables, but features
8649
+** different in each, an UPDATE record is added to the session.
8650
+** </ul>
8651
+**
8652
+** To clarify, if this function is called and then a changeset constructed
8653
+** using [sqlite3session_changeset()], then after applying that changeset to
8654
+** database zFrom the contents of the two compatible tables would be
8655
+** identical.
8656
+**
8657
+** It an error if database zFrom does not exist or does not contain the
8658
+** required compatible table.
8659
+**
8660
+** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
8661
+** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
8662
+** may be set to point to a buffer containing an English language error
8663
+** message. It is the responsibility of the caller to free this buffer using
8664
+** sqlite3_free().
8665
+*/
8666
+int sqlite3session_diff(
8667
+ sqlite3_session *pSession,
8668
+ const char *zFromDb,
8669
+ const char *zTbl,
8670
+ char **pzErrMsg
8671
+);
8672
+
8673
+
8674
+/*
8675
+** CAPI3REF: Generate A Patchset From A Session Object
8676
+**
8677
+** The differences between a patchset and a changeset are that:
8678
+**
8679
+** <ul>
8680
+** <li> DELETE records consist of the primary key fields only. The
8681
+** original values of other fields are omitted.
8682
+** <li> The original values of any modified fields are omitted from
8683
+** UPDATE records.
8684
+** </ul>
8685
+**
8686
+** A patchset blob may be used with up to date versions of all
8687
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
8688
+** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
8689
+** attempting to use a patchset blob with old versions of the
8690
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
8691
+**
8692
+** Because the non-primary key "old.*" fields are omitted, no
8693
+** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
8694
+** is passed to the sqlite3changeset_apply() API. Other conflict types work
8695
+** in the same way as for changesets.
8696
+**
8697
+** Changes within a patchset are ordered in the same way as for changesets
8698
+** generated by the sqlite3session_changeset() function (i.e. all changes for
8699
+** a single table are grouped together, tables appear in the order in which
8700
+** they were attached to the session object).
8701
+*/
8702
+int sqlite3session_patchset(
8703
+ sqlite3_session *pSession, /* Session object */
8704
+ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
8705
+ void **ppPatchset /* OUT: Buffer containing changeset */
8706
+);
8707
+
8708
+/*
8709
+** CAPI3REF: Test if a changeset has recorded any changes.
8710
+**
8711
+** Return non-zero if no changes to attached tables have been recorded by
8712
+** the session object passed as the first argument. Otherwise, if one or
8713
+** more changes have been recorded, return zero.
8714
+**
8715
+** Even if this function returns zero, it is possible that calling
8716
+** [sqlite3session_changeset()] on the session handle may still return a
8717
+** changeset that contains no changes. This can happen when a row in
8718
+** an attached table is modified and then later on the original values
8719
+** are restored. However, if this function returns non-zero, then it is
8720
+** guaranteed that a call to sqlite3session_changeset() will return a
8721
+** changeset containing zero changes.
8722
+*/
8723
+int sqlite3session_isempty(sqlite3_session *pSession);
8724
+
8725
+/*
8726
+** CAPI3REF: Create An Iterator To Traverse A Changeset
8727
+**
8728
+** Create an iterator used to iterate through the contents of a changeset.
8729
+** If successful, *pp is set to point to the iterator handle and SQLITE_OK
8730
+** is returned. Otherwise, if an error occurs, *pp is set to zero and an
8731
+** SQLite error code is returned.
8732
+**
8733
+** The following functions can be used to advance and query a changeset
8734
+** iterator created by this function:
8735
+**
8736
+** <ul>
8737
+** <li> [sqlite3changeset_next()]
8738
+** <li> [sqlite3changeset_op()]
8739
+** <li> [sqlite3changeset_new()]
8740
+** <li> [sqlite3changeset_old()]
8741
+** </ul>
8742
+**
8743
+** It is the responsibility of the caller to eventually destroy the iterator
8744
+** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
8745
+** changeset (pChangeset) must remain valid until after the iterator is
8746
+** destroyed.
8747
+**
8748
+** Assuming the changeset blob was created by one of the
8749
+** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
8750
+** [sqlite3changeset_invert()] functions, all changes within the changeset
8751
+** that apply to a single table are grouped together. This means that when
8752
+** an application iterates through a changeset using an iterator created by
8753
+** this function, all changes that relate to a single table are visted
8754
+** consecutively. There is no chance that the iterator will visit a change
8755
+** the applies to table X, then one for table Y, and then later on visit
8756
+** another change for table X.
8757
+*/
8758
+int sqlite3changeset_start(
8759
+ sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
8760
+ int nChangeset, /* Size of changeset blob in bytes */
8761
+ void *pChangeset /* Pointer to blob containing changeset */
8762
+);
8763
+
8764
+
8765
+/*
8766
+** CAPI3REF: Advance A Changeset Iterator
8767
+**
8768
+** This function may only be used with iterators created by function
8769
+** [sqlite3changeset_start()]. If it is called on an iterator passed to
8770
+** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
8771
+** is returned and the call has no effect.
8772
+**
8773
+** Immediately after an iterator is created by sqlite3changeset_start(), it
8774
+** does not point to any change in the changeset. Assuming the changeset
8775
+** is not empty, the first call to this function advances the iterator to
8776
+** point to the first change in the changeset. Each subsequent call advances
8777
+** the iterator to point to the next change in the changeset (if any). If
8778
+** no error occurs and the iterator points to a valid change after a call
8779
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
8780
+** Otherwise, if all changes in the changeset have already been visited,
8781
+** SQLITE_DONE is returned.
8782
+**
8783
+** If an error occurs, an SQLite error code is returned. Possible error
8784
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
8785
+** SQLITE_NOMEM.
8786
+*/
8787
+int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
8788
+
8789
+/*
8790
+** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
8791
+**
8792
+** The pIter argument passed to this function may either be an iterator
8793
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8794
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
8795
+** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
8796
+** is not the case, this function returns [SQLITE_MISUSE].
8797
+**
8798
+** If argument pzTab is not NULL, then *pzTab is set to point to a
8799
+** nul-terminated utf-8 encoded string containing the name of the table
8800
+** affected by the current change. The buffer remains valid until either
8801
+** sqlite3changeset_next() is called on the iterator or until the
8802
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
8803
+** set to the number of columns in the table affected by the change. If
8804
+** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
8805
+** is an indirect change, or false (0) otherwise. See the documentation for
8806
+** [sqlite3session_indirect()] for a description of direct and indirect
8807
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
8808
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
8809
+** type of change that the iterator currently points to.
8810
+**
8811
+** If no error occurs, SQLITE_OK is returned. If an error does occur, an
8812
+** SQLite error code is returned. The values of the output variables may not
8813
+** be trusted in this case.
8814
+*/
8815
+int sqlite3changeset_op(
8816
+ sqlite3_changeset_iter *pIter, /* Iterator object */
8817
+ const char **pzTab, /* OUT: Pointer to table name */
8818
+ int *pnCol, /* OUT: Number of columns in table */
8819
+ int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
8820
+ int *pbIndirect /* OUT: True for an 'indirect' change */
8821
+);
8822
+
8823
+/*
8824
+** CAPI3REF: Obtain The Primary Key Definition Of A Table
8825
+**
8826
+** For each modified table, a changeset includes the following:
8827
+**
8828
+** <ul>
8829
+** <li> The number of columns in the table, and
8830
+** <li> Which of those columns make up the tables PRIMARY KEY.
8831
+** </ul>
8832
+**
8833
+** This function is used to find which columns comprise the PRIMARY KEY of
8834
+** the table modified by the change that iterator pIter currently points to.
8835
+** If successful, *pabPK is set to point to an array of nCol entries, where
8836
+** nCol is the number of columns in the table. Elements of *pabPK are set to
8837
+** 0x01 if the corresponding column is part of the tables primary key, or
8838
+** 0x00 if it is not.
8839
+**
8840
+** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
8841
+** in the table.
8842
+**
8843
+** If this function is called when the iterator does not point to a valid
8844
+** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
8845
+** SQLITE_OK is returned and the output variables populated as described
8846
+** above.
8847
+*/
8848
+int sqlite3changeset_pk(
8849
+ sqlite3_changeset_iter *pIter, /* Iterator object */
8850
+ unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
8851
+ int *pnCol /* OUT: Number of entries in output array */
8852
+);
8853
+
8854
+/*
8855
+** CAPI3REF: Obtain old.* Values From A Changeset Iterator
8856
+**
8857
+** The pIter argument passed to this function may either be an iterator
8858
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8859
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
8860
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
8861
+** Furthermore, it may only be called if the type of change that the iterator
8862
+** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
8863
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
8864
+**
8865
+** Argument iVal must be greater than or equal to 0, and less than the number
8866
+** of columns in the table affected by the current change. Otherwise,
8867
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8868
+**
8869
+** If successful, this function sets *ppValue to point to a protected
8870
+** sqlite3_value object containing the iVal'th value from the vector of
8871
+** original row values stored as part of the UPDATE or DELETE change and
8872
+** returns SQLITE_OK. The name of the function comes from the fact that this
8873
+** is similar to the "old.*" columns available to update or delete triggers.
8874
+**
8875
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
8876
+** is returned and *ppValue is set to NULL.
8877
+*/
8878
+int sqlite3changeset_old(
8879
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
8880
+ int iVal, /* Column number */
8881
+ sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
8882
+);
8883
+
8884
+/*
8885
+** CAPI3REF: Obtain new.* Values From A Changeset Iterator
8886
+**
8887
+** The pIter argument passed to this function may either be an iterator
8888
+** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8889
+** created by [sqlite3changeset_start()]. In the latter case, the most recent
8890
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
8891
+** Furthermore, it may only be called if the type of change that the iterator
8892
+** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
8893
+** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
8894
+**
8895
+** Argument iVal must be greater than or equal to 0, and less than the number
8896
+** of columns in the table affected by the current change. Otherwise,
8897
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8898
+**
8899
+** If successful, this function sets *ppValue to point to a protected
8900
+** sqlite3_value object containing the iVal'th value from the vector of
8901
+** new row values stored as part of the UPDATE or INSERT change and
8902
+** returns SQLITE_OK. If the change is an UPDATE and does not include
8903
+** a new value for the requested column, *ppValue is set to NULL and
8904
+** SQLITE_OK returned. The name of the function comes from the fact that
8905
+** this is similar to the "new.*" columns available to update or delete
8906
+** triggers.
8907
+**
8908
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
8909
+** is returned and *ppValue is set to NULL.
8910
+*/
8911
+int sqlite3changeset_new(
8912
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
8913
+ int iVal, /* Column number */
8914
+ sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
8915
+);
8916
+
8917
+/*
8918
+** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
8919
+**
8920
+** This function should only be used with iterator objects passed to a
8921
+** conflict-handler callback by [sqlite3changeset_apply()] with either
8922
+** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
8923
+** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
8924
+** is set to NULL.
8925
+**
8926
+** Argument iVal must be greater than or equal to 0, and less than the number
8927
+** of columns in the table affected by the current change. Otherwise,
8928
+** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8929
+**
8930
+** If successful, this function sets *ppValue to point to a protected
8931
+** sqlite3_value object containing the iVal'th value from the
8932
+** "conflicting row" associated with the current conflict-handler callback
8933
+** and returns SQLITE_OK.
8934
+**
8935
+** If some other error occurs (e.g. an OOM condition), an SQLite error code
8936
+** is returned and *ppValue is set to NULL.
8937
+*/
8938
+int sqlite3changeset_conflict(
8939
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
8940
+ int iVal, /* Column number */
8941
+ sqlite3_value **ppValue /* OUT: Value from conflicting row */
8942
+);
8943
+
8944
+/*
8945
+** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
8946
+**
8947
+** This function may only be called with an iterator passed to an
8948
+** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
8949
+** it sets the output variable to the total number of known foreign key
8950
+** violations in the destination database and returns SQLITE_OK.
8951
+**
8952
+** In all other cases this function returns SQLITE_MISUSE.
8953
+*/
8954
+int sqlite3changeset_fk_conflicts(
8955
+ sqlite3_changeset_iter *pIter, /* Changeset iterator */
8956
+ int *pnOut /* OUT: Number of FK violations */
8957
+);
8958
+
8959
+
8960
+/*
8961
+** CAPI3REF: Finalize A Changeset Iterator
8962
+**
8963
+** This function is used to finalize an iterator allocated with
8964
+** [sqlite3changeset_start()].
8965
+**
8966
+** This function should only be called on iterators created using the
8967
+** [sqlite3changeset_start()] function. If an application calls this
8968
+** function with an iterator passed to a conflict-handler by
8969
+** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
8970
+** call has no effect.
8971
+**
8972
+** If an error was encountered within a call to an sqlite3changeset_xxx()
8973
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
8974
+** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
8975
+** to that error is returned by this function. Otherwise, SQLITE_OK is
8976
+** returned. This is to allow the following pattern (pseudo-code):
8977
+**
8978
+** sqlite3changeset_start();
8979
+** while( SQLITE_ROW==sqlite3changeset_next() ){
8980
+** // Do something with change.
8981
+** }
8982
+** rc = sqlite3changeset_finalize();
8983
+** if( rc!=SQLITE_OK ){
8984
+** // An error has occurred
8985
+** }
8986
+*/
8987
+int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
8988
+
8989
+/*
8990
+** CAPI3REF: Invert A Changeset
8991
+**
8992
+** This function is used to "invert" a changeset object. Applying an inverted
8993
+** changeset to a database reverses the effects of applying the uninverted
8994
+** changeset. Specifically:
8995
+**
8996
+** <ul>
8997
+** <li> Each DELETE change is changed to an INSERT, and
8998
+** <li> Each INSERT change is changed to a DELETE, and
8999
+** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9000
+** </ul>
9001
+**
9002
+** This function does not change the order in which changes appear within
9003
+** the changeset. It merely reverses the sense of each individual change.
9004
+**
9005
+** If successful, a pointer to a buffer containing the inverted changeset
9006
+** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9007
+** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9008
+** zeroed and an SQLite error code returned.
9009
+**
9010
+** It is the responsibility of the caller to eventually call sqlite3_free()
9011
+** on the *ppOut pointer to free the buffer allocation following a successful
9012
+** call to this function.
9013
+**
9014
+** WARNING/TODO: This function currently assumes that the input is a valid
9015
+** changeset. If it is not, the results are undefined.
9016
+*/
9017
+int sqlite3changeset_invert(
9018
+ int nIn, const void *pIn, /* Input changeset */
9019
+ int *pnOut, void **ppOut /* OUT: Inverse of input */
9020
+);
9021
+
9022
+/*
9023
+** CAPI3REF: Concatenate Two Changeset Objects
9024
+**
9025
+** This function is used to concatenate two changesets, A and B, into a
9026
+** single changeset. The result is a changeset equivalent to applying
9027
+** changeset A followed by changeset B.
9028
+**
9029
+** This function combines the two input changesets using an
9030
+** sqlite3_changegroup object. Calling it produces similar results as the
9031
+** following code fragment:
9032
+**
9033
+** sqlite3_changegroup *pGrp;
9034
+** rc = sqlite3_changegroup_new(&pGrp);
9035
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9036
+** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9037
+** if( rc==SQLITE_OK ){
9038
+** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9039
+** }else{
9040
+** *ppOut = 0;
9041
+** *pnOut = 0;
9042
+** }
9043
+**
9044
+** Refer to the sqlite3_changegroup documentation below for details.
9045
+*/
9046
+int sqlite3changeset_concat(
9047
+ int nA, /* Number of bytes in buffer pA */
9048
+ void *pA, /* Pointer to buffer containing changeset A */
9049
+ int nB, /* Number of bytes in buffer pB */
9050
+ void *pB, /* Pointer to buffer containing changeset B */
9051
+ int *pnOut, /* OUT: Number of bytes in output changeset */
9052
+ void **ppOut /* OUT: Buffer containing output changeset */
9053
+);
9054
+
9055
+
9056
+/*
9057
+** Changegroup handle.
9058
+*/
9059
+typedef struct sqlite3_changegroup sqlite3_changegroup;
9060
+
9061
+/*
9062
+** CAPI3REF: Combine two or more changesets into a single changeset.
9063
+**
9064
+** An sqlite3_changegroup object is used to combine two or more changesets
9065
+** (or patchsets) into a single changeset (or patchset). A single changegroup
9066
+** object may combine changesets or patchsets, but not both. The output is
9067
+** always in the same format as the input.
9068
+**
9069
+** If successful, this function returns SQLITE_OK and populates (*pp) with
9070
+** a pointer to a new sqlite3_changegroup object before returning. The caller
9071
+** should eventually free the returned object using a call to
9072
+** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9073
+** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9074
+**
9075
+** The usual usage pattern for an sqlite3_changegroup object is as follows:
9076
+**
9077
+** <ul>
9078
+** <li> It is created using a call to sqlite3changegroup_new().
9079
+**
9080
+** <li> Zero or more changesets (or patchsets) are added to the object
9081
+** by calling sqlite3changegroup_add().
9082
+**
9083
+** <li> The result of combining all input changesets together is obtained
9084
+** by the application via a call to sqlite3changegroup_output().
9085
+**
9086
+** <li> The object is deleted using a call to sqlite3changegroup_delete().
9087
+** </ul>
9088
+**
9089
+** Any number of calls to add() and output() may be made between the calls to
9090
+** new() and delete(), and in any order.
9091
+**
9092
+** As well as the regular sqlite3changegroup_add() and
9093
+** sqlite3changegroup_output() functions, also available are the streaming
9094
+** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9095
+*/
9096
+int sqlite3changegroup_new(sqlite3_changegroup **pp);
9097
+
9098
+/*
9099
+** Add all changes within the changeset (or patchset) in buffer pData (size
9100
+** nData bytes) to the changegroup.
9101
+**
9102
+** If the buffer contains a patchset, then all prior calls to this function
9103
+** on the same changegroup object must also have specified patchsets. Or, if
9104
+** the buffer contains a changeset, so must have the earlier calls to this
9105
+** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9106
+** to the changegroup.
9107
+**
9108
+** Rows within the changeset and changegroup are identified by the values in
9109
+** their PRIMARY KEY columns. A change in the changeset is considered to
9110
+** apply to the same row as a change already present in the changegroup if
9111
+** the two rows have the same primary key.
9112
+**
9113
+** Changes to rows that that do not already appear in the changegroup are
9114
+** simply copied into it. Or, if both the new changeset and the changegroup
9115
+** contain changes that apply to a single row, the final contents of the
9116
+** changegroup depends on the type of each change, as follows:
9117
+**
9118
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
9119
+** <tr><th style="white-space:pre">Existing Change </th>
9120
+** <th style="white-space:pre">New Change </th>
9121
+** <th>Output Change
9122
+** <tr><td>INSERT <td>INSERT <td>
9123
+** The new change is ignored. This case does not occur if the new
9124
+** changeset was recorded immediately after the changesets already
9125
+** added to the changegroup.
9126
+** <tr><td>INSERT <td>UPDATE <td>
9127
+** The INSERT change remains in the changegroup. The values in the
9128
+** INSERT change are modified as if the row was inserted by the
9129
+** existing change and then updated according to the new change.
9130
+** <tr><td>INSERT <td>DELETE <td>
9131
+** The existing INSERT is removed from the changegroup. The DELETE is
9132
+** not added.
9133
+** <tr><td>UPDATE <td>INSERT <td>
9134
+** The new change is ignored. This case does not occur if the new
9135
+** changeset was recorded immediately after the changesets already
9136
+** added to the changegroup.
9137
+** <tr><td>UPDATE <td>UPDATE <td>
9138
+** The existing UPDATE remains within the changegroup. It is amended
9139
+** so that the accompanying values are as if the row was updated once
9140
+** by the existing change and then again by the new change.
9141
+** <tr><td>UPDATE <td>DELETE <td>
9142
+** The existing UPDATE is replaced by the new DELETE within the
9143
+** changegroup.
9144
+** <tr><td>DELETE <td>INSERT <td>
9145
+** If one or more of the column values in the row inserted by the
9146
+** new change differ from those in the row deleted by the existing
9147
+** change, the existing DELETE is replaced by an UPDATE within the
9148
+** changegroup. Otherwise, if the inserted row is exactly the same
9149
+** as the deleted row, the existing DELETE is simply discarded.
9150
+** <tr><td>DELETE <td>UPDATE <td>
9151
+** The new change is ignored. This case does not occur if the new
9152
+** changeset was recorded immediately after the changesets already
9153
+** added to the changegroup.
9154
+** <tr><td>DELETE <td>DELETE <td>
9155
+** The new change is ignored. This case does not occur if the new
9156
+** changeset was recorded immediately after the changesets already
9157
+** added to the changegroup.
9158
+** </table>
9159
+**
9160
+** If the new changeset contains changes to a table that is already present
9161
+** in the changegroup, then the number of columns and the position of the
9162
+** primary key columns for the table must be consistent. If this is not the
9163
+** case, this function fails with SQLITE_SCHEMA. If the input changeset
9164
+** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9165
+** returned. Or, if an out-of-memory condition occurs during processing, this
9166
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9167
+** final contents of the changegroup is undefined.
9168
+**
9169
+** If no error occurs, SQLITE_OK is returned.
9170
+*/
9171
+int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9172
+
9173
+/*
9174
+** Obtain a buffer containing a changeset (or patchset) representing the
9175
+** current contents of the changegroup. If the inputs to the changegroup
9176
+** were themselves changesets, the output is a changeset. Or, if the
9177
+** inputs were patchsets, the output is also a patchset.
9178
+**
9179
+** As with the output of the sqlite3session_changeset() and
9180
+** sqlite3session_patchset() functions, all changes related to a single
9181
+** table are grouped together in the output of this function. Tables appear
9182
+** in the same order as for the very first changeset added to the changegroup.
9183
+** If the second or subsequent changesets added to the changegroup contain
9184
+** changes for tables that do not appear in the first changeset, they are
9185
+** appended onto the end of the output changeset, again in the order in
9186
+** which they are first encountered.
9187
+**
9188
+** If an error occurs, an SQLite error code is returned and the output
9189
+** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9190
+** is returned and the output variables are set to the size of and a
9191
+** pointer to the output buffer, respectively. In this case it is the
9192
+** responsibility of the caller to eventually free the buffer using a
9193
+** call to sqlite3_free().
9194
+*/
9195
+int sqlite3changegroup_output(
9196
+ sqlite3_changegroup*,
9197
+ int *pnData, /* OUT: Size of output buffer in bytes */
9198
+ void **ppData /* OUT: Pointer to output buffer */
9199
+);
9200
+
9201
+/*
9202
+** Delete a changegroup object.
9203
+*/
9204
+void sqlite3changegroup_delete(sqlite3_changegroup*);
9205
+
9206
+/*
9207
+** CAPI3REF: Apply A Changeset To A Database
9208
+**
9209
+** Apply a changeset to a database. This function attempts to update the
9210
+** "main" database attached to handle db with the changes found in the
9211
+** changeset passed via the second and third arguments.
9212
+**
9213
+** The fourth argument (xFilter) passed to this function is the "filter
9214
+** callback". If it is not NULL, then for each table affected by at least one
9215
+** change in the changeset, the filter callback is invoked with
9216
+** the table name as the second argument, and a copy of the context pointer
9217
+** passed as the sixth argument to this function as the first. If the "filter
9218
+** callback" returns zero, then no attempt is made to apply any changes to
9219
+** the table. Otherwise, if the return value is non-zero or the xFilter
9220
+** argument to this function is NULL, all changes related to the table are
9221
+** attempted.
9222
+**
9223
+** For each table that is not excluded by the filter callback, this function
9224
+** tests that the target database contains a compatible table. A table is
9225
+** considered compatible if all of the following are true:
9226
+**
9227
+** <ul>
9228
+** <li> The table has the same name as the name recorded in the
9229
+** changeset, and
9230
+** <li> The table has the same number of columns as recorded in the
9231
+** changeset, and
9232
+** <li> The table has primary key columns in the same position as
9233
+** recorded in the changeset.
9234
+** </ul>
9235
+**
9236
+** If there is no compatible table, it is not an error, but none of the
9237
+** changes associated with the table are applied. A warning message is issued
9238
+** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9239
+** one such warning is issued for each table in the changeset.
9240
+**
9241
+** For each change for which there is a compatible table, an attempt is made
9242
+** to modify the table contents according to the UPDATE, INSERT or DELETE
9243
+** change. If a change cannot be applied cleanly, the conflict handler
9244
+** function passed as the fifth argument to sqlite3changeset_apply() may be
9245
+** invoked. A description of exactly when the conflict handler is invoked for
9246
+** each type of change is below.
9247
+**
9248
+** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9249
+** of passing anything other than a valid function pointer as the xConflict
9250
+** argument are undefined.
9251
+**
9252
+** Each time the conflict handler function is invoked, it must return one
9253
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9254
+** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9255
+** if the second argument passed to the conflict handler is either
9256
+** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9257
+** returns an illegal value, any changes already made are rolled back and
9258
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9259
+** actions are taken by sqlite3changeset_apply() depending on the value
9260
+** returned by each invocation of the conflict-handler function. Refer to
9261
+** the documentation for the three
9262
+** [SQLITE_CHANGESET_OMIT|available return values] for details.
9263
+**
9264
+** <dl>
9265
+** <dt>DELETE Changes<dd>
9266
+** For each DELETE change, this function checks if the target database
9267
+** contains a row with the same primary key value (or values) as the
9268
+** original row values stored in the changeset. If it does, and the values
9269
+** stored in all non-primary key columns also match the values stored in
9270
+** the changeset the row is deleted from the target database.
9271
+**
9272
+** If a row with matching primary key values is found, but one or more of
9273
+** the non-primary key fields contains a value different from the original
9274
+** row value stored in the changeset, the conflict-handler function is
9275
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9276
+**
9277
+** If no row with matching primary key values is found in the database,
9278
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9279
+** passed as the second argument.
9280
+**
9281
+** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9282
+** (which can only happen if a foreign key constraint is violated), the
9283
+** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9284
+** passed as the second argument. This includes the case where the DELETE
9285
+** operation is attempted because an earlier call to the conflict handler
9286
+** function returned [SQLITE_CHANGESET_REPLACE].
9287
+**
9288
+** <dt>INSERT Changes<dd>
9289
+** For each INSERT change, an attempt is made to insert the new row into
9290
+** the database.
9291
+**
9292
+** If the attempt to insert the row fails because the database already
9293
+** contains a row with the same primary key values, the conflict handler
9294
+** function is invoked with the second argument set to
9295
+** [SQLITE_CHANGESET_CONFLICT].
9296
+**
9297
+** If the attempt to insert the row fails because of some other constraint
9298
+** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9299
+** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9300
+** This includes the case where the INSERT operation is re-attempted because
9301
+** an earlier call to the conflict handler function returned
9302
+** [SQLITE_CHANGESET_REPLACE].
9303
+**
9304
+** <dt>UPDATE Changes<dd>
9305
+** For each UPDATE change, this function checks if the target database
9306
+** contains a row with the same primary key value (or values) as the
9307
+** original row values stored in the changeset. If it does, and the values
9308
+** stored in all non-primary key columns also match the values stored in
9309
+** the changeset the row is updated within the target database.
9310
+**
9311
+** If a row with matching primary key values is found, but one or more of
9312
+** the non-primary key fields contains a value different from an original
9313
+** row value stored in the changeset, the conflict-handler function is
9314
+** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9315
+** UPDATE changes only contain values for non-primary key fields that are
9316
+** to be modified, only those fields need to match the original values to
9317
+** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9318
+**
9319
+** If no row with matching primary key values is found in the database,
9320
+** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9321
+** passed as the second argument.
9322
+**
9323
+** If the UPDATE operation is attempted, but SQLite returns
9324
+** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9325
+** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9326
+** This includes the case where the UPDATE operation is attempted after
9327
+** an earlier call to the conflict handler function returned
9328
+** [SQLITE_CHANGESET_REPLACE].
9329
+** </dl>
9330
+**
9331
+** It is safe to execute SQL statements, including those that write to the
9332
+** table that the callback related to, from within the xConflict callback.
9333
+** This can be used to further customize the applications conflict
9334
+** resolution strategy.
9335
+**
9336
+** All changes made by this function are enclosed in a savepoint transaction.
9337
+** If any other error (aside from a constraint failure when attempting to
9338
+** write to the target database) occurs, then the savepoint transaction is
9339
+** rolled back, restoring the target database to its original state, and an
9340
+** SQLite error code returned.
9341
+*/
9342
+int sqlite3changeset_apply(
9343
+ sqlite3 *db, /* Apply change to "main" db of this handle */
9344
+ int nChangeset, /* Size of changeset in bytes */
9345
+ void *pChangeset, /* Changeset blob */
9346
+ int(*xFilter)(
9347
+ void *pCtx, /* Copy of sixth arg to _apply() */
9348
+ const char *zTab /* Table name */
9349
+ ),
9350
+ int(*xConflict)(
9351
+ void *pCtx, /* Copy of sixth arg to _apply() */
9352
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9353
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
9354
+ ),
9355
+ void *pCtx /* First argument passed to xConflict */
9356
+);
9357
+
9358
+/*
9359
+** CAPI3REF: Constants Passed To The Conflict Handler
9360
+**
9361
+** Values that may be passed as the second argument to a conflict-handler.
9362
+**
9363
+** <dl>
9364
+** <dt>SQLITE_CHANGESET_DATA<dd>
9365
+** The conflict handler is invoked with CHANGESET_DATA as the second argument
9366
+** when processing a DELETE or UPDATE change if a row with the required
9367
+** PRIMARY KEY fields is present in the database, but one or more other
9368
+** (non primary-key) fields modified by the update do not contain the
9369
+** expected "before" values.
9370
+**
9371
+** The conflicting row, in this case, is the database row with the matching
9372
+** primary key.
9373
+**
9374
+** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9375
+** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9376
+** argument when processing a DELETE or UPDATE change if a row with the
9377
+** required PRIMARY KEY fields is not present in the database.
9378
+**
9379
+** There is no conflicting row in this case. The results of invoking the
9380
+** sqlite3changeset_conflict() API are undefined.
9381
+**
9382
+** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9383
+** CHANGESET_CONFLICT is passed as the second argument to the conflict
9384
+** handler while processing an INSERT change if the operation would result
9385
+** in duplicate primary key values.
9386
+**
9387
+** The conflicting row in this case is the database row with the matching
9388
+** primary key.
9389
+**
9390
+** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9391
+** If foreign key handling is enabled, and applying a changeset leaves the
9392
+** database in a state containing foreign key violations, the conflict
9393
+** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9394
+** exactly once before the changeset is committed. If the conflict handler
9395
+** returns CHANGESET_OMIT, the changes, including those that caused the
9396
+** foreign key constraint violation, are committed. Or, if it returns
9397
+** CHANGESET_ABORT, the changeset is rolled back.
9398
+**
9399
+** No current or conflicting row information is provided. The only function
9400
+** it is possible to call on the supplied sqlite3_changeset_iter handle
9401
+** is sqlite3changeset_fk_conflicts().
9402
+**
9403
+** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9404
+** If any other constraint violation occurs while applying a change (i.e.
9405
+** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9406
+** invoked with CHANGESET_CONSTRAINT as the second argument.
9407
+**
9408
+** There is no conflicting row in this case. The results of invoking the
9409
+** sqlite3changeset_conflict() API are undefined.
9410
+**
9411
+** </dl>
9412
+*/
9413
+#define SQLITE_CHANGESET_DATA 1
9414
+#define SQLITE_CHANGESET_NOTFOUND 2
9415
+#define SQLITE_CHANGESET_CONFLICT 3
9416
+#define SQLITE_CHANGESET_CONSTRAINT 4
9417
+#define SQLITE_CHANGESET_FOREIGN_KEY 5
9418
+
9419
+/*
9420
+** CAPI3REF: Constants Returned By The Conflict Handler
9421
+**
9422
+** A conflict handler callback must return one of the following three values.
9423
+**
9424
+** <dl>
9425
+** <dt>SQLITE_CHANGESET_OMIT<dd>
9426
+** If a conflict handler returns this value no special action is taken. The
9427
+** change that caused the conflict is not applied. The session module
9428
+** continues to the next change in the changeset.
9429
+**
9430
+** <dt>SQLITE_CHANGESET_REPLACE<dd>
9431
+** This value may only be returned if the second argument to the conflict
9432
+** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9433
+** is not the case, any changes applied so far are rolled back and the
9434
+** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9435
+**
9436
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9437
+** handler, then the conflicting row is either updated or deleted, depending
9438
+** on the type of change.
9439
+**
9440
+** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9441
+** handler, then the conflicting row is removed from the database and a
9442
+** second attempt to apply the change is made. If this second attempt fails,
9443
+** the original row is restored to the database before continuing.
9444
+**
9445
+** <dt>SQLITE_CHANGESET_ABORT<dd>
9446
+** If this value is returned, any changes applied so far are rolled back
9447
+** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9448
+** </dl>
9449
+*/
9450
+#define SQLITE_CHANGESET_OMIT 0
9451
+#define SQLITE_CHANGESET_REPLACE 1
9452
+#define SQLITE_CHANGESET_ABORT 2
9453
+
9454
+/*
9455
+** CAPI3REF: Streaming Versions of API functions.
9456
+**
9457
+** The six streaming API xxx_strm() functions serve similar purposes to the
9458
+** corresponding non-streaming API functions:
9459
+**
9460
+** <table border=1 style="margin-left:8ex;margin-right:8ex">
9461
+** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9462
+** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9463
+** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9464
+** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9465
+** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9466
+** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9467
+** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9468
+** </table>
9469
+**
9470
+** Non-streaming functions that accept changesets (or patchsets) as input
9471
+** require that the entire changeset be stored in a single buffer in memory.
9472
+** Similarly, those that return a changeset or patchset do so by returning
9473
+** a pointer to a single large buffer allocated using sqlite3_malloc().
9474
+** Normally this is convenient. However, if an application running in a
9475
+** low-memory environment is required to handle very large changesets, the
9476
+** large contiguous memory allocations required can become onerous.
9477
+**
9478
+** In order to avoid this problem, instead of a single large buffer, input
9479
+** is passed to a streaming API functions by way of a callback function that
9480
+** the sessions module invokes to incrementally request input data as it is
9481
+** required. In all cases, a pair of API function parameters such as
9482
+**
9483
+** <pre>
9484
+** &nbsp; int nChangeset,
9485
+** &nbsp; void *pChangeset,
9486
+** </pre>
9487
+**
9488
+** Is replaced by:
9489
+**
9490
+** <pre>
9491
+** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9492
+** &nbsp; void *pIn,
9493
+** </pre>
9494
+**
9495
+** Each time the xInput callback is invoked by the sessions module, the first
9496
+** argument passed is a copy of the supplied pIn context pointer. The second
9497
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9498
+** error occurs the xInput method should copy up to (*pnData) bytes of data
9499
+** into the buffer and set (*pnData) to the actual number of bytes copied
9500
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9501
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9502
+** error code should be returned. In all cases, if an xInput callback returns
9503
+** an error, all processing is abandoned and the streaming API function
9504
+** returns a copy of the error code to the caller.
9505
+**
9506
+** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9507
+** invoked by the sessions module at any point during the lifetime of the
9508
+** iterator. If such an xInput callback returns an error, the iterator enters
9509
+** an error state, whereby all subsequent calls to iterator functions
9510
+** immediately fail with the same error code as returned by xInput.
9511
+**
9512
+** Similarly, streaming API functions that return changesets (or patchsets)
9513
+** return them in chunks by way of a callback function instead of via a
9514
+** pointer to a single large buffer. In this case, a pair of parameters such
9515
+** as:
9516
+**
9517
+** <pre>
9518
+** &nbsp; int *pnChangeset,
9519
+** &nbsp; void **ppChangeset,
9520
+** </pre>
9521
+**
9522
+** Is replaced by:
9523
+**
9524
+** <pre>
9525
+** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9526
+** &nbsp; void *pOut
9527
+** </pre>
9528
+**
9529
+** The xOutput callback is invoked zero or more times to return data to
9530
+** the application. The first parameter passed to each call is a copy of the
9531
+** pOut pointer supplied by the application. The second parameter, pData,
9532
+** points to a buffer nData bytes in size containing the chunk of output
9533
+** data being returned. If the xOutput callback successfully processes the
9534
+** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9535
+** it should return some other SQLite error code. In this case processing
9536
+** is immediately abandoned and the streaming API function returns a copy
9537
+** of the xOutput error code to the application.
9538
+**
9539
+** The sessions module never invokes an xOutput callback with the third
9540
+** parameter set to a value less than or equal to zero. Other than this,
9541
+** no guarantees are made as to the size of the chunks of data returned.
9542
+*/
9543
+int sqlite3changeset_apply_strm(
9544
+ sqlite3 *db, /* Apply change to "main" db of this handle */
9545
+ int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9546
+ void *pIn, /* First arg for xInput */
9547
+ int(*xFilter)(
9548
+ void *pCtx, /* Copy of sixth arg to _apply() */
9549
+ const char *zTab /* Table name */
9550
+ ),
9551
+ int(*xConflict)(
9552
+ void *pCtx, /* Copy of sixth arg to _apply() */
9553
+ int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9554
+ sqlite3_changeset_iter *p /* Handle describing change and conflict */
9555
+ ),
9556
+ void *pCtx /* First argument passed to xConflict */
9557
+);
9558
+int sqlite3changeset_concat_strm(
9559
+ int (*xInputA)(void *pIn, void *pData, int *pnData),
9560
+ void *pInA,
9561
+ int (*xInputB)(void *pIn, void *pData, int *pnData),
9562
+ void *pInB,
9563
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9564
+ void *pOut
9565
+);
9566
+int sqlite3changeset_invert_strm(
9567
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9568
+ void *pIn,
9569
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9570
+ void *pOut
9571
+);
9572
+int sqlite3changeset_start_strm(
9573
+ sqlite3_changeset_iter **pp,
9574
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9575
+ void *pIn
9576
+);
9577
+int sqlite3session_changeset_strm(
9578
+ sqlite3_session *pSession,
9579
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9580
+ void *pOut
9581
+);
9582
+int sqlite3session_patchset_strm(
9583
+ sqlite3_session *pSession,
9584
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9585
+ void *pOut
9586
+);
9587
+int sqlite3changegroup_add_strm(sqlite3_changegroup*,
9588
+ int (*xInput)(void *pIn, void *pData, int *pnData),
9589
+ void *pIn
9590
+);
9591
+int sqlite3changegroup_output_strm(sqlite3_changegroup*,
9592
+ int (*xOutput)(void *pOut, const void *pData, int nData),
9593
+ void *pOut
9594
+);
9595
+
9596
+
9597
+/*
9598
+** Make sure we can call this stuff from C++.
9599
+*/
9600
+#ifdef __cplusplus
9601
+}
9602
+#endif
9603
+
9604
+#endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
9605
+
9606
+/******** End of sqlite3session.h *********/
9607
+/******** Begin file fts5.h *********/
81569608
/*
81579609
** 2014 May 31
81589610
**
81599611
** The author disclaims copyright to this source code. In place of
81609612
** a legal notice, here is a blessing:
@@ -8295,15 +9747,17 @@
82959747
** of the current query. Specifically, a query equivalent to:
82969748
**
82979749
** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
82989750
**
82999751
** with $p set to a phrase equivalent to the phrase iPhrase of the
8300
-** current query is executed. For each row visited, the callback function
8301
-** passed as the fourth argument is invoked. The context and API objects
8302
-** passed to the callback function may be used to access the properties of
8303
-** each matched row. Invoking Api.xUserData() returns a copy of the pointer
8304
-** passed as the third argument to pUserData.
9752
+** current query is executed. Any column filter that applies to
9753
+** phrase iPhrase of the current query is included in $p. For each
9754
+** row visited, the callback function passed as the fourth argument
9755
+** is invoked. The context and API objects passed to the callback
9756
+** function may be used to access the properties of each matched row.
9757
+** Invoking Api.xUserData() returns a copy of the pointer passed as
9758
+** the third argument to pUserData.
83059759
**
83069760
** If the callback function returns any value other than SQLITE_OK, the
83079761
** query is abandoned and the xQueryPhrase function returns immediately.
83089762
** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
83099763
** Otherwise, the error code is propagated upwards.
@@ -8729,5 +10183,6 @@
872910183
#endif
873010184
873110185
#endif /* _FTS5_H */
873210186
873310187
10188
+/******** End of fts5.h *********/
873410189
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -109,13 +109,13 @@
109 **
110 ** See also: [sqlite3_libversion()],
111 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
112 ** [sqlite_version()] and [sqlite_source_id()].
113 */
114 #define SQLITE_VERSION "3.12.1"
115 #define SQLITE_VERSION_NUMBER 3012001
116 #define SQLITE_SOURCE_ID "2016-04-08 15:09:49 fe7d3b75fe1bde41511b323925af8ae1b910bc4d"
117
118 /*
119 ** CAPI3REF: Run-Time Library Version Numbers
120 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
121 **
@@ -1930,16 +1930,34 @@
1930 ** The second parameter is a pointer to an integer into which
1931 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
1932 ** following this call. The second parameter may be a NULL pointer, in
1933 ** which case the new setting is not reported back. </dd>
1934 **
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1935 ** </dl>
1936 */
1937 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1938 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
1939 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
1940 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
 
1941
1942
1943 /*
1944 ** CAPI3REF: Enable Or Disable Extended Result Codes
1945 ** METHOD: sqlite3
@@ -5185,11 +5203,11 @@
5185 ** METHOD: sqlite3
5186 **
5187 ** ^The sqlite3_update_hook() interface registers a callback function
5188 ** with the [database connection] identified by the first argument
5189 ** to be invoked whenever a row is updated, inserted or deleted in
5190 ** a rowid table.
5191 ** ^Any callback set by a previous call to this function
5192 ** for the same database connection is overridden.
5193 **
5194 ** ^The second argument is a pointer to the function to invoke when a
5195 ** row is updated, inserted or deleted in a rowid table.
@@ -5224,12 +5242,12 @@
5224 ** ^The sqlite3_update_hook(D,C,P) function
5225 ** returns the P argument from the previous call
5226 ** on the same [database connection] D, or NULL for
5227 ** the first call on D.
5228 **
5229 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5230 ** interfaces.
5231 */
5232 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5233 sqlite3*,
5234 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5235 void*
@@ -5472,12 +5490,21 @@
5472 ** fill *pzErrMsg with error message text stored in memory
5473 ** obtained from [sqlite3_malloc()]. The calling function
5474 ** should free this memory by calling [sqlite3_free()].
5475 **
5476 ** ^Extension loading must be enabled using
5477 ** [sqlite3_enable_load_extension()] prior to calling this API,
 
 
5478 ** otherwise an error will be returned.
 
 
 
 
 
 
 
5479 **
5480 ** See also the [load_extension() SQL function].
5481 */
5482 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5483 sqlite3 *db, /* Load the extension into this database connection */
@@ -5497,10 +5524,21 @@
5497 **
5498 ** ^Extension loading is off by default.
5499 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5500 ** to turn extension loading on and call it with onoff==0 to turn
5501 ** it back off again.
 
 
 
 
 
 
 
 
 
 
 
5502 */
5503 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5504
5505 /*
5506 ** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7135,11 +7173,11 @@
7135 ** and database name of the source database, respectively.
7136 ** ^The source and destination [database connections] (parameters S and D)
7137 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7138 ** an error.
7139 **
7140 ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7141 ** there is already a read or read-write transaction open on the
7142 ** destination database.
7143 **
7144 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7145 ** returned and an error code and error message are stored in the
@@ -7913,15 +7951,111 @@
7913 ** ^This function does not set the database handle error code or message
7914 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
7915 */
7916 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
7917
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7918 /*
7919 ** CAPI3REF: Low-level system error code
7920 **
7921 ** ^Attempt to return the underlying operating system error code or error
7922 ** number that caused the most reason I/O error or failure to open a file.
7923 ** The return value is OS-dependent. For example, on unix systems, after
7924 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
7925 ** called to get back the underlying "errno" that caused the problem, such
7926 ** as ENOSPC, EAUTH, EISDIR, and so forth.
7927 */
@@ -7983,24 +8117,33 @@
7983
7984 /*
7985 ** CAPI3REF: Start a read transaction on an historical snapshot
7986 ** EXPERIMENTAL
7987 **
7988 ** ^The [sqlite3_snapshot_open(D,S,P)] interface attempts to move the
7989 ** read transaction that is currently open on schema S of
7990 ** [database connection] D so that it refers to historical [snapshot] P.
 
 
7991 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
7992 ** or an appropriate [error code] if it fails.
7993 **
7994 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
7995 ** the first operation, apart from other sqlite3_snapshot_open() calls,
7996 ** following the [BEGIN] that starts a new read transaction.
7997 ** ^A [snapshot] will fail to open if it has been overwritten by a
 
 
 
7998 ** [checkpoint].
7999 ** ^A [snapshot] will fail to open if the database connection D has not
8000 ** previously completed at least one read operation against the database
8001 ** file. (Hint: Run "[PRAGMA application_id]" against a newly opened
 
 
 
 
8002 ** database connection in order to make it ready to use snapshots.)
8003 **
8004 ** The [sqlite3_snapshot_open()] interface is only available when the
8005 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8006 */
@@ -8021,10 +8164,37 @@
8021 ** The [sqlite3_snapshot_free()] interface is only available when the
8022 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8023 */
8024 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8026 /*
8027 ** Undo the hack that converts floating point types to integer for
8028 ** builds on processors without floating point support.
8029 */
8030 #ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8034,10 +8204,11 @@
8034 #ifdef __cplusplus
8035 } /* End of the 'extern "C"' block */
8036 #endif
8037 #endif /* _SQLITE3_H_ */
8038
 
8039 /*
8040 ** 2010 August 30
8041 **
8042 ** The author disclaims copyright to this source code. In place of
8043 ** a legal notice, here is a blessing:
@@ -8151,10 +8322,1291 @@
8151 } /* end of the 'extern "C"' block */
8152 #endif
8153
8154 #endif /* ifndef _SQLITE3RTREE_H_ */
8155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8156 /*
8157 ** 2014 May 31
8158 **
8159 ** The author disclaims copyright to this source code. In place of
8160 ** a legal notice, here is a blessing:
@@ -8295,15 +9747,17 @@
8295 ** of the current query. Specifically, a query equivalent to:
8296 **
8297 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
8298 **
8299 ** with $p set to a phrase equivalent to the phrase iPhrase of the
8300 ** current query is executed. For each row visited, the callback function
8301 ** passed as the fourth argument is invoked. The context and API objects
8302 ** passed to the callback function may be used to access the properties of
8303 ** each matched row. Invoking Api.xUserData() returns a copy of the pointer
8304 ** passed as the third argument to pUserData.
 
 
8305 **
8306 ** If the callback function returns any value other than SQLITE_OK, the
8307 ** query is abandoned and the xQueryPhrase function returns immediately.
8308 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
8309 ** Otherwise, the error code is propagated upwards.
@@ -8729,5 +10183,6 @@
8729 #endif
8730
8731 #endif /* _FTS5_H */
8732
8733
 
8734
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -109,13 +109,13 @@
109 **
110 ** See also: [sqlite3_libversion()],
111 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
112 ** [sqlite_version()] and [sqlite_source_id()].
113 */
114 #define SQLITE_VERSION "3.13.0"
115 #define SQLITE_VERSION_NUMBER 3013000
116 #define SQLITE_SOURCE_ID "2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2"
117
118 /*
119 ** CAPI3REF: Run-Time Library Version Numbers
120 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
121 **
@@ -1930,16 +1930,34 @@
1930 ** The second parameter is a pointer to an integer into which
1931 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
1932 ** following this call. The second parameter may be a NULL pointer, in
1933 ** which case the new setting is not reported back. </dd>
1934 **
1935 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
1936 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
1937 ** interface independently of the [load_extension()] SQL function.
1938 ** The [sqlite3_enable_load_extension()] API enables or disables both the
1939 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
1940 ** There should be two additional arguments.
1941 ** When the first argument to this interface is 1, then only the C-API is
1942 ** enabled and the SQL function remains disabled. If the first argment to
1943 ** this interface is 0, then both the C-API and the SQL function are disabled.
1944 ** If the first argument is -1, then no changes are made to state of either the
1945 ** C-API or the SQL function.
1946 ** The second parameter is a pointer to an integer into which
1947 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
1948 ** is disabled or enabled following this call. The second parameter may
1949 ** be a NULL pointer, in which case the new setting is not reported back.
1950 ** </dd>
1951 **
1952 ** </dl>
1953 */
1954 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1955 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
1956 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
1957 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
1958 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
1959
1960
1961 /*
1962 ** CAPI3REF: Enable Or Disable Extended Result Codes
1963 ** METHOD: sqlite3
@@ -5185,11 +5203,11 @@
5203 ** METHOD: sqlite3
5204 **
5205 ** ^The sqlite3_update_hook() interface registers a callback function
5206 ** with the [database connection] identified by the first argument
5207 ** to be invoked whenever a row is updated, inserted or deleted in
5208 ** a [rowid table].
5209 ** ^Any callback set by a previous call to this function
5210 ** for the same database connection is overridden.
5211 **
5212 ** ^The second argument is a pointer to the function to invoke when a
5213 ** row is updated, inserted or deleted in a rowid table.
@@ -5224,12 +5242,12 @@
5242 ** ^The sqlite3_update_hook(D,C,P) function
5243 ** returns the P argument from the previous call
5244 ** on the same [database connection] D, or NULL for
5245 ** the first call on D.
5246 **
5247 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5248 ** and [sqlite3_preupdate_hook()] interfaces.
5249 */
5250 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5251 sqlite3*,
5252 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5253 void*
@@ -5472,12 +5490,21 @@
5490 ** fill *pzErrMsg with error message text stored in memory
5491 ** obtained from [sqlite3_malloc()]. The calling function
5492 ** should free this memory by calling [sqlite3_free()].
5493 **
5494 ** ^Extension loading must be enabled using
5495 ** [sqlite3_enable_load_extension()] or
5496 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5497 ** prior to calling this API,
5498 ** otherwise an error will be returned.
5499 **
5500 ** <b>Security warning:</b> It is recommended that the
5501 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5502 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5503 ** should be avoided. This will keep the SQL function [load_extension()]
5504 ** disabled and prevent SQL injections from giving attackers
5505 ** access to extension loading capabilities.
5506 **
5507 ** See also the [load_extension() SQL function].
5508 */
5509 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5510 sqlite3 *db, /* Load the extension into this database connection */
@@ -5497,10 +5524,21 @@
5524 **
5525 ** ^Extension loading is off by default.
5526 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5527 ** to turn extension loading on and call it with onoff==0 to turn
5528 ** it back off again.
5529 **
5530 ** ^This interface enables or disables both the C-API
5531 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5532 ** Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5533 ** to enable or disable only the C-API.
5534 **
5535 ** <b>Security warning:</b> It is recommended that extension loading
5536 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5537 ** rather than this interface, so the [load_extension()] SQL function
5538 ** remains disabled. This will prevent SQL injections from giving attackers
5539 ** access to extension loading capabilities.
5540 */
5541 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5542
5543 /*
5544 ** CAPI3REF: Automatically Load Statically Linked Extensions
@@ -7135,11 +7173,11 @@
7173 ** and database name of the source database, respectively.
7174 ** ^The source and destination [database connections] (parameters S and D)
7175 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7176 ** an error.
7177 **
7178 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7179 ** there is already a read or read-write transaction open on the
7180 ** destination database.
7181 **
7182 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7183 ** returned and an error code and error message are stored in the
@@ -7913,15 +7951,111 @@
7951 ** ^This function does not set the database handle error code or message
7952 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
7953 */
7954 SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3*);
7955
7956 /*
7957 ** CAPI3REF: The pre-update hook.
7958 **
7959 ** ^These interfaces are only available if SQLite is compiled using the
7960 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
7961 **
7962 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
7963 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
7964 ** on a [rowid table].
7965 ** ^At most one preupdate hook may be registered at a time on a single
7966 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
7967 ** the previous setting.
7968 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
7969 ** with a NULL pointer as the second parameter.
7970 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
7971 ** the first parameter to callbacks.
7972 **
7973 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
7974 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
7975 ** tables.
7976 **
7977 ** ^The second parameter to the preupdate callback is a pointer to
7978 ** the [database connection] that registered the preupdate hook.
7979 ** ^The third parameter to the preupdate callback is one of the constants
7980 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to indentify the
7981 ** kind of update operation that is about to occur.
7982 ** ^(The fourth parameter to the preupdate callback is the name of the
7983 ** database within the database connection that is being modified. This
7984 ** will be "main" for the main database or "temp" for TEMP tables or
7985 ** the name given after the AS keyword in the [ATTACH] statement for attached
7986 ** databases.)^
7987 ** ^The fifth parameter to the preupdate callback is the name of the
7988 ** table that is being modified.
7989 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
7990 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
7991 ** undefined for SQLITE_INSERT changes.
7992 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
7993 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
7994 ** undefined for SQLITE_DELETE changes.
7995 **
7996 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
7997 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
7998 ** provide additional information about a preupdate event. These routines
7999 ** may only be called from within a preupdate callback. Invoking any of
8000 ** these routines from outside of a preupdate callback or with a
8001 ** [database connection] pointer that is different from the one supplied
8002 ** to the preupdate callback results in undefined and probably undesirable
8003 ** behavior.
8004 **
8005 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8006 ** in the row that is being inserted, updated, or deleted.
8007 **
8008 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8009 ** a [protected sqlite3_value] that contains the value of the Nth column of
8010 ** the table row before it is updated. The N parameter must be between 0
8011 ** and one less than the number of columns or the behavior will be
8012 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8013 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8014 ** behavior is undefined. The [sqlite3_value] that P points to
8015 ** will be destroyed when the preupdate callback returns.
8016 **
8017 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8018 ** a [protected sqlite3_value] that contains the value of the Nth column of
8019 ** the table row after it is updated. The N parameter must be between 0
8020 ** and one less than the number of columns or the behavior will be
8021 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8022 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8023 ** behavior is undefined. The [sqlite3_value] that P points to
8024 ** will be destroyed when the preupdate callback returns.
8025 **
8026 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8027 ** callback was invoked as a result of a direct insert, update, or delete
8028 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8029 ** triggers; or 2 for changes resulting from triggers called by top-level
8030 ** triggers; and so forth.
8031 **
8032 ** See also: [sqlite3_update_hook()]
8033 */
8034 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_preupdate_hook(
8035 sqlite3 *db,
8036 void(*xPreUpdate)(
8037 void *pCtx, /* Copy of third arg to preupdate_hook() */
8038 sqlite3 *db, /* Database handle */
8039 int op, /* SQLITE_UPDATE, DELETE or INSERT */
8040 char const *zDb, /* Database name */
8041 char const *zName, /* Table name */
8042 sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8043 sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8044 ),
8045 void*
8046 );
8047 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
8048 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *);
8049 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *);
8050 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
8051
8052 /*
8053 ** CAPI3REF: Low-level system error code
8054 **
8055 ** ^Attempt to return the underlying operating system error code or error
8056 ** number that caused the most recent I/O error or failure to open a file.
8057 ** The return value is OS-dependent. For example, on unix systems, after
8058 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8059 ** called to get back the underlying "errno" that caused the problem, such
8060 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8061 */
@@ -7983,24 +8117,33 @@
8117
8118 /*
8119 ** CAPI3REF: Start a read transaction on an historical snapshot
8120 ** EXPERIMENTAL
8121 **
8122 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8123 ** read transaction for schema S of
8124 ** [database connection] D such that the read transaction
8125 ** refers to historical [snapshot] P, rather than the most
8126 ** recent change to the database.
8127 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8128 ** or an appropriate [error code] if it fails.
8129 **
8130 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8131 ** the first operation following the [BEGIN] that takes the schema S
8132 ** out of [autocommit mode].
8133 ** ^In other words, schema S must not currently be in
8134 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8135 ** database connection D must be out of [autocommit mode].
8136 ** ^A [snapshot] will fail to open if it has been overwritten by a
8137 ** [checkpoint].
8138 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8139 ** database connection D does not know that the database file for
8140 ** schema S is in [WAL mode]. A database connection might not know
8141 ** that the database file is in [WAL mode] if there has been no prior
8142 ** I/O on that database connection, or if the database entered [WAL mode]
8143 ** after the most recent I/O on the database connection.)^
8144 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8145 ** database connection in order to make it ready to use snapshots.)
8146 **
8147 ** The [sqlite3_snapshot_open()] interface is only available when the
8148 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8149 */
@@ -8021,10 +8164,37 @@
8164 ** The [sqlite3_snapshot_free()] interface is only available when the
8165 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8166 */
8167 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot*);
8168
8169 /*
8170 ** CAPI3REF: Compare the ages of two snapshot handles.
8171 ** EXPERIMENTAL
8172 **
8173 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8174 ** of two valid snapshot handles.
8175 **
8176 ** If the two snapshot handles are not associated with the same database
8177 ** file, the result of the comparison is undefined.
8178 **
8179 ** Additionally, the result of the comparison is only valid if both of the
8180 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8181 ** last time the wal file was deleted. The wal file is deleted when the
8182 ** database is changed back to rollback mode or when the number of database
8183 ** clients drops to zero. If either snapshot handle was obtained before the
8184 ** wal file was last deleted, the value returned by this function
8185 ** is undefined.
8186 **
8187 ** Otherwise, this API returns a negative value if P1 refers to an older
8188 ** snapshot than P2, zero if the two handles refer to the same database
8189 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8190 */
8191 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(
8192 sqlite3_snapshot *p1,
8193 sqlite3_snapshot *p2
8194 );
8195
8196 /*
8197 ** Undo the hack that converts floating point types to integer for
8198 ** builds on processors without floating point support.
8199 */
8200 #ifdef SQLITE_OMIT_FLOATING_POINT
@@ -8034,10 +8204,11 @@
8204 #ifdef __cplusplus
8205 } /* End of the 'extern "C"' block */
8206 #endif
8207 #endif /* _SQLITE3_H_ */
8208
8209 /******** Begin file sqlite3rtree.h *********/
8210 /*
8211 ** 2010 August 30
8212 **
8213 ** The author disclaims copyright to this source code. In place of
8214 ** a legal notice, here is a blessing:
@@ -8151,10 +8322,1291 @@
8322 } /* end of the 'extern "C"' block */
8323 #endif
8324
8325 #endif /* ifndef _SQLITE3RTREE_H_ */
8326
8327 /******** End of sqlite3rtree.h *********/
8328 /******** Begin file sqlite3session.h *********/
8329
8330 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8331 #define __SQLITESESSION_H_ 1
8332
8333 /*
8334 ** Make sure we can call this stuff from C++.
8335 */
8336 #ifdef __cplusplus
8337 extern "C" {
8338 #endif
8339
8340
8341 /*
8342 ** CAPI3REF: Session Object Handle
8343 */
8344 typedef struct sqlite3_session sqlite3_session;
8345
8346 /*
8347 ** CAPI3REF: Changeset Iterator Handle
8348 */
8349 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8350
8351 /*
8352 ** CAPI3REF: Create A New Session Object
8353 **
8354 ** Create a new session object attached to database handle db. If successful,
8355 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8356 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8357 ** error code (e.g. SQLITE_NOMEM) is returned.
8358 **
8359 ** It is possible to create multiple session objects attached to a single
8360 ** database handle.
8361 **
8362 ** Session objects created using this function should be deleted using the
8363 ** [sqlite3session_delete()] function before the database handle that they
8364 ** are attached to is itself closed. If the database handle is closed before
8365 ** the session object is deleted, then the results of calling any session
8366 ** module function, including [sqlite3session_delete()] on the session object
8367 ** are undefined.
8368 **
8369 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8370 ** is not possible for an application to register a pre-update hook on a
8371 ** database handle that has one or more session objects attached. Nor is
8372 ** it possible to create a session object attached to a database handle for
8373 ** which a pre-update hook is already defined. The results of attempting
8374 ** either of these things are undefined.
8375 **
8376 ** The session object will be used to create changesets for tables in
8377 ** database zDb, where zDb is either "main", or "temp", or the name of an
8378 ** attached database. It is not an error if database zDb is not attached
8379 ** to the database when the session object is created.
8380 */
8381 int sqlite3session_create(
8382 sqlite3 *db, /* Database handle */
8383 const char *zDb, /* Name of db (e.g. "main") */
8384 sqlite3_session **ppSession /* OUT: New session object */
8385 );
8386
8387 /*
8388 ** CAPI3REF: Delete A Session Object
8389 **
8390 ** Delete a session object previously allocated using
8391 ** [sqlite3session_create()]. Once a session object has been deleted, the
8392 ** results of attempting to use pSession with any other session module
8393 ** function are undefined.
8394 **
8395 ** Session objects must be deleted before the database handle to which they
8396 ** are attached is closed. Refer to the documentation for
8397 ** [sqlite3session_create()] for details.
8398 */
8399 void sqlite3session_delete(sqlite3_session *pSession);
8400
8401
8402 /*
8403 ** CAPI3REF: Enable Or Disable A Session Object
8404 **
8405 ** Enable or disable the recording of changes by a session object. When
8406 ** enabled, a session object records changes made to the database. When
8407 ** disabled - it does not. A newly created session object is enabled.
8408 ** Refer to the documentation for [sqlite3session_changeset()] for further
8409 ** details regarding how enabling and disabling a session object affects
8410 ** the eventual changesets.
8411 **
8412 ** Passing zero to this function disables the session. Passing a value
8413 ** greater than zero enables it. Passing a value less than zero is a
8414 ** no-op, and may be used to query the current state of the session.
8415 **
8416 ** The return value indicates the final state of the session object: 0 if
8417 ** the session is disabled, or 1 if it is enabled.
8418 */
8419 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8420
8421 /*
8422 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8423 **
8424 ** Each change recorded by a session object is marked as either direct or
8425 ** indirect. A change is marked as indirect if either:
8426 **
8427 ** <ul>
8428 ** <li> The session object "indirect" flag is set when the change is
8429 ** made, or
8430 ** <li> The change is made by an SQL trigger or foreign key action
8431 ** instead of directly as a result of a users SQL statement.
8432 ** </ul>
8433 **
8434 ** If a single row is affected by more than one operation within a session,
8435 ** then the change is considered indirect if all operations meet the criteria
8436 ** for an indirect change above, or direct otherwise.
8437 **
8438 ** This function is used to set, clear or query the session object indirect
8439 ** flag. If the second argument passed to this function is zero, then the
8440 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8441 ** is set. Passing a value less than zero does not modify the current value
8442 ** of the indirect flag, and may be used to query the current state of the
8443 ** indirect flag for the specified session object.
8444 **
8445 ** The return value indicates the final state of the indirect flag: 0 if
8446 ** it is clear, or 1 if it is set.
8447 */
8448 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8449
8450 /*
8451 ** CAPI3REF: Attach A Table To A Session Object
8452 **
8453 ** If argument zTab is not NULL, then it is the name of a table to attach
8454 ** to the session object passed as the first argument. All subsequent changes
8455 ** made to the table while the session object is enabled will be recorded. See
8456 ** documentation for [sqlite3session_changeset()] for further details.
8457 **
8458 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8459 ** in the database. If additional tables are added to the database (by
8460 ** executing "CREATE TABLE" statements) after this call is made, changes for
8461 ** the new tables are also recorded.
8462 **
8463 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8464 ** defined as part of their CREATE TABLE statement. It does not matter if the
8465 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8466 ** KEY may consist of a single column, or may be a composite key.
8467 **
8468 ** It is not an error if the named table does not exist in the database. Nor
8469 ** is it an error if the named table does not have a PRIMARY KEY. However,
8470 ** no changes will be recorded in either of these scenarios.
8471 **
8472 ** Changes are not recorded for individual rows that have NULL values stored
8473 ** in one or more of their PRIMARY KEY columns.
8474 **
8475 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8476 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8477 */
8478 int sqlite3session_attach(
8479 sqlite3_session *pSession, /* Session object */
8480 const char *zTab /* Table name */
8481 );
8482
8483 /*
8484 ** CAPI3REF: Set a table filter on a Session Object.
8485 **
8486 ** The second argument (xFilter) is the "filter callback". For changes to rows
8487 ** in tables that are not attached to the Session oject, the filter is called
8488 ** to determine whether changes to the table's rows should be tracked or not.
8489 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8490 ** attached, xFilter will not be called again.
8491 */
8492 void sqlite3session_table_filter(
8493 sqlite3_session *pSession, /* Session object */
8494 int(*xFilter)(
8495 void *pCtx, /* Copy of third arg to _filter_table() */
8496 const char *zTab /* Table name */
8497 ),
8498 void *pCtx /* First argument passed to xFilter */
8499 );
8500
8501 /*
8502 ** CAPI3REF: Generate A Changeset From A Session Object
8503 **
8504 ** Obtain a changeset containing changes to the tables attached to the
8505 ** session object passed as the first argument. If successful,
8506 ** set *ppChangeset to point to a buffer containing the changeset
8507 ** and *pnChangeset to the size of the changeset in bytes before returning
8508 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8509 ** zero and return an SQLite error code.
8510 **
8511 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8512 ** each representing a change to a single row of an attached table. An INSERT
8513 ** change contains the values of each field of a new database row. A DELETE
8514 ** contains the original values of each field of a deleted database row. An
8515 ** UPDATE change contains the original values of each field of an updated
8516 ** database row along with the updated values for each updated non-primary-key
8517 ** column. It is not possible for an UPDATE change to represent a change that
8518 ** modifies the values of primary key columns. If such a change is made, it
8519 ** is represented in a changeset as a DELETE followed by an INSERT.
8520 **
8521 ** Changes are not recorded for rows that have NULL values stored in one or
8522 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8523 ** no corresponding change is present in the changesets returned by this
8524 ** function. If an existing row with one or more NULL values stored in
8525 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8526 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8527 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8528 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8529 ** DELETE change only.
8530 **
8531 ** The contents of a changeset may be traversed using an iterator created
8532 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8533 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8534 ** API.
8535 **
8536 ** Within a changeset generated by this function, all changes related to a
8537 ** single table are grouped together. In other words, when iterating through
8538 ** a changeset or when applying a changeset to a database, all changes related
8539 ** to a single table are processed before moving on to the next table. Tables
8540 ** are sorted in the same order in which they were attached (or auto-attached)
8541 ** to the sqlite3_session object. The order in which the changes related to
8542 ** a single table are stored is undefined.
8543 **
8544 ** Following a successful call to this function, it is the responsibility of
8545 ** the caller to eventually free the buffer that *ppChangeset points to using
8546 ** [sqlite3_free()].
8547 **
8548 ** <h3>Changeset Generation</h3>
8549 **
8550 ** Once a table has been attached to a session object, the session object
8551 ** records the primary key values of all new rows inserted into the table.
8552 ** It also records the original primary key and other column values of any
8553 ** deleted or updated rows. For each unique primary key value, data is only
8554 ** recorded once - the first time a row with said primary key is inserted,
8555 ** updated or deleted in the lifetime of the session.
8556 **
8557 ** There is one exception to the previous paragraph: when a row is inserted,
8558 ** updated or deleted, if one or more of its primary key columns contain a
8559 ** NULL value, no record of the change is made.
8560 **
8561 ** The session object therefore accumulates two types of records - those
8562 ** that consist of primary key values only (created when the user inserts
8563 ** a new record) and those that consist of the primary key values and the
8564 ** original values of other table columns (created when the users deletes
8565 ** or updates a record).
8566 **
8567 ** When this function is called, the requested changeset is created using
8568 ** both the accumulated records and the current contents of the database
8569 ** file. Specifically:
8570 **
8571 ** <ul>
8572 ** <li> For each record generated by an insert, the database is queried
8573 ** for a row with a matching primary key. If one is found, an INSERT
8574 ** change is added to the changeset. If no such row is found, no change
8575 ** is added to the changeset.
8576 **
8577 ** <li> For each record generated by an update or delete, the database is
8578 ** queried for a row with a matching primary key. If such a row is
8579 ** found and one or more of the non-primary key fields have been
8580 ** modified from their original values, an UPDATE change is added to
8581 ** the changeset. Or, if no such row is found in the table, a DELETE
8582 ** change is added to the changeset. If there is a row with a matching
8583 ** primary key in the database, but all fields contain their original
8584 ** values, no change is added to the changeset.
8585 ** </ul>
8586 **
8587 ** This means, amongst other things, that if a row is inserted and then later
8588 ** deleted while a session object is active, neither the insert nor the delete
8589 ** will be present in the changeset. Or if a row is deleted and then later a
8590 ** row with the same primary key values inserted while a session object is
8591 ** active, the resulting changeset will contain an UPDATE change instead of
8592 ** a DELETE and an INSERT.
8593 **
8594 ** When a session object is disabled (see the [sqlite3session_enable()] API),
8595 ** it does not accumulate records when rows are inserted, updated or deleted.
8596 ** This may appear to have some counter-intuitive effects if a single row
8597 ** is written to more than once during a session. For example, if a row
8598 ** is inserted while a session object is enabled, then later deleted while
8599 ** the same session object is disabled, no INSERT record will appear in the
8600 ** changeset, even though the delete took place while the session was disabled.
8601 ** Or, if one field of a row is updated while a session is disabled, and
8602 ** another field of the same row is updated while the session is enabled, the
8603 ** resulting changeset will contain an UPDATE change that updates both fields.
8604 */
8605 int sqlite3session_changeset(
8606 sqlite3_session *pSession, /* Session object */
8607 int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
8608 void **ppChangeset /* OUT: Buffer containing changeset */
8609 );
8610
8611 /*
8612 ** CAPI3REF: Load The Difference Between Tables Into A Session
8613 **
8614 ** If it is not already attached to the session object passed as the first
8615 ** argument, this function attaches table zTbl in the same manner as the
8616 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
8617 ** does not have a primary key, this function is a no-op (but does not return
8618 ** an error).
8619 **
8620 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
8621 ** attached to the same database handle as the session object that contains
8622 ** a table compatible with the table attached to the session by this function.
8623 ** A table is considered compatible if it:
8624 **
8625 ** <ul>
8626 ** <li> Has the same name,
8627 ** <li> Has the same set of columns declared in the same order, and
8628 ** <li> Has the same PRIMARY KEY definition.
8629 ** </ul>
8630 **
8631 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
8632 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
8633 ** but no changes are added to the session object. As with other session
8634 ** APIs, tables without PRIMARY KEYs are simply ignored.
8635 **
8636 ** This function adds a set of changes to the session object that could be
8637 ** used to update the table in database zFrom (call this the "from-table")
8638 ** so that its content is the same as the table attached to the session
8639 ** object (call this the "to-table"). Specifically:
8640 **
8641 ** <ul>
8642 ** <li> For each row (primary key) that exists in the to-table but not in
8643 ** the from-table, an INSERT record is added to the session object.
8644 **
8645 ** <li> For each row (primary key) that exists in the to-table but not in
8646 ** the from-table, a DELETE record is added to the session object.
8647 **
8648 ** <li> For each row (primary key) that exists in both tables, but features
8649 ** different in each, an UPDATE record is added to the session.
8650 ** </ul>
8651 **
8652 ** To clarify, if this function is called and then a changeset constructed
8653 ** using [sqlite3session_changeset()], then after applying that changeset to
8654 ** database zFrom the contents of the two compatible tables would be
8655 ** identical.
8656 **
8657 ** It an error if database zFrom does not exist or does not contain the
8658 ** required compatible table.
8659 **
8660 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
8661 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
8662 ** may be set to point to a buffer containing an English language error
8663 ** message. It is the responsibility of the caller to free this buffer using
8664 ** sqlite3_free().
8665 */
8666 int sqlite3session_diff(
8667 sqlite3_session *pSession,
8668 const char *zFromDb,
8669 const char *zTbl,
8670 char **pzErrMsg
8671 );
8672
8673
8674 /*
8675 ** CAPI3REF: Generate A Patchset From A Session Object
8676 **
8677 ** The differences between a patchset and a changeset are that:
8678 **
8679 ** <ul>
8680 ** <li> DELETE records consist of the primary key fields only. The
8681 ** original values of other fields are omitted.
8682 ** <li> The original values of any modified fields are omitted from
8683 ** UPDATE records.
8684 ** </ul>
8685 **
8686 ** A patchset blob may be used with up to date versions of all
8687 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
8688 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
8689 ** attempting to use a patchset blob with old versions of the
8690 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
8691 **
8692 ** Because the non-primary key "old.*" fields are omitted, no
8693 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
8694 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
8695 ** in the same way as for changesets.
8696 **
8697 ** Changes within a patchset are ordered in the same way as for changesets
8698 ** generated by the sqlite3session_changeset() function (i.e. all changes for
8699 ** a single table are grouped together, tables appear in the order in which
8700 ** they were attached to the session object).
8701 */
8702 int sqlite3session_patchset(
8703 sqlite3_session *pSession, /* Session object */
8704 int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
8705 void **ppPatchset /* OUT: Buffer containing changeset */
8706 );
8707
8708 /*
8709 ** CAPI3REF: Test if a changeset has recorded any changes.
8710 **
8711 ** Return non-zero if no changes to attached tables have been recorded by
8712 ** the session object passed as the first argument. Otherwise, if one or
8713 ** more changes have been recorded, return zero.
8714 **
8715 ** Even if this function returns zero, it is possible that calling
8716 ** [sqlite3session_changeset()] on the session handle may still return a
8717 ** changeset that contains no changes. This can happen when a row in
8718 ** an attached table is modified and then later on the original values
8719 ** are restored. However, if this function returns non-zero, then it is
8720 ** guaranteed that a call to sqlite3session_changeset() will return a
8721 ** changeset containing zero changes.
8722 */
8723 int sqlite3session_isempty(sqlite3_session *pSession);
8724
8725 /*
8726 ** CAPI3REF: Create An Iterator To Traverse A Changeset
8727 **
8728 ** Create an iterator used to iterate through the contents of a changeset.
8729 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
8730 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
8731 ** SQLite error code is returned.
8732 **
8733 ** The following functions can be used to advance and query a changeset
8734 ** iterator created by this function:
8735 **
8736 ** <ul>
8737 ** <li> [sqlite3changeset_next()]
8738 ** <li> [sqlite3changeset_op()]
8739 ** <li> [sqlite3changeset_new()]
8740 ** <li> [sqlite3changeset_old()]
8741 ** </ul>
8742 **
8743 ** It is the responsibility of the caller to eventually destroy the iterator
8744 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
8745 ** changeset (pChangeset) must remain valid until after the iterator is
8746 ** destroyed.
8747 **
8748 ** Assuming the changeset blob was created by one of the
8749 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
8750 ** [sqlite3changeset_invert()] functions, all changes within the changeset
8751 ** that apply to a single table are grouped together. This means that when
8752 ** an application iterates through a changeset using an iterator created by
8753 ** this function, all changes that relate to a single table are visted
8754 ** consecutively. There is no chance that the iterator will visit a change
8755 ** the applies to table X, then one for table Y, and then later on visit
8756 ** another change for table X.
8757 */
8758 int sqlite3changeset_start(
8759 sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
8760 int nChangeset, /* Size of changeset blob in bytes */
8761 void *pChangeset /* Pointer to blob containing changeset */
8762 );
8763
8764
8765 /*
8766 ** CAPI3REF: Advance A Changeset Iterator
8767 **
8768 ** This function may only be used with iterators created by function
8769 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
8770 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
8771 ** is returned and the call has no effect.
8772 **
8773 ** Immediately after an iterator is created by sqlite3changeset_start(), it
8774 ** does not point to any change in the changeset. Assuming the changeset
8775 ** is not empty, the first call to this function advances the iterator to
8776 ** point to the first change in the changeset. Each subsequent call advances
8777 ** the iterator to point to the next change in the changeset (if any). If
8778 ** no error occurs and the iterator points to a valid change after a call
8779 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
8780 ** Otherwise, if all changes in the changeset have already been visited,
8781 ** SQLITE_DONE is returned.
8782 **
8783 ** If an error occurs, an SQLite error code is returned. Possible error
8784 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
8785 ** SQLITE_NOMEM.
8786 */
8787 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
8788
8789 /*
8790 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
8791 **
8792 ** The pIter argument passed to this function may either be an iterator
8793 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8794 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
8795 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
8796 ** is not the case, this function returns [SQLITE_MISUSE].
8797 **
8798 ** If argument pzTab is not NULL, then *pzTab is set to point to a
8799 ** nul-terminated utf-8 encoded string containing the name of the table
8800 ** affected by the current change. The buffer remains valid until either
8801 ** sqlite3changeset_next() is called on the iterator or until the
8802 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
8803 ** set to the number of columns in the table affected by the change. If
8804 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
8805 ** is an indirect change, or false (0) otherwise. See the documentation for
8806 ** [sqlite3session_indirect()] for a description of direct and indirect
8807 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
8808 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
8809 ** type of change that the iterator currently points to.
8810 **
8811 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
8812 ** SQLite error code is returned. The values of the output variables may not
8813 ** be trusted in this case.
8814 */
8815 int sqlite3changeset_op(
8816 sqlite3_changeset_iter *pIter, /* Iterator object */
8817 const char **pzTab, /* OUT: Pointer to table name */
8818 int *pnCol, /* OUT: Number of columns in table */
8819 int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
8820 int *pbIndirect /* OUT: True for an 'indirect' change */
8821 );
8822
8823 /*
8824 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
8825 **
8826 ** For each modified table, a changeset includes the following:
8827 **
8828 ** <ul>
8829 ** <li> The number of columns in the table, and
8830 ** <li> Which of those columns make up the tables PRIMARY KEY.
8831 ** </ul>
8832 **
8833 ** This function is used to find which columns comprise the PRIMARY KEY of
8834 ** the table modified by the change that iterator pIter currently points to.
8835 ** If successful, *pabPK is set to point to an array of nCol entries, where
8836 ** nCol is the number of columns in the table. Elements of *pabPK are set to
8837 ** 0x01 if the corresponding column is part of the tables primary key, or
8838 ** 0x00 if it is not.
8839 **
8840 ** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
8841 ** in the table.
8842 **
8843 ** If this function is called when the iterator does not point to a valid
8844 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
8845 ** SQLITE_OK is returned and the output variables populated as described
8846 ** above.
8847 */
8848 int sqlite3changeset_pk(
8849 sqlite3_changeset_iter *pIter, /* Iterator object */
8850 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
8851 int *pnCol /* OUT: Number of entries in output array */
8852 );
8853
8854 /*
8855 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
8856 **
8857 ** The pIter argument passed to this function may either be an iterator
8858 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8859 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
8860 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
8861 ** Furthermore, it may only be called if the type of change that the iterator
8862 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
8863 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
8864 **
8865 ** Argument iVal must be greater than or equal to 0, and less than the number
8866 ** of columns in the table affected by the current change. Otherwise,
8867 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8868 **
8869 ** If successful, this function sets *ppValue to point to a protected
8870 ** sqlite3_value object containing the iVal'th value from the vector of
8871 ** original row values stored as part of the UPDATE or DELETE change and
8872 ** returns SQLITE_OK. The name of the function comes from the fact that this
8873 ** is similar to the "old.*" columns available to update or delete triggers.
8874 **
8875 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
8876 ** is returned and *ppValue is set to NULL.
8877 */
8878 int sqlite3changeset_old(
8879 sqlite3_changeset_iter *pIter, /* Changeset iterator */
8880 int iVal, /* Column number */
8881 sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
8882 );
8883
8884 /*
8885 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
8886 **
8887 ** The pIter argument passed to this function may either be an iterator
8888 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
8889 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
8890 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
8891 ** Furthermore, it may only be called if the type of change that the iterator
8892 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
8893 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
8894 **
8895 ** Argument iVal must be greater than or equal to 0, and less than the number
8896 ** of columns in the table affected by the current change. Otherwise,
8897 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8898 **
8899 ** If successful, this function sets *ppValue to point to a protected
8900 ** sqlite3_value object containing the iVal'th value from the vector of
8901 ** new row values stored as part of the UPDATE or INSERT change and
8902 ** returns SQLITE_OK. If the change is an UPDATE and does not include
8903 ** a new value for the requested column, *ppValue is set to NULL and
8904 ** SQLITE_OK returned. The name of the function comes from the fact that
8905 ** this is similar to the "new.*" columns available to update or delete
8906 ** triggers.
8907 **
8908 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
8909 ** is returned and *ppValue is set to NULL.
8910 */
8911 int sqlite3changeset_new(
8912 sqlite3_changeset_iter *pIter, /* Changeset iterator */
8913 int iVal, /* Column number */
8914 sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
8915 );
8916
8917 /*
8918 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
8919 **
8920 ** This function should only be used with iterator objects passed to a
8921 ** conflict-handler callback by [sqlite3changeset_apply()] with either
8922 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
8923 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
8924 ** is set to NULL.
8925 **
8926 ** Argument iVal must be greater than or equal to 0, and less than the number
8927 ** of columns in the table affected by the current change. Otherwise,
8928 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
8929 **
8930 ** If successful, this function sets *ppValue to point to a protected
8931 ** sqlite3_value object containing the iVal'th value from the
8932 ** "conflicting row" associated with the current conflict-handler callback
8933 ** and returns SQLITE_OK.
8934 **
8935 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
8936 ** is returned and *ppValue is set to NULL.
8937 */
8938 int sqlite3changeset_conflict(
8939 sqlite3_changeset_iter *pIter, /* Changeset iterator */
8940 int iVal, /* Column number */
8941 sqlite3_value **ppValue /* OUT: Value from conflicting row */
8942 );
8943
8944 /*
8945 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
8946 **
8947 ** This function may only be called with an iterator passed to an
8948 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
8949 ** it sets the output variable to the total number of known foreign key
8950 ** violations in the destination database and returns SQLITE_OK.
8951 **
8952 ** In all other cases this function returns SQLITE_MISUSE.
8953 */
8954 int sqlite3changeset_fk_conflicts(
8955 sqlite3_changeset_iter *pIter, /* Changeset iterator */
8956 int *pnOut /* OUT: Number of FK violations */
8957 );
8958
8959
8960 /*
8961 ** CAPI3REF: Finalize A Changeset Iterator
8962 **
8963 ** This function is used to finalize an iterator allocated with
8964 ** [sqlite3changeset_start()].
8965 **
8966 ** This function should only be called on iterators created using the
8967 ** [sqlite3changeset_start()] function. If an application calls this
8968 ** function with an iterator passed to a conflict-handler by
8969 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
8970 ** call has no effect.
8971 **
8972 ** If an error was encountered within a call to an sqlite3changeset_xxx()
8973 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
8974 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
8975 ** to that error is returned by this function. Otherwise, SQLITE_OK is
8976 ** returned. This is to allow the following pattern (pseudo-code):
8977 **
8978 ** sqlite3changeset_start();
8979 ** while( SQLITE_ROW==sqlite3changeset_next() ){
8980 ** // Do something with change.
8981 ** }
8982 ** rc = sqlite3changeset_finalize();
8983 ** if( rc!=SQLITE_OK ){
8984 ** // An error has occurred
8985 ** }
8986 */
8987 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
8988
8989 /*
8990 ** CAPI3REF: Invert A Changeset
8991 **
8992 ** This function is used to "invert" a changeset object. Applying an inverted
8993 ** changeset to a database reverses the effects of applying the uninverted
8994 ** changeset. Specifically:
8995 **
8996 ** <ul>
8997 ** <li> Each DELETE change is changed to an INSERT, and
8998 ** <li> Each INSERT change is changed to a DELETE, and
8999 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9000 ** </ul>
9001 **
9002 ** This function does not change the order in which changes appear within
9003 ** the changeset. It merely reverses the sense of each individual change.
9004 **
9005 ** If successful, a pointer to a buffer containing the inverted changeset
9006 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9007 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9008 ** zeroed and an SQLite error code returned.
9009 **
9010 ** It is the responsibility of the caller to eventually call sqlite3_free()
9011 ** on the *ppOut pointer to free the buffer allocation following a successful
9012 ** call to this function.
9013 **
9014 ** WARNING/TODO: This function currently assumes that the input is a valid
9015 ** changeset. If it is not, the results are undefined.
9016 */
9017 int sqlite3changeset_invert(
9018 int nIn, const void *pIn, /* Input changeset */
9019 int *pnOut, void **ppOut /* OUT: Inverse of input */
9020 );
9021
9022 /*
9023 ** CAPI3REF: Concatenate Two Changeset Objects
9024 **
9025 ** This function is used to concatenate two changesets, A and B, into a
9026 ** single changeset. The result is a changeset equivalent to applying
9027 ** changeset A followed by changeset B.
9028 **
9029 ** This function combines the two input changesets using an
9030 ** sqlite3_changegroup object. Calling it produces similar results as the
9031 ** following code fragment:
9032 **
9033 ** sqlite3_changegroup *pGrp;
9034 ** rc = sqlite3_changegroup_new(&pGrp);
9035 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9036 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9037 ** if( rc==SQLITE_OK ){
9038 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9039 ** }else{
9040 ** *ppOut = 0;
9041 ** *pnOut = 0;
9042 ** }
9043 **
9044 ** Refer to the sqlite3_changegroup documentation below for details.
9045 */
9046 int sqlite3changeset_concat(
9047 int nA, /* Number of bytes in buffer pA */
9048 void *pA, /* Pointer to buffer containing changeset A */
9049 int nB, /* Number of bytes in buffer pB */
9050 void *pB, /* Pointer to buffer containing changeset B */
9051 int *pnOut, /* OUT: Number of bytes in output changeset */
9052 void **ppOut /* OUT: Buffer containing output changeset */
9053 );
9054
9055
9056 /*
9057 ** Changegroup handle.
9058 */
9059 typedef struct sqlite3_changegroup sqlite3_changegroup;
9060
9061 /*
9062 ** CAPI3REF: Combine two or more changesets into a single changeset.
9063 **
9064 ** An sqlite3_changegroup object is used to combine two or more changesets
9065 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9066 ** object may combine changesets or patchsets, but not both. The output is
9067 ** always in the same format as the input.
9068 **
9069 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9070 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9071 ** should eventually free the returned object using a call to
9072 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9073 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9074 **
9075 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9076 **
9077 ** <ul>
9078 ** <li> It is created using a call to sqlite3changegroup_new().
9079 **
9080 ** <li> Zero or more changesets (or patchsets) are added to the object
9081 ** by calling sqlite3changegroup_add().
9082 **
9083 ** <li> The result of combining all input changesets together is obtained
9084 ** by the application via a call to sqlite3changegroup_output().
9085 **
9086 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9087 ** </ul>
9088 **
9089 ** Any number of calls to add() and output() may be made between the calls to
9090 ** new() and delete(), and in any order.
9091 **
9092 ** As well as the regular sqlite3changegroup_add() and
9093 ** sqlite3changegroup_output() functions, also available are the streaming
9094 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9095 */
9096 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9097
9098 /*
9099 ** Add all changes within the changeset (or patchset) in buffer pData (size
9100 ** nData bytes) to the changegroup.
9101 **
9102 ** If the buffer contains a patchset, then all prior calls to this function
9103 ** on the same changegroup object must also have specified patchsets. Or, if
9104 ** the buffer contains a changeset, so must have the earlier calls to this
9105 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9106 ** to the changegroup.
9107 **
9108 ** Rows within the changeset and changegroup are identified by the values in
9109 ** their PRIMARY KEY columns. A change in the changeset is considered to
9110 ** apply to the same row as a change already present in the changegroup if
9111 ** the two rows have the same primary key.
9112 **
9113 ** Changes to rows that that do not already appear in the changegroup are
9114 ** simply copied into it. Or, if both the new changeset and the changegroup
9115 ** contain changes that apply to a single row, the final contents of the
9116 ** changegroup depends on the type of each change, as follows:
9117 **
9118 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9119 ** <tr><th style="white-space:pre">Existing Change </th>
9120 ** <th style="white-space:pre">New Change </th>
9121 ** <th>Output Change
9122 ** <tr><td>INSERT <td>INSERT <td>
9123 ** The new change is ignored. This case does not occur if the new
9124 ** changeset was recorded immediately after the changesets already
9125 ** added to the changegroup.
9126 ** <tr><td>INSERT <td>UPDATE <td>
9127 ** The INSERT change remains in the changegroup. The values in the
9128 ** INSERT change are modified as if the row was inserted by the
9129 ** existing change and then updated according to the new change.
9130 ** <tr><td>INSERT <td>DELETE <td>
9131 ** The existing INSERT is removed from the changegroup. The DELETE is
9132 ** not added.
9133 ** <tr><td>UPDATE <td>INSERT <td>
9134 ** The new change is ignored. This case does not occur if the new
9135 ** changeset was recorded immediately after the changesets already
9136 ** added to the changegroup.
9137 ** <tr><td>UPDATE <td>UPDATE <td>
9138 ** The existing UPDATE remains within the changegroup. It is amended
9139 ** so that the accompanying values are as if the row was updated once
9140 ** by the existing change and then again by the new change.
9141 ** <tr><td>UPDATE <td>DELETE <td>
9142 ** The existing UPDATE is replaced by the new DELETE within the
9143 ** changegroup.
9144 ** <tr><td>DELETE <td>INSERT <td>
9145 ** If one or more of the column values in the row inserted by the
9146 ** new change differ from those in the row deleted by the existing
9147 ** change, the existing DELETE is replaced by an UPDATE within the
9148 ** changegroup. Otherwise, if the inserted row is exactly the same
9149 ** as the deleted row, the existing DELETE is simply discarded.
9150 ** <tr><td>DELETE <td>UPDATE <td>
9151 ** The new change is ignored. This case does not occur if the new
9152 ** changeset was recorded immediately after the changesets already
9153 ** added to the changegroup.
9154 ** <tr><td>DELETE <td>DELETE <td>
9155 ** The new change is ignored. This case does not occur if the new
9156 ** changeset was recorded immediately after the changesets already
9157 ** added to the changegroup.
9158 ** </table>
9159 **
9160 ** If the new changeset contains changes to a table that is already present
9161 ** in the changegroup, then the number of columns and the position of the
9162 ** primary key columns for the table must be consistent. If this is not the
9163 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9164 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9165 ** returned. Or, if an out-of-memory condition occurs during processing, this
9166 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9167 ** final contents of the changegroup is undefined.
9168 **
9169 ** If no error occurs, SQLITE_OK is returned.
9170 */
9171 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9172
9173 /*
9174 ** Obtain a buffer containing a changeset (or patchset) representing the
9175 ** current contents of the changegroup. If the inputs to the changegroup
9176 ** were themselves changesets, the output is a changeset. Or, if the
9177 ** inputs were patchsets, the output is also a patchset.
9178 **
9179 ** As with the output of the sqlite3session_changeset() and
9180 ** sqlite3session_patchset() functions, all changes related to a single
9181 ** table are grouped together in the output of this function. Tables appear
9182 ** in the same order as for the very first changeset added to the changegroup.
9183 ** If the second or subsequent changesets added to the changegroup contain
9184 ** changes for tables that do not appear in the first changeset, they are
9185 ** appended onto the end of the output changeset, again in the order in
9186 ** which they are first encountered.
9187 **
9188 ** If an error occurs, an SQLite error code is returned and the output
9189 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9190 ** is returned and the output variables are set to the size of and a
9191 ** pointer to the output buffer, respectively. In this case it is the
9192 ** responsibility of the caller to eventually free the buffer using a
9193 ** call to sqlite3_free().
9194 */
9195 int sqlite3changegroup_output(
9196 sqlite3_changegroup*,
9197 int *pnData, /* OUT: Size of output buffer in bytes */
9198 void **ppData /* OUT: Pointer to output buffer */
9199 );
9200
9201 /*
9202 ** Delete a changegroup object.
9203 */
9204 void sqlite3changegroup_delete(sqlite3_changegroup*);
9205
9206 /*
9207 ** CAPI3REF: Apply A Changeset To A Database
9208 **
9209 ** Apply a changeset to a database. This function attempts to update the
9210 ** "main" database attached to handle db with the changes found in the
9211 ** changeset passed via the second and third arguments.
9212 **
9213 ** The fourth argument (xFilter) passed to this function is the "filter
9214 ** callback". If it is not NULL, then for each table affected by at least one
9215 ** change in the changeset, the filter callback is invoked with
9216 ** the table name as the second argument, and a copy of the context pointer
9217 ** passed as the sixth argument to this function as the first. If the "filter
9218 ** callback" returns zero, then no attempt is made to apply any changes to
9219 ** the table. Otherwise, if the return value is non-zero or the xFilter
9220 ** argument to this function is NULL, all changes related to the table are
9221 ** attempted.
9222 **
9223 ** For each table that is not excluded by the filter callback, this function
9224 ** tests that the target database contains a compatible table. A table is
9225 ** considered compatible if all of the following are true:
9226 **
9227 ** <ul>
9228 ** <li> The table has the same name as the name recorded in the
9229 ** changeset, and
9230 ** <li> The table has the same number of columns as recorded in the
9231 ** changeset, and
9232 ** <li> The table has primary key columns in the same position as
9233 ** recorded in the changeset.
9234 ** </ul>
9235 **
9236 ** If there is no compatible table, it is not an error, but none of the
9237 ** changes associated with the table are applied. A warning message is issued
9238 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9239 ** one such warning is issued for each table in the changeset.
9240 **
9241 ** For each change for which there is a compatible table, an attempt is made
9242 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9243 ** change. If a change cannot be applied cleanly, the conflict handler
9244 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9245 ** invoked. A description of exactly when the conflict handler is invoked for
9246 ** each type of change is below.
9247 **
9248 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9249 ** of passing anything other than a valid function pointer as the xConflict
9250 ** argument are undefined.
9251 **
9252 ** Each time the conflict handler function is invoked, it must return one
9253 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9254 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9255 ** if the second argument passed to the conflict handler is either
9256 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9257 ** returns an illegal value, any changes already made are rolled back and
9258 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9259 ** actions are taken by sqlite3changeset_apply() depending on the value
9260 ** returned by each invocation of the conflict-handler function. Refer to
9261 ** the documentation for the three
9262 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9263 **
9264 ** <dl>
9265 ** <dt>DELETE Changes<dd>
9266 ** For each DELETE change, this function checks if the target database
9267 ** contains a row with the same primary key value (or values) as the
9268 ** original row values stored in the changeset. If it does, and the values
9269 ** stored in all non-primary key columns also match the values stored in
9270 ** the changeset the row is deleted from the target database.
9271 **
9272 ** If a row with matching primary key values is found, but one or more of
9273 ** the non-primary key fields contains a value different from the original
9274 ** row value stored in the changeset, the conflict-handler function is
9275 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9276 **
9277 ** If no row with matching primary key values is found in the database,
9278 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9279 ** passed as the second argument.
9280 **
9281 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9282 ** (which can only happen if a foreign key constraint is violated), the
9283 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9284 ** passed as the second argument. This includes the case where the DELETE
9285 ** operation is attempted because an earlier call to the conflict handler
9286 ** function returned [SQLITE_CHANGESET_REPLACE].
9287 **
9288 ** <dt>INSERT Changes<dd>
9289 ** For each INSERT change, an attempt is made to insert the new row into
9290 ** the database.
9291 **
9292 ** If the attempt to insert the row fails because the database already
9293 ** contains a row with the same primary key values, the conflict handler
9294 ** function is invoked with the second argument set to
9295 ** [SQLITE_CHANGESET_CONFLICT].
9296 **
9297 ** If the attempt to insert the row fails because of some other constraint
9298 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9299 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9300 ** This includes the case where the INSERT operation is re-attempted because
9301 ** an earlier call to the conflict handler function returned
9302 ** [SQLITE_CHANGESET_REPLACE].
9303 **
9304 ** <dt>UPDATE Changes<dd>
9305 ** For each UPDATE change, this function checks if the target database
9306 ** contains a row with the same primary key value (or values) as the
9307 ** original row values stored in the changeset. If it does, and the values
9308 ** stored in all non-primary key columns also match the values stored in
9309 ** the changeset the row is updated within the target database.
9310 **
9311 ** If a row with matching primary key values is found, but one or more of
9312 ** the non-primary key fields contains a value different from an original
9313 ** row value stored in the changeset, the conflict-handler function is
9314 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9315 ** UPDATE changes only contain values for non-primary key fields that are
9316 ** to be modified, only those fields need to match the original values to
9317 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9318 **
9319 ** If no row with matching primary key values is found in the database,
9320 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9321 ** passed as the second argument.
9322 **
9323 ** If the UPDATE operation is attempted, but SQLite returns
9324 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9325 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9326 ** This includes the case where the UPDATE operation is attempted after
9327 ** an earlier call to the conflict handler function returned
9328 ** [SQLITE_CHANGESET_REPLACE].
9329 ** </dl>
9330 **
9331 ** It is safe to execute SQL statements, including those that write to the
9332 ** table that the callback related to, from within the xConflict callback.
9333 ** This can be used to further customize the applications conflict
9334 ** resolution strategy.
9335 **
9336 ** All changes made by this function are enclosed in a savepoint transaction.
9337 ** If any other error (aside from a constraint failure when attempting to
9338 ** write to the target database) occurs, then the savepoint transaction is
9339 ** rolled back, restoring the target database to its original state, and an
9340 ** SQLite error code returned.
9341 */
9342 int sqlite3changeset_apply(
9343 sqlite3 *db, /* Apply change to "main" db of this handle */
9344 int nChangeset, /* Size of changeset in bytes */
9345 void *pChangeset, /* Changeset blob */
9346 int(*xFilter)(
9347 void *pCtx, /* Copy of sixth arg to _apply() */
9348 const char *zTab /* Table name */
9349 ),
9350 int(*xConflict)(
9351 void *pCtx, /* Copy of sixth arg to _apply() */
9352 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9353 sqlite3_changeset_iter *p /* Handle describing change and conflict */
9354 ),
9355 void *pCtx /* First argument passed to xConflict */
9356 );
9357
9358 /*
9359 ** CAPI3REF: Constants Passed To The Conflict Handler
9360 **
9361 ** Values that may be passed as the second argument to a conflict-handler.
9362 **
9363 ** <dl>
9364 ** <dt>SQLITE_CHANGESET_DATA<dd>
9365 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9366 ** when processing a DELETE or UPDATE change if a row with the required
9367 ** PRIMARY KEY fields is present in the database, but one or more other
9368 ** (non primary-key) fields modified by the update do not contain the
9369 ** expected "before" values.
9370 **
9371 ** The conflicting row, in this case, is the database row with the matching
9372 ** primary key.
9373 **
9374 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9375 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9376 ** argument when processing a DELETE or UPDATE change if a row with the
9377 ** required PRIMARY KEY fields is not present in the database.
9378 **
9379 ** There is no conflicting row in this case. The results of invoking the
9380 ** sqlite3changeset_conflict() API are undefined.
9381 **
9382 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9383 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9384 ** handler while processing an INSERT change if the operation would result
9385 ** in duplicate primary key values.
9386 **
9387 ** The conflicting row in this case is the database row with the matching
9388 ** primary key.
9389 **
9390 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9391 ** If foreign key handling is enabled, and applying a changeset leaves the
9392 ** database in a state containing foreign key violations, the conflict
9393 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9394 ** exactly once before the changeset is committed. If the conflict handler
9395 ** returns CHANGESET_OMIT, the changes, including those that caused the
9396 ** foreign key constraint violation, are committed. Or, if it returns
9397 ** CHANGESET_ABORT, the changeset is rolled back.
9398 **
9399 ** No current or conflicting row information is provided. The only function
9400 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9401 ** is sqlite3changeset_fk_conflicts().
9402 **
9403 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9404 ** If any other constraint violation occurs while applying a change (i.e.
9405 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9406 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9407 **
9408 ** There is no conflicting row in this case. The results of invoking the
9409 ** sqlite3changeset_conflict() API are undefined.
9410 **
9411 ** </dl>
9412 */
9413 #define SQLITE_CHANGESET_DATA 1
9414 #define SQLITE_CHANGESET_NOTFOUND 2
9415 #define SQLITE_CHANGESET_CONFLICT 3
9416 #define SQLITE_CHANGESET_CONSTRAINT 4
9417 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9418
9419 /*
9420 ** CAPI3REF: Constants Returned By The Conflict Handler
9421 **
9422 ** A conflict handler callback must return one of the following three values.
9423 **
9424 ** <dl>
9425 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9426 ** If a conflict handler returns this value no special action is taken. The
9427 ** change that caused the conflict is not applied. The session module
9428 ** continues to the next change in the changeset.
9429 **
9430 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9431 ** This value may only be returned if the second argument to the conflict
9432 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9433 ** is not the case, any changes applied so far are rolled back and the
9434 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9435 **
9436 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9437 ** handler, then the conflicting row is either updated or deleted, depending
9438 ** on the type of change.
9439 **
9440 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9441 ** handler, then the conflicting row is removed from the database and a
9442 ** second attempt to apply the change is made. If this second attempt fails,
9443 ** the original row is restored to the database before continuing.
9444 **
9445 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9446 ** If this value is returned, any changes applied so far are rolled back
9447 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9448 ** </dl>
9449 */
9450 #define SQLITE_CHANGESET_OMIT 0
9451 #define SQLITE_CHANGESET_REPLACE 1
9452 #define SQLITE_CHANGESET_ABORT 2
9453
9454 /*
9455 ** CAPI3REF: Streaming Versions of API functions.
9456 **
9457 ** The six streaming API xxx_strm() functions serve similar purposes to the
9458 ** corresponding non-streaming API functions:
9459 **
9460 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9461 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9462 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9463 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9464 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9465 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9466 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9467 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9468 ** </table>
9469 **
9470 ** Non-streaming functions that accept changesets (or patchsets) as input
9471 ** require that the entire changeset be stored in a single buffer in memory.
9472 ** Similarly, those that return a changeset or patchset do so by returning
9473 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9474 ** Normally this is convenient. However, if an application running in a
9475 ** low-memory environment is required to handle very large changesets, the
9476 ** large contiguous memory allocations required can become onerous.
9477 **
9478 ** In order to avoid this problem, instead of a single large buffer, input
9479 ** is passed to a streaming API functions by way of a callback function that
9480 ** the sessions module invokes to incrementally request input data as it is
9481 ** required. In all cases, a pair of API function parameters such as
9482 **
9483 ** <pre>
9484 ** &nbsp; int nChangeset,
9485 ** &nbsp; void *pChangeset,
9486 ** </pre>
9487 **
9488 ** Is replaced by:
9489 **
9490 ** <pre>
9491 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9492 ** &nbsp; void *pIn,
9493 ** </pre>
9494 **
9495 ** Each time the xInput callback is invoked by the sessions module, the first
9496 ** argument passed is a copy of the supplied pIn context pointer. The second
9497 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9498 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9499 ** into the buffer and set (*pnData) to the actual number of bytes copied
9500 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9501 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9502 ** error code should be returned. In all cases, if an xInput callback returns
9503 ** an error, all processing is abandoned and the streaming API function
9504 ** returns a copy of the error code to the caller.
9505 **
9506 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9507 ** invoked by the sessions module at any point during the lifetime of the
9508 ** iterator. If such an xInput callback returns an error, the iterator enters
9509 ** an error state, whereby all subsequent calls to iterator functions
9510 ** immediately fail with the same error code as returned by xInput.
9511 **
9512 ** Similarly, streaming API functions that return changesets (or patchsets)
9513 ** return them in chunks by way of a callback function instead of via a
9514 ** pointer to a single large buffer. In this case, a pair of parameters such
9515 ** as:
9516 **
9517 ** <pre>
9518 ** &nbsp; int *pnChangeset,
9519 ** &nbsp; void **ppChangeset,
9520 ** </pre>
9521 **
9522 ** Is replaced by:
9523 **
9524 ** <pre>
9525 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9526 ** &nbsp; void *pOut
9527 ** </pre>
9528 **
9529 ** The xOutput callback is invoked zero or more times to return data to
9530 ** the application. The first parameter passed to each call is a copy of the
9531 ** pOut pointer supplied by the application. The second parameter, pData,
9532 ** points to a buffer nData bytes in size containing the chunk of output
9533 ** data being returned. If the xOutput callback successfully processes the
9534 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9535 ** it should return some other SQLite error code. In this case processing
9536 ** is immediately abandoned and the streaming API function returns a copy
9537 ** of the xOutput error code to the application.
9538 **
9539 ** The sessions module never invokes an xOutput callback with the third
9540 ** parameter set to a value less than or equal to zero. Other than this,
9541 ** no guarantees are made as to the size of the chunks of data returned.
9542 */
9543 int sqlite3changeset_apply_strm(
9544 sqlite3 *db, /* Apply change to "main" db of this handle */
9545 int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9546 void *pIn, /* First arg for xInput */
9547 int(*xFilter)(
9548 void *pCtx, /* Copy of sixth arg to _apply() */
9549 const char *zTab /* Table name */
9550 ),
9551 int(*xConflict)(
9552 void *pCtx, /* Copy of sixth arg to _apply() */
9553 int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9554 sqlite3_changeset_iter *p /* Handle describing change and conflict */
9555 ),
9556 void *pCtx /* First argument passed to xConflict */
9557 );
9558 int sqlite3changeset_concat_strm(
9559 int (*xInputA)(void *pIn, void *pData, int *pnData),
9560 void *pInA,
9561 int (*xInputB)(void *pIn, void *pData, int *pnData),
9562 void *pInB,
9563 int (*xOutput)(void *pOut, const void *pData, int nData),
9564 void *pOut
9565 );
9566 int sqlite3changeset_invert_strm(
9567 int (*xInput)(void *pIn, void *pData, int *pnData),
9568 void *pIn,
9569 int (*xOutput)(void *pOut, const void *pData, int nData),
9570 void *pOut
9571 );
9572 int sqlite3changeset_start_strm(
9573 sqlite3_changeset_iter **pp,
9574 int (*xInput)(void *pIn, void *pData, int *pnData),
9575 void *pIn
9576 );
9577 int sqlite3session_changeset_strm(
9578 sqlite3_session *pSession,
9579 int (*xOutput)(void *pOut, const void *pData, int nData),
9580 void *pOut
9581 );
9582 int sqlite3session_patchset_strm(
9583 sqlite3_session *pSession,
9584 int (*xOutput)(void *pOut, const void *pData, int nData),
9585 void *pOut
9586 );
9587 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
9588 int (*xInput)(void *pIn, void *pData, int *pnData),
9589 void *pIn
9590 );
9591 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
9592 int (*xOutput)(void *pOut, const void *pData, int nData),
9593 void *pOut
9594 );
9595
9596
9597 /*
9598 ** Make sure we can call this stuff from C++.
9599 */
9600 #ifdef __cplusplus
9601 }
9602 #endif
9603
9604 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
9605
9606 /******** End of sqlite3session.h *********/
9607 /******** Begin file fts5.h *********/
9608 /*
9609 ** 2014 May 31
9610 **
9611 ** The author disclaims copyright to this source code. In place of
9612 ** a legal notice, here is a blessing:
@@ -8295,15 +9747,17 @@
9747 ** of the current query. Specifically, a query equivalent to:
9748 **
9749 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
9750 **
9751 ** with $p set to a phrase equivalent to the phrase iPhrase of the
9752 ** current query is executed. Any column filter that applies to
9753 ** phrase iPhrase of the current query is included in $p. For each
9754 ** row visited, the callback function passed as the fourth argument
9755 ** is invoked. The context and API objects passed to the callback
9756 ** function may be used to access the properties of each matched row.
9757 ** Invoking Api.xUserData() returns a copy of the pointer passed as
9758 ** the third argument to pUserData.
9759 **
9760 ** If the callback function returns any value other than SQLITE_OK, the
9761 ** query is abandoned and the xQueryPhrase function returns immediately.
9762 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
9763 ** Otherwise, the error code is propagated upwards.
@@ -8729,5 +10183,6 @@
10183 #endif
10184
10185 #endif /* _FTS5_H */
10186
10187
10188 /******** End of fts5.h *********/
10189

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button