Fossil SCM

merge trunk

wolfgang 2010-09-29 14:11 wolfgangFormat2CSS_2 merge
Commit e410d40b1ba10bf462126bf2cff092131b344523
2 files changed +2156 -1025 +469 -251
+2156 -1025
--- 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.7.2. By combining all the individual C code files into this
3
+** version 3.7.3. By combining all the individual C code files into this
44
** single large file, the entire code can be compiled as a one 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% are more are commonly seen when SQLite is compiled as a single
88
** translation unit.
@@ -352,19 +352,25 @@
352352
# define SQLITE_INT_TO_PTR(X) ((void*)(X))
353353
# define SQLITE_PTR_TO_INT(X) ((int)(X))
354354
#endif
355355
356356
/*
357
-** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
357
+** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358
+** 0 means mutexes are permanently disable and the library is never
359
+** threadsafe. 1 means the library is serialized which is the highest
360
+** level of threadsafety. 2 means the libary is multithreaded - multiple
361
+** threads can use SQLite as long as no two threads try to use the same
362
+** database connection at the same time.
363
+**
358364
** Older versions of SQLite used an optional THREADSAFE macro.
359
-** We support that for legacy
365
+** We support that for legacy.
360366
*/
361367
#if !defined(SQLITE_THREADSAFE)
362368
#if defined(THREADSAFE)
363369
# define SQLITE_THREADSAFE THREADSAFE
364370
#else
365
-# define SQLITE_THREADSAFE 1
371
+# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
366372
#endif
367373
#endif
368374
369375
/*
370376
** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
@@ -642,13 +648,13 @@
642648
**
643649
** See also: [sqlite3_libversion()],
644650
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
645651
** [sqlite_version()] and [sqlite_source_id()].
646652
*/
647
-#define SQLITE_VERSION "3.7.2"
648
-#define SQLITE_VERSION_NUMBER 3007002
649
-#define SQLITE_SOURCE_ID "2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3"
653
+#define SQLITE_VERSION "3.7.3"
654
+#define SQLITE_VERSION_NUMBER 3007003
655
+#define SQLITE_SOURCE_ID "2010-09-29 23:09:23 1ef0dc9328f47506cb2dcd142150e96cb4755216"
650656
651657
/*
652658
** CAPI3REF: Run-Time Library Version Numbers
653659
** KEYWORDS: sqlite3_version, sqlite3_sourceid
654660
**
@@ -1292,19 +1298,23 @@
12921298
** object once the object has been registered.
12931299
**
12941300
** The zName field holds the name of the VFS module. The name must
12951301
** be unique across all VFS modules.
12961302
**
1297
-** SQLite will guarantee that the zFilename parameter to xOpen
1303
+** ^SQLite guarantees that the zFilename parameter to xOpen
12981304
** is either a NULL pointer or string obtained
1299
-** from xFullPathname(). SQLite further guarantees that
1305
+** from xFullPathname() with an optional suffix added.
1306
+** ^If a suffix is added to the zFilename parameter, it will
1307
+** consist of a single "-" character followed by no more than
1308
+** 10 alphanumeric and/or "-" characters.
1309
+** ^SQLite further guarantees that
13001310
** the string will be valid and unchanged until xClose() is
13011311
** called. Because of the previous sentence,
13021312
** the [sqlite3_file] can safely store a pointer to the
13031313
** filename if it needs to remember the filename for some reason.
1304
-** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1305
-** must invent its own temporary name for the file. Whenever the
1314
+** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1315
+** must invent its own temporary name for the file. ^Whenever the
13061316
** xFilename parameter is NULL it will also be the case that the
13071317
** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
13081318
**
13091319
** The flags argument to xOpen() includes all bits set in
13101320
** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -1311,11 +1321,11 @@
13111321
** or [sqlite3_open16()] is used, then flags includes at least
13121322
** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
13131323
** If xOpen() opens a file read-only then it sets *pOutFlags to
13141324
** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
13151325
**
1316
-** SQLite will also add one of the following flags to the xOpen()
1326
+** ^(SQLite will also add one of the following flags to the xOpen()
13171327
** call, depending on the object being opened:
13181328
**
13191329
** <ul>
13201330
** <li> [SQLITE_OPEN_MAIN_DB]
13211331
** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -1322,11 +1332,12 @@
13221332
** <li> [SQLITE_OPEN_TEMP_DB]
13231333
** <li> [SQLITE_OPEN_TEMP_JOURNAL]
13241334
** <li> [SQLITE_OPEN_TRANSIENT_DB]
13251335
** <li> [SQLITE_OPEN_SUBJOURNAL]
13261336
** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1327
-** </ul>
1337
+** <li> [SQLITE_OPEN_WAL]
1338
+** </ul>)^
13281339
**
13291340
** The file I/O implementation can use the object type flags to
13301341
** change the way it deals with files. For example, an application
13311342
** that does not care about crash recovery or rollback might make
13321343
** the open of a journal file a no-op. Writes to this journal would
@@ -1341,39 +1352,40 @@
13411352
** <li> [SQLITE_OPEN_DELETEONCLOSE]
13421353
** <li> [SQLITE_OPEN_EXCLUSIVE]
13431354
** </ul>
13441355
**
13451356
** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1346
-** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
1347
-** will be set for TEMP databases, journals and for subjournals.
1357
+** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1358
+** will be set for TEMP databases and their journals, transient
1359
+** databases, and subjournals.
13481360
**
1349
-** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1361
+** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
13501362
** with the [SQLITE_OPEN_CREATE] flag, which are both directly
13511363
** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
13521364
** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
13531365
** SQLITE_OPEN_CREATE, is used to indicate that file should always
13541366
** be created, and that it is an error if it already exists.
13551367
** It is <i>not</i> used to indicate the file should be opened
13561368
** for exclusive access.
13571369
**
1358
-** At least szOsFile bytes of memory are allocated by SQLite
1370
+** ^At least szOsFile bytes of memory are allocated by SQLite
13591371
** to hold the [sqlite3_file] structure passed as the third
13601372
** argument to xOpen. The xOpen method does not have to
13611373
** allocate the structure; it should just fill it in. Note that
13621374
** the xOpen method must set the sqlite3_file.pMethods to either
13631375
** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
13641376
** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
13651377
** element will be valid after xOpen returns regardless of the success
13661378
** or failure of the xOpen call.
13671379
**
1368
-** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1380
+** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
13691381
** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
13701382
** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
13711383
** to test whether a file is at least readable. The file can be a
13721384
** directory.
13731385
**
1374
-** SQLite will always allocate at least mxPathname+1 bytes for the
1386
+** ^SQLite will always allocate at least mxPathname+1 bytes for the
13751387
** output buffer xFullPathname. The exact size of the output buffer
13761388
** is also passed as a parameter to both methods. If the output buffer
13771389
** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
13781390
** handled as a fatal error by SQLite, vfs implementations should endeavor
13791391
** to prevent this by setting mxPathname to a sufficiently large value.
@@ -1383,14 +1395,14 @@
13831395
** included in the VFS structure for completeness.
13841396
** The xRandomness() function attempts to return nBytes bytes
13851397
** of good-quality randomness into zOut. The return value is
13861398
** the actual number of bytes of randomness obtained.
13871399
** The xSleep() method causes the calling thread to sleep for at
1388
-** least the number of microseconds given. The xCurrentTime()
1400
+** least the number of microseconds given. ^The xCurrentTime()
13891401
** method returns a Julian Day Number for the current date and time as
13901402
** a floating point value.
1391
-** The xCurrentTimeInt64() method returns, as an integer, the Julian
1403
+** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
13921404
** Day Number multipled by 86400000 (the number of milliseconds in
13931405
** a 24-hour day).
13941406
** ^SQLite will use the xCurrentTimeInt64() method to get the current
13951407
** date and time if that method is available (if iVersion is 2 or
13961408
** greater and the function pointer is not NULL) and will fall back
@@ -1783,11 +1795,11 @@
17831795
** statistics. ^(When memory allocation statistics are disabled, the
17841796
** following SQLite interfaces become non-operational:
17851797
** <ul>
17861798
** <li> [sqlite3_memory_used()]
17871799
** <li> [sqlite3_memory_highwater()]
1788
-** <li> [sqlite3_soft_heap_limit()]
1800
+** <li> [sqlite3_soft_heap_limit64()]
17891801
** <li> [sqlite3_status()]
17901802
** </ul>)^
17911803
** ^Memory allocation statistics are enabled by default unless SQLite is
17921804
** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
17931805
** allocation statistics are disabled by default.
@@ -1797,19 +1809,18 @@
17971809
** <dd> ^This option specifies a static memory buffer that SQLite can use for
17981810
** scratch memory. There are three arguments: A pointer an 8-byte
17991811
** aligned memory buffer from which the scrach allocations will be
18001812
** drawn, the size of each scratch allocation (sz),
18011813
** and the maximum number of scratch allocations (N). The sz
1802
-** argument must be a multiple of 16. The sz parameter should be a few bytes
1803
-** larger than the actual scratch space required due to internal overhead.
1814
+** argument must be a multiple of 16.
18041815
** The first argument must be a pointer to an 8-byte aligned buffer
18051816
** of at least sz*N bytes of memory.
1806
-** ^SQLite will use no more than one scratch buffer per thread. So
1807
-** N should be set to the expected maximum number of threads. ^SQLite will
1808
-** never require a scratch buffer that is more than 6 times the database
1809
-** page size. ^If SQLite needs needs additional scratch memory beyond
1810
-** what is provided by this configuration option, then
1817
+** ^SQLite will use no more than two scratch buffers per thread. So
1818
+** N should be set to twice the expected maximum number of threads.
1819
+** ^SQLite will never require a scratch buffer that is more than 6
1820
+** times the database page size. ^If SQLite needs needs additional
1821
+** scratch memory beyond what is provided by this configuration option, then
18111822
** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
18121823
**
18131824
** <dt>SQLITE_CONFIG_PAGECACHE</dt>
18141825
** <dd> ^This option specifies a static memory buffer that SQLite can use for
18151826
** the database page cache with the default page cache implemenation.
@@ -1825,12 +1836,11 @@
18251836
** argument should point to an allocation of at least sz*N bytes of memory.
18261837
** ^SQLite will use the memory provided by the first argument to satisfy its
18271838
** memory needs for the first N pages that it adds to cache. ^If additional
18281839
** page cache memory is needed beyond what is provided by this option, then
18291840
** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1830
-** ^The implementation might use one or more of the N buffers to hold
1831
-** memory accounting information. The pointer in the first argument must
1841
+** The pointer in the first argument must
18321842
** be aligned to an 8-byte boundary or subsequent behavior of SQLite
18331843
** will be undefined.</dd>
18341844
**
18351845
** <dt>SQLITE_CONFIG_HEAP</dt>
18361846
** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1955,12 +1965,18 @@
19551965
** size of each lookaside buffer slot. ^The third argument is the number of
19561966
** slots. The size of the buffer in the first argument must be greater than
19571967
** or equal to the product of the second and third arguments. The buffer
19581968
** must be aligned to an 8-byte boundary. ^If the second argument to
19591969
** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1960
-** rounded down to the next smaller
1961
-** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1970
+** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1971
+** configuration for a database connection can only be changed when that
1972
+** connection is not currently using lookaside memory, or in other words
1973
+** when the "current value" returned by
1974
+** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1975
+** Any attempt to change the lookaside memory configuration when lookaside
1976
+** memory is in use leaves the configuration unchanged and returns
1977
+** [SQLITE_BUSY].)^</dd>
19621978
**
19631979
** </dl>
19641980
*/
19651981
#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
19661982
@@ -2260,10 +2276,13 @@
22602276
*/
22612277
SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
22622278
22632279
/*
22642280
** CAPI3REF: Convenience Routines For Running Queries
2281
+**
2282
+** This is a legacy interface that is preserved for backwards compatibility.
2283
+** Use of this interface is not recommended.
22652284
**
22662285
** Definition: A <b>result table</b> is memory data structure created by the
22672286
** [sqlite3_get_table()] interface. A result table records the
22682287
** complete query results from one or more queries.
22692288
**
@@ -2281,11 +2300,11 @@
22812300
**
22822301
** A result table might consist of one or more memory allocations.
22832302
** It is not safe to pass a result table directly to [sqlite3_free()].
22842303
** A result table should be deallocated using [sqlite3_free_table()].
22852304
**
2286
-** As an example of the result table format, suppose a query result
2305
+** ^(As an example of the result table format, suppose a query result
22872306
** is as follows:
22882307
**
22892308
** <blockquote><pre>
22902309
** Name | Age
22912310
** -----------------------
@@ -2305,31 +2324,31 @@
23052324
** azResult&#91;3] = "43";
23062325
** azResult&#91;4] = "Bob";
23072326
** azResult&#91;5] = "28";
23082327
** azResult&#91;6] = "Cindy";
23092328
** azResult&#91;7] = "21";
2310
-** </pre></blockquote>
2329
+** </pre></blockquote>)^
23112330
**
23122331
** ^The sqlite3_get_table() function evaluates one or more
23132332
** semicolon-separated SQL statements in the zero-terminated UTF-8
23142333
** string of its 2nd parameter and returns a result table to the
23152334
** pointer given in its 3rd parameter.
23162335
**
23172336
** After the application has finished with the result from sqlite3_get_table(),
2318
-** it should pass the result table pointer to sqlite3_free_table() in order to
2337
+** it must pass the result table pointer to sqlite3_free_table() in order to
23192338
** release the memory that was malloced. Because of the way the
23202339
** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
23212340
** function must not try to call [sqlite3_free()] directly. Only
23222341
** [sqlite3_free_table()] is able to release the memory properly and safely.
23232342
**
2324
-** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2343
+** The sqlite3_get_table() interface is implemented as a wrapper around
23252344
** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
23262345
** to any internal data structures of SQLite. It uses only the public
23272346
** interface defined here. As a consequence, errors that occur in the
23282347
** wrapper layer outside of the internal [sqlite3_exec()] call are not
23292348
** reflected in subsequent calls to [sqlite3_errcode()] or
2330
-** [sqlite3_errmsg()].)^
2349
+** [sqlite3_errmsg()].
23312350
*/
23322351
SQLITE_API int sqlite3_get_table(
23332352
sqlite3 *db, /* An open database */
23342353
const char *zSql, /* SQL to be evaluated */
23352354
char ***pazResult, /* Results of the query */
@@ -2477,11 +2496,13 @@
24772496
** by sqlite3_realloc() and the prior allocation is freed.
24782497
** ^If sqlite3_realloc() returns NULL, then the prior allocation
24792498
** is not freed.
24802499
**
24812500
** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2482
-** is always aligned to at least an 8 byte boundary.
2501
+** is always aligned to at least an 8 byte boundary, or to a
2502
+** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2503
+** option is used.
24832504
**
24842505
** In SQLite version 3.5.0 and 3.5.1, it was possible to define
24852506
** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
24862507
** implementation of these routines to be omitted. That capability
24872508
** is no longer provided. Only built-in memory allocators can be used.
@@ -2735,21 +2756,32 @@
27352756
void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
27362757
27372758
/*
27382759
** CAPI3REF: Query Progress Callbacks
27392760
**
2740
-** ^This routine configures a callback function - the
2741
-** progress callback - that is invoked periodically during long
2742
-** running calls to [sqlite3_exec()], [sqlite3_step()] and
2743
-** [sqlite3_get_table()]. An example use for this
2761
+** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2762
+** function X to be invoked periodically during long running calls to
2763
+** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2764
+** database connection D. An example use for this
27442765
** interface is to keep a GUI updated during a large query.
2766
+**
2767
+** ^The parameter P is passed through as the only parameter to the
2768
+** callback function X. ^The parameter N is the number of
2769
+** [virtual machine instructions] that are evaluated between successive
2770
+** invocations of the callback X.
2771
+**
2772
+** ^Only a single progress handler may be defined at one time per
2773
+** [database connection]; setting a new progress handler cancels the
2774
+** old one. ^Setting parameter X to NULL disables the progress handler.
2775
+** ^The progress handler is also disabled by setting N to a value less
2776
+** than 1.
27452777
**
27462778
** ^If the progress callback returns non-zero, the operation is
27472779
** interrupted. This feature can be used to implement a
27482780
** "Cancel" button on a GUI progress dialog box.
27492781
**
2750
-** The progress handler must not do anything that will modify
2782
+** The progress handler callback must not do anything that will modify
27512783
** the database connection that invoked the progress handler.
27522784
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
27532785
** database connections for the meaning of "modify" in this paragraph.
27542786
**
27552787
*/
@@ -2804,11 +2836,11 @@
28042836
** </dl>
28052837
**
28062838
** If the 3rd parameter to sqlite3_open_v2() is not one of the
28072839
** combinations shown above or one of the combinations shown above combined
28082840
** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2809
-** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2841
+** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
28102842
** then the behavior is undefined.
28112843
**
28122844
** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
28132845
** opens in the multi-thread [threading mode] as long as the single-thread
28142846
** mode has not been set at compile-time or start-time. ^If the
@@ -2929,21 +2961,26 @@
29292961
** ^(This interface allows the size of various constructs to be limited
29302962
** on a connection by connection basis. The first parameter is the
29312963
** [database connection] whose limit is to be set or queried. The
29322964
** second parameter is one of the [limit categories] that define a
29332965
** class of constructs to be size limited. The third parameter is the
2934
-** new limit for that construct. The function returns the old limit.)^
2966
+** new limit for that construct.)^
29352967
**
29362968
** ^If the new limit is a negative number, the limit is unchanged.
2937
-** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2969
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
29382970
** [limits | hard upper bound]
2939
-** set by a compile-time C preprocessor macro named
2940
-** [limits | SQLITE_MAX_XYZ].
2971
+** set at compile-time by a C preprocessor macro called
2972
+** [limits | SQLITE_MAX_<i>NAME</i>].
29412973
** (The "_LIMIT_" in the name is changed to "_MAX_".))^
29422974
** ^Attempts to increase a limit above its hard upper bound are
29432975
** silently truncated to the hard upper bound.
29442976
**
2977
+** ^Regardless of whether or not the limit was changed, the
2978
+** [sqlite3_limit()] interface returns the prior value of the limit.
2979
+** ^Hence, to find the current value of a limit without changing it,
2980
+** simply invoke this interface with the third parameter set to -1.
2981
+**
29452982
** Run-time limits are intended for use in applications that manage
29462983
** both their own internal database and also databases that are controlled
29472984
** by untrusted external sources. An example application might be a
29482985
** web browser that has its own databases for storing history and
29492986
** separate databases controlled by JavaScript applications downloaded
@@ -2968,11 +3005,11 @@
29683005
** The synopsis of the meanings of the various limits is shown below.
29693006
** Additional information is available at [limits | Limits in SQLite].
29703007
**
29713008
** <dl>
29723009
** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2973
-** <dd>The maximum size of any string or BLOB or table row.<dd>)^
3010
+** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
29743011
**
29753012
** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
29763013
** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
29773014
**
29783015
** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2986,11 +3023,13 @@
29863023
** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
29873024
** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
29883025
**
29893026
** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
29903027
** <dd>The maximum number of instructions in a virtual machine program
2991
-** used to implement an SQL statement.</dd>)^
3028
+** used to implement an SQL statement. This limit is not currently
3029
+** enforced, though that might be added in some future release of
3030
+** SQLite.</dd>)^
29923031
**
29933032
** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
29943033
** <dd>The maximum number of arguments on a function.</dd>)^
29953034
**
29963035
** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2999,12 +3038,11 @@
29993038
** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
30003039
** <dd>The maximum length of the pattern argument to the [LIKE] or
30013040
** [GLOB] operators.</dd>)^
30023041
**
30033042
** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3004
-** <dd>The maximum number of variables in an SQL statement that can
3005
-** be bound.</dd>)^
3043
+** <dd>The maximum index number of any [parameter] in an SQL statement.)^
30063044
**
30073045
** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
30083046
** <dd>The maximum depth of recursion for triggers.</dd>)^
30093047
** </dl>
30103048
*/
@@ -3072,16 +3110,11 @@
30723110
**
30733111
** <ol>
30743112
** <li>
30753113
** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
30763114
** always used to do, [sqlite3_step()] will automatically recompile the SQL
3077
-** statement and try to run it again. ^If the schema has changed in
3078
-** a way that makes the statement no longer valid, [sqlite3_step()] will still
3079
-** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
3080
-** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
3081
-** error go away. Note: use [sqlite3_errmsg()] to find the text
3082
-** of the parsing error that results in an [SQLITE_SCHEMA] return.
3115
+** statement and try to run it again.
30833116
** </li>
30843117
**
30853118
** <li>
30863119
** ^When an error occurs, [sqlite3_step()] will return one of the detailed
30873120
** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -3090,15 +3123,20 @@
30903123
** in order to find the underlying cause of the problem. With the "v2" prepare
30913124
** interfaces, the underlying reason for the error is returned immediately.
30923125
** </li>
30933126
**
30943127
** <li>
3095
-** ^If the value of a [parameter | host parameter] in the WHERE clause might
3096
-** change the query plan for a statement, then the statement may be
3097
-** automatically recompiled (as if there had been a schema change) on the first
3098
-** [sqlite3_step()] call following any change to the
3099
-** [sqlite3_bind_text | bindings] of the [parameter].
3128
+** ^If the specific value bound to [parameter | host parameter] in the
3129
+** WHERE clause might influence the choice of query plan for a statement,
3130
+** then the statement will be automatically recompiled, as if there had been
3131
+** a schema change, on the first [sqlite3_step()] call following any change
3132
+** to the [sqlite3_bind_text | bindings] of that [parameter].
3133
+** ^The specific value of WHERE-clause [parameter] might influence the
3134
+** choice of query plan if the parameter is the left-hand side of a [LIKE]
3135
+** or [GLOB] operator or if the parameter is compared to an indexed column
3136
+** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3137
+** the
31003138
** </li>
31013139
** </ol>
31023140
*/
31033141
SQLITE_API int sqlite3_prepare(
31043142
sqlite3 *db, /* Database handle */
@@ -3161,11 +3199,11 @@
31613199
** or if SQLite is run in one of reduced mutex modes
31623200
** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
31633201
** then there is no distinction between protected and unprotected
31643202
** sqlite3_value objects and they can be used interchangeably. However,
31653203
** for maximum code portability it is recommended that applications
3166
-** still make the distinction between between protected and unprotected
3204
+** still make the distinction between protected and unprotected
31673205
** sqlite3_value objects even when not strictly required.
31683206
**
31693207
** ^The sqlite3_value objects that are passed as parameters into the
31703208
** implementation of [application-defined SQL functions] are protected.
31713209
** ^The sqlite3_value object returned by
@@ -3356,10 +3394,12 @@
33563394
** CAPI3REF: Number Of Columns In A Result Set
33573395
**
33583396
** ^Return the number of columns in the result set returned by the
33593397
** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
33603398
** statement that does not return data (for example an [UPDATE]).
3399
+**
3400
+** See also: [sqlite3_data_count()]
33613401
*/
33623402
SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
33633403
33643404
/*
33653405
** CAPI3REF: Column Names In A Result Set
@@ -3546,12 +3586,18 @@
35463586
SQLITE_API int sqlite3_step(sqlite3_stmt*);
35473587
35483588
/*
35493589
** CAPI3REF: Number of columns in a result set
35503590
**
3551
-** ^The sqlite3_data_count(P) the number of columns in the
3552
-** of the result set of [prepared statement] P.
3591
+** ^The sqlite3_data_count(P) interface returns the number of columns in the
3592
+** current row of the result set of [prepared statement] P.
3593
+** ^If prepared statement P does not have results ready to return
3594
+** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3595
+** interfaces) then sqlite3_data_count(P) returns 0.
3596
+** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3597
+**
3598
+** See also: [sqlite3_column_count()]
35533599
*/
35543600
SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
35553601
35563602
/*
35573603
** CAPI3REF: Fundamental Datatypes
@@ -3627,22 +3673,30 @@
36273673
** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
36283674
** the string to UTF-8 and then returns the number of bytes.
36293675
** ^If the result is a numeric value then sqlite3_column_bytes() uses
36303676
** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
36313677
** the number of bytes in that string.
3632
-** ^The value returned does not include the zero terminator at the end
3633
-** of the string. ^For clarity: the value returned is the number of
3678
+** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3679
+**
3680
+** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3681
+** routine returns the number of bytes in that BLOB or string.
3682
+** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3683
+** the string to UTF-16 and then returns the number of bytes.
3684
+** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3685
+** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3686
+** the number of bytes in that string.
3687
+** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3688
+**
3689
+** ^The values returned by [sqlite3_column_bytes()] and
3690
+** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3691
+** of the string. ^For clarity: the values returned by
3692
+** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
36343693
** bytes in the string, not the number of characters.
36353694
**
36363695
** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
36373696
** even empty strings, are always zero terminated. ^The return
3638
-** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3639
-** pointer, possibly even a NULL pointer.
3640
-**
3641
-** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3642
-** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3643
-** ^The zero terminator is not included in this count.
3697
+** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
36443698
**
36453699
** ^The object returned by [sqlite3_column_value()] is an
36463700
** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
36473701
** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
36483702
** If the [unprotected sqlite3_value] object returned by
@@ -3683,14 +3737,14 @@
36833737
** and atof(). SQLite does not really use these functions. It has its
36843738
** own equivalent internal routines. The atoi() and atof() names are
36853739
** used in the table for brevity and because they are familiar to most
36863740
** C programmers.
36873741
**
3688
-** ^Note that when type conversions occur, pointers returned by prior
3742
+** Note that when type conversions occur, pointers returned by prior
36893743
** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
36903744
** sqlite3_column_text16() may be invalidated.
3691
-** ^(Type conversions and pointer invalidations might occur
3745
+** Type conversions and pointer invalidations might occur
36923746
** in the following cases:
36933747
**
36943748
** <ul>
36953749
** <li> The initial content is a BLOB and sqlite3_column_text() or
36963750
** sqlite3_column_text16() is called. A zero-terminator might
@@ -3699,26 +3753,26 @@
36993753
** sqlite3_column_text16() is called. The content must be converted
37003754
** to UTF-16.</li>
37013755
** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
37023756
** sqlite3_column_text() is called. The content must be converted
37033757
** to UTF-8.</li>
3704
-** </ul>)^
3758
+** </ul>
37053759
**
37063760
** ^Conversions between UTF-16be and UTF-16le are always done in place and do
37073761
** not invalidate a prior pointer, though of course the content of the buffer
3708
-** that the prior pointer points to will have been modified. Other kinds
3762
+** that the prior pointer references will have been modified. Other kinds
37093763
** of conversion are done in place when it is possible, but sometimes they
37103764
** are not possible and in those cases prior pointers are invalidated.
37113765
**
3712
-** ^(The safest and easiest to remember policy is to invoke these routines
3766
+** The safest and easiest to remember policy is to invoke these routines
37133767
** in one of the following ways:
37143768
**
37153769
** <ul>
37163770
** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
37173771
** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
37183772
** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3719
-** </ul>)^
3773
+** </ul>
37203774
**
37213775
** In other words, you should call sqlite3_column_text(),
37223776
** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
37233777
** into the desired format, then invoke sqlite3_column_bytes() or
37243778
** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3752,21 +3806,30 @@
37523806
37533807
/*
37543808
** CAPI3REF: Destroy A Prepared Statement Object
37553809
**
37563810
** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3757
-** ^If the statement was executed successfully or not executed at all, then
3758
-** SQLITE_OK is returned. ^If execution of the statement failed then an
3759
-** [error code] or [extended error code] is returned.
3811
+** ^If the most recent evaluation of the statement encountered no errors or
3812
+** or if the statement is never been evaluated, then sqlite3_finalize() returns
3813
+** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3814
+** sqlite3_finalize(S) returns the appropriate [error code] or
3815
+** [extended error code].
37603816
**
3761
-** ^This routine can be called at any point during the execution of the
3762
-** [prepared statement]. ^If the virtual machine has not
3763
-** completed execution when this routine is called, that is like
3764
-** encountering an error or an [sqlite3_interrupt | interrupt].
3765
-** ^Incomplete updates may be rolled back and transactions canceled,
3766
-** depending on the circumstances, and the
3767
-** [error code] returned will be [SQLITE_ABORT].
3817
+** ^The sqlite3_finalize(S) routine can be called at any point during
3818
+** the life cycle of [prepared statement] S:
3819
+** before statement S is ever evaluated, after
3820
+** one or more calls to [sqlite3_reset()], or after any call
3821
+** to [sqlite3_step()] regardless of whether or not the statement has
3822
+** completed execution.
3823
+**
3824
+** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3825
+**
3826
+** The application must finalize every [prepared statement] in order to avoid
3827
+** resource leaks. It is a grievous error for the application to try to use
3828
+** a prepared statement after it has been finalized. Any use of a prepared
3829
+** statement after it has been finalized can result in undefined and
3830
+** undesirable behavior such as segfaults and heap corruption.
37683831
*/
37693832
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
37703833
37713834
/*
37723835
** CAPI3REF: Reset A Prepared Statement Object
@@ -3798,40 +3861,42 @@
37983861
** CAPI3REF: Create Or Redefine SQL Functions
37993862
** KEYWORDS: {function creation routines}
38003863
** KEYWORDS: {application-defined SQL function}
38013864
** KEYWORDS: {application-defined SQL functions}
38023865
**
3803
-** ^These two functions (collectively known as "function creation routines")
3866
+** ^These functions (collectively known as "function creation routines")
38043867
** are used to add SQL functions or aggregates or to redefine the behavior
3805
-** of existing SQL functions or aggregates. The only difference between the
3806
-** two is that the second parameter, the name of the (scalar) function or
3807
-** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3808
-** for sqlite3_create_function16().
3868
+** of existing SQL functions or aggregates. The only differences between
3869
+** these routines are the text encoding expected for
3870
+** the the second parameter (the name of the function being created)
3871
+** and the presence or absence of a destructor callback for
3872
+** the application data pointer.
38093873
**
38103874
** ^The first parameter is the [database connection] to which the SQL
38113875
** function is to be added. ^If an application uses more than one database
38123876
** connection then application-defined SQL functions must be added
38133877
** to each database connection separately.
38143878
**
3815
-** The second parameter is the name of the SQL function to be created or
3816
-** redefined. ^The length of the name is limited to 255 bytes, exclusive of
3817
-** the zero-terminator. Note that the name length limit is in bytes, not
3818
-** characters. ^Any attempt to create a function with a longer name
3819
-** will result in [SQLITE_ERROR] being returned.
3879
+** ^The second parameter is the name of the SQL function to be created or
3880
+** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
3881
+** representation, exclusive of the zero-terminator. ^Note that the name
3882
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
3883
+** ^Any attempt to create a function with a longer name
3884
+** will result in [SQLITE_MISUSE] being returned.
38203885
**
38213886
** ^The third parameter (nArg)
38223887
** is the number of arguments that the SQL function or
38233888
** aggregate takes. ^If this parameter is -1, then the SQL function or
38243889
** aggregate may take any number of arguments between 0 and the limit
38253890
** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
38263891
** parameter is less than -1 or greater than 127 then the behavior is
38273892
** undefined.
38283893
**
3829
-** The fourth parameter, eTextRep, specifies what
3894
+** ^The fourth parameter, eTextRep, specifies what
38303895
** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3831
-** its parameters. Any SQL function implementation should be able to work
3832
-** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3896
+** its parameters. Every SQL function implementation must be able to work
3897
+** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
38333898
** more efficient with one encoding than another. ^An application may
38343899
** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
38353900
** times with the same function but with different values of eTextRep.
38363901
** ^When multiple implementations of the same function are available, SQLite
38373902
** will pick the one that involves the least amount of data conversion.
@@ -3839,17 +3904,25 @@
38393904
** encoding is used, then the fourth argument should be [SQLITE_ANY].
38403905
**
38413906
** ^(The fifth parameter is an arbitrary pointer. The implementation of the
38423907
** function can gain access to this pointer using [sqlite3_user_data()].)^
38433908
**
3844
-** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3909
+** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
38453910
** pointers to C-language functions that implement the SQL function or
38463911
** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3847
-** callback only; NULL pointers should be passed as the xStep and xFinal
3912
+** callback only; NULL pointers must be passed as the xStep and xFinal
38483913
** parameters. ^An aggregate SQL function requires an implementation of xStep
3849
-** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3850
-** SQL function or aggregate, pass NULL for all three function callbacks.
3914
+** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3915
+** SQL function or aggregate, pass NULL poiners for all three function
3916
+** callbacks.
3917
+**
3918
+** ^If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3919
+** then it is invoked when the function is deleted, either by being
3920
+** overloaded or when the database connection closes.
3921
+** ^When the destructure callback of the tenth parameter is invoked, it
3922
+** is passed a single argument which is a copy of the pointer which was
3923
+** the fifth parameter to sqlite3_create_function_v2().
38513924
**
38523925
** ^It is permitted to register multiple implementations of the same
38533926
** functions with the same name but with either differing numbers of
38543927
** arguments or differing preferred text encodings. ^SQLite will use
38553928
** the implementation that most closely matches the way in which the
@@ -3861,15 +3934,10 @@
38613934
** ^A function where the encoding difference is between UTF16le and UTF16be
38623935
** is a closer match than a function where the encoding difference is
38633936
** between UTF8 and UTF16.
38643937
**
38653938
** ^Built-in functions may be overloaded by new application-defined functions.
3866
-** ^The first application-defined function with a given name overrides all
3867
-** built-in functions in the same [database connection] with the same name.
3868
-** ^Subsequent application-defined functions of the same name only override
3869
-** prior application-defined functions that are an exact match for the
3870
-** number of parameters and preferred encoding.
38713939
**
38723940
** ^An application-defined function is permitted to call other
38733941
** SQLite interfaces. However, such calls must not
38743942
** close the database connection nor finalize or reset the prepared
38753943
** statement in which the function is running.
@@ -3891,10 +3959,21 @@
38913959
int eTextRep,
38923960
void *pApp,
38933961
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
38943962
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
38953963
void (*xFinal)(sqlite3_context*)
3964
+);
3965
+SQLITE_API int sqlite3_create_function_v2(
3966
+ sqlite3 *db,
3967
+ const char *zFunctionName,
3968
+ int nArg,
3969
+ int eTextRep,
3970
+ void *pApp,
3971
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3972
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3973
+ void (*xFinal)(sqlite3_context*),
3974
+ void(*xDestroy)(void*)
38963975
);
38973976
38983977
/*
38993978
** CAPI3REF: Text Encodings
39003979
**
@@ -4238,73 +4317,97 @@
42384317
SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
42394318
42404319
/*
42414320
** CAPI3REF: Define New Collating Sequences
42424321
**
4243
-** These functions are used to add new collation sequences to the
4244
-** [database connection] specified as the first argument.
4322
+** ^These functions add, remove, or modify a [collation] associated
4323
+** with the [database connection] specified as the first argument.
42454324
**
4246
-** ^The name of the new collation sequence is specified as a UTF-8 string
4325
+** ^The name of the collation is a UTF-8 string
42474326
** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4248
-** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4249
-** the name is passed as the second function argument.
4250
-**
4251
-** ^The third argument may be one of the constants [SQLITE_UTF8],
4252
-** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4253
-** routine expects to be passed pointers to strings encoded using UTF-8,
4254
-** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4255
-** third argument might also be [SQLITE_UTF16] to indicate that the routine
4256
-** expects pointers to be UTF-16 strings in the native byte order, or the
4257
-** argument can be [SQLITE_UTF16_ALIGNED] if the
4258
-** the routine expects pointers to 16-bit word aligned strings
4259
-** of UTF-16 in the native byte order.
4260
-**
4261
-** A pointer to the user supplied routine must be passed as the fifth
4262
-** argument. ^If it is NULL, this is the same as deleting the collation
4263
-** sequence (so that SQLite cannot call it any more).
4264
-** ^Each time the application supplied function is invoked, it is passed
4265
-** as its first parameter a copy of the void* passed as the fourth argument
4266
-** to sqlite3_create_collation() or sqlite3_create_collation16().
4267
-**
4268
-** ^The remaining arguments to the application-supplied routine are two strings,
4269
-** each represented by a (length, data) pair and encoded in the encoding
4270
-** that was passed as the third argument when the collation sequence was
4271
-** registered. The application defined collation routine should
4272
-** return negative, zero or positive if the first string is less than,
4273
-** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4327
+** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4328
+** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4329
+** considered to be the same name.
4330
+**
4331
+** ^(The third argument (eTextRep) must be one of the constants:
4332
+** <ul>
4333
+** <li> [SQLITE_UTF8],
4334
+** <li> [SQLITE_UTF16LE],
4335
+** <li> [SQLITE_UTF16BE],
4336
+** <li> [SQLITE_UTF16], or
4337
+** <li> [SQLITE_UTF16_ALIGNED].
4338
+** </ul>)^
4339
+** ^The eTextRep argument determines the encoding of strings passed
4340
+** to the collating function callback, xCallback.
4341
+** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4342
+** force strings to be UTF16 with native byte order.
4343
+** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4344
+** on an even byte address.
4345
+**
4346
+** ^The fourth argument, pArg, is a application data pointer that is passed
4347
+** through as the first argument to the collating function callback.
4348
+**
4349
+** ^The fifth argument, xCallback, is a pointer to the collating function.
4350
+** ^Multiple collating functions can be registered using the same name but
4351
+** with different eTextRep parameters and SQLite will use whichever
4352
+** function requires the least amount of data transformation.
4353
+** ^If the xCallback argument is NULL then the collating function is
4354
+** deleted. ^When all collating functions having the same name are deleted,
4355
+** that collation is no longer usable.
4356
+**
4357
+** ^The collating function callback is invoked with a copy of the pArg
4358
+** application data pointer and with two strings in the encoding specified
4359
+** by the eTextRep argument. The collating function must return an
4360
+** integer that is negative, zero, or positive
4361
+** if the first string is less than, equal to, or greater than the second,
4362
+** respectively. A collating function must alway return the same answer
4363
+** given the same inputs. If two or more collating functions are registered
4364
+** to the same collation name (using different eTextRep values) then all
4365
+** must give an equivalent answer when invoked with equivalent strings.
4366
+** The collating function must obey the following properties for all
4367
+** strings A, B, and C:
4368
+**
4369
+** <ol>
4370
+** <li> If A==B then B==A.
4371
+** <li> If A==B and B==C then A==C.
4372
+** <li> If A&lt;B THEN B&gt;A.
4373
+** <li> If A&lt;B and B&lt;C then A&lt;C.
4374
+** </ol>
4375
+**
4376
+** If a collating function fails any of the above constraints and that
4377
+** collating function is registered and used, then the behavior of SQLite
4378
+** is undefined.
42744379
**
42754380
** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4276
-** except that it takes an extra argument which is a destructor for
4277
-** the collation. ^The destructor is called when the collation is
4278
-** destroyed and is passed a copy of the fourth parameter void* pointer
4279
-** of the sqlite3_create_collation_v2().
4280
-** ^Collations are destroyed when they are overridden by later calls to the
4281
-** collation creation functions or when the [database connection] is closed
4282
-** using [sqlite3_close()].
4381
+** with the addition that the xDestroy callback is invoked on pArg when
4382
+** the collating function is deleted.
4383
+** ^Collating functions are deleted when they are overridden by later
4384
+** calls to the collation creation functions or when the
4385
+** [database connection] is closed using [sqlite3_close()].
42834386
**
42844387
** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
42854388
*/
42864389
SQLITE_API int sqlite3_create_collation(
42874390
sqlite3*,
42884391
const char *zName,
42894392
int eTextRep,
4290
- void*,
4393
+ void *pArg,
42914394
int(*xCompare)(void*,int,const void*,int,const void*)
42924395
);
42934396
SQLITE_API int sqlite3_create_collation_v2(
42944397
sqlite3*,
42954398
const char *zName,
42964399
int eTextRep,
4297
- void*,
4400
+ void *pArg,
42984401
int(*xCompare)(void*,int,const void*,int,const void*),
42994402
void(*xDestroy)(void*)
43004403
);
43014404
SQLITE_API int sqlite3_create_collation16(
43024405
sqlite3*,
43034406
const void *zName,
43044407
int eTextRep,
4305
- void*,
4408
+ void *pArg,
43064409
int(*xCompare)(void*,int,const void*,int,const void*)
43074410
);
43084411
43094412
/*
43104413
** CAPI3REF: Collation Needed Callbacks
@@ -4389,20 +4492,23 @@
43894492
#endif
43904493
43914494
/*
43924495
** CAPI3REF: Suspend Execution For A Short Time
43934496
**
4394
-** ^The sqlite3_sleep() function causes the current thread to suspend execution
4497
+** The sqlite3_sleep() function causes the current thread to suspend execution
43954498
** for at least a number of milliseconds specified in its parameter.
43964499
**
4397
-** ^If the operating system does not support sleep requests with
4500
+** If the operating system does not support sleep requests with
43984501
** millisecond time resolution, then the time will be rounded up to
4399
-** the nearest second. ^The number of milliseconds of sleep actually
4502
+** the nearest second. The number of milliseconds of sleep actually
44004503
** requested from the operating system is returned.
44014504
**
44024505
** ^SQLite implements this interface by calling the xSleep()
4403
-** method of the default [sqlite3_vfs] object.
4506
+** method of the default [sqlite3_vfs] object. If the xSleep() method
4507
+** of the default VFS is not implemented correctly, or not implemented at
4508
+** all, then the behavior of sqlite3_sleep() may deviate from the description
4509
+** in the previous paragraphs.
44044510
*/
44054511
SQLITE_API int sqlite3_sleep(int);
44064512
44074513
/*
44084514
** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4620,44 +4726,77 @@
46204726
** of heap memory by deallocating non-essential memory allocations
46214727
** held by the database library. Memory used to cache database
46224728
** pages to improve performance is an example of non-essential memory.
46234729
** ^sqlite3_release_memory() returns the number of bytes actually freed,
46244730
** which might be more or less than the amount requested.
4731
+** ^The sqlite3_release_memory() routine is a no-op returning zero
4732
+** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
46254733
*/
46264734
SQLITE_API int sqlite3_release_memory(int);
46274735
46284736
/*
46294737
** CAPI3REF: Impose A Limit On Heap Size
46304738
**
4631
-** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4632
-** on the amount of heap memory that may be allocated by SQLite.
4633
-** ^If an internal allocation is requested that would exceed the
4634
-** soft heap limit, [sqlite3_release_memory()] is invoked one or
4635
-** more times to free up some space before the allocation is performed.
4636
-**
4637
-** ^The limit is called "soft" because if [sqlite3_release_memory()]
4638
-** cannot free sufficient memory to prevent the limit from being exceeded,
4639
-** the memory is allocated anyway and the current operation proceeds.
4640
-**
4641
-** ^A negative or zero value for N means that there is no soft heap limit and
4642
-** [sqlite3_release_memory()] will only be called when memory is exhausted.
4643
-** ^The default value for the soft heap limit is zero.
4644
-**
4645
-** ^(SQLite makes a best effort to honor the soft heap limit.
4646
-** But if the soft heap limit cannot be honored, execution will
4647
-** continue without error or notification.)^ This is why the limit is
4648
-** called a "soft" limit. It is advisory only.
4649
-**
4650
-** Prior to SQLite version 3.5.0, this routine only constrained the memory
4651
-** allocated by a single thread - the same thread in which this routine
4652
-** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
4653
-** applied to all threads. The value specified for the soft heap limit
4654
-** is an upper bound on the total memory allocation for all threads. In
4655
-** version 3.5.0 there is no mechanism for limiting the heap usage for
4656
-** individual threads.
4657
-*/
4658
-SQLITE_API void sqlite3_soft_heap_limit(int);
4739
+** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4740
+** soft limit on the amount of heap memory that may be allocated by SQLite.
4741
+** ^SQLite strives to keep heap memory utilization below the soft heap
4742
+** limit by reducing the number of pages held in the page cache
4743
+** as heap memory usages approaches the limit.
4744
+** ^The soft heap limit is "soft" because even though SQLite strives to stay
4745
+** below the limit, it will exceed the limit rather than generate
4746
+** an [SQLITE_NOMEM] error. In other words, the soft heap limit
4747
+** is advisory only.
4748
+**
4749
+** ^The return value from sqlite3_soft_heap_limit64() is the size of
4750
+** the soft heap limit prior to the call. ^If the argument N is negative
4751
+** then no change is made to the soft heap limit. Hence, the current
4752
+** size of the soft heap limit can be determined by invoking
4753
+** sqlite3_soft_heap_limit64() with a negative argument.
4754
+**
4755
+** ^If the argument N is zero then the soft heap limit is disabled.
4756
+**
4757
+** ^(The soft heap limit is not enforced in the current implementation
4758
+** if one or more of following conditions are true:
4759
+**
4760
+** <ul>
4761
+** <li> The soft heap limit is set to zero.
4762
+** <li> Memory accounting is disabled using a combination of the
4763
+** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4764
+** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4765
+** <li> An alternative page cache implementation is specifed using
4766
+** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4767
+** <li> The page cache allocates from its own memory pool supplied
4768
+** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4769
+** from the heap.
4770
+** </ul>)^
4771
+**
4772
+** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4773
+** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4774
+** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4775
+** the soft heap limit is enforced on every memory allocation. Without
4776
+** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4777
+** when memory is allocated by the page cache. Testing suggests that because
4778
+** the page cache is the predominate memory user in SQLite, most
4779
+** applications will achieve adequate soft heap limit enforcement without
4780
+** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4781
+**
4782
+** The circumstances under which SQLite will enforce the soft heap limit may
4783
+** changes in future releases of SQLite.
4784
+*/
4785
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4786
+
4787
+/*
4788
+** CAPI3REF: Deprecated Soft Heap Limit Interface
4789
+** DEPRECATED
4790
+**
4791
+** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4792
+** interface. This routine is provided for historical compatibility
4793
+** only. All new applications should use the
4794
+** [sqlite3_soft_heap_limit64()] interface rather than this one.
4795
+*/
4796
+SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4797
+
46594798
46604799
/*
46614800
** CAPI3REF: Extract Metadata About A Column Of A Table
46624801
**
46634802
** ^This routine returns metadata about a specific column of a specific
@@ -4777,38 +4916,51 @@
47774916
** it back off again.
47784917
*/
47794918
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
47804919
47814920
/*
4782
-** CAPI3REF: Automatically Load An Extensions
4783
-**
4784
-** ^This API can be invoked at program startup in order to register
4785
-** one or more statically linked extensions that will be available
4786
-** to all new [database connections].
4787
-**
4788
-** ^(This routine stores a pointer to the extension entry point
4789
-** in an array that is obtained from [sqlite3_malloc()]. That memory
4790
-** is deallocated by [sqlite3_reset_auto_extension()].)^
4791
-**
4792
-** ^This function registers an extension entry point that is
4793
-** automatically invoked whenever a new [database connection]
4794
-** is opened using [sqlite3_open()], [sqlite3_open16()],
4795
-** or [sqlite3_open_v2()].
4796
-** ^Duplicate extensions are detected so calling this routine
4797
-** multiple times with the same extension is harmless.
4798
-** ^Automatic extensions apply across all threads.
4921
+** CAPI3REF: Automatically Load Statically Linked Extensions
4922
+**
4923
+** ^This interface causes the xEntryPoint() function to be invoked for
4924
+** each new [database connection] that is created. The idea here is that
4925
+** xEntryPoint() is the entry point for a statically linked SQLite extension
4926
+** that is to be automatically loaded into all new database connections.
4927
+**
4928
+** ^(Even though the function prototype shows that xEntryPoint() takes
4929
+** no arguments and returns void, SQLite invokes xEntryPoint() with three
4930
+** arguments and expects and integer result as if the signature of the
4931
+** entry point where as follows:
4932
+**
4933
+** <blockquote><pre>
4934
+** &nbsp; int xEntryPoint(
4935
+** &nbsp; sqlite3 *db,
4936
+** &nbsp; const char **pzErrMsg,
4937
+** &nbsp; const struct sqlite3_api_routines *pThunk
4938
+** &nbsp; );
4939
+** </pre></blockquote>)^
4940
+**
4941
+** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4942
+** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4943
+** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
4944
+** is NULL before calling the xEntryPoint(). ^SQLite will invoke
4945
+** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
4946
+** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4947
+** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4948
+**
4949
+** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4950
+** on the list of automatic extensions is a harmless no-op. ^No entry point
4951
+** will be called more than once for each database connection that is opened.
4952
+**
4953
+** See also: [sqlite3_reset_auto_extension()].
47994954
*/
48004955
SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
48014956
48024957
/*
48034958
** CAPI3REF: Reset Automatic Extension Loading
48044959
**
4805
-** ^(This function disables all previously registered automatic
4806
-** extensions. It undoes the effect of all prior
4807
-** [sqlite3_auto_extension()] calls.)^
4808
-**
4809
-** ^This function disables automatic extensions in all threads.
4960
+** ^This interface disables all automatic extensions previously
4961
+** registered using [sqlite3_auto_extension()].
48104962
*/
48114963
SQLITE_API void sqlite3_reset_auto_extension(void);
48124964
48134965
/*
48144966
** The interface to the virtual-table mechanism is currently considered
@@ -5443,11 +5595,11 @@
54435595
** output variable when querying the system for the current mutex
54445596
** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
54455597
**
54465598
** ^The xMutexInit method defined by this structure is invoked as
54475599
** part of system initialization by the sqlite3_initialize() function.
5448
-** ^The xMutexInit routine is calle by SQLite exactly once for each
5600
+** ^The xMutexInit routine is called by SQLite exactly once for each
54495601
** effective call to [sqlite3_initialize()].
54505602
**
54515603
** ^The xMutexEnd method defined by this structure is invoked as
54525604
** part of system shutdown by the sqlite3_shutdown() function. The
54535605
** implementation of this method is expected to release all outstanding
@@ -5640,11 +5792,12 @@
56405792
#define SQLITE_TESTCTRL_ALWAYS 13
56415793
#define SQLITE_TESTCTRL_RESERVE 14
56425794
#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
56435795
#define SQLITE_TESTCTRL_ISKEYWORD 16
56445796
#define SQLITE_TESTCTRL_PGHDRSZ 17
5645
-#define SQLITE_TESTCTRL_LAST 17
5797
+#define SQLITE_TESTCTRL_SCRATCHMALLOC 18
5798
+#define SQLITE_TESTCTRL_LAST 18
56465799
56475800
/*
56485801
** CAPI3REF: SQLite Runtime Status
56495802
**
56505803
** ^This interface is used to retrieve runtime status information
@@ -5659,11 +5812,11 @@
56595812
** value. For those parameters
56605813
** nothing is written into *pHighwater and the resetFlag is ignored.)^
56615814
** ^(Other parameters record only the highwater mark and not the current
56625815
** value. For these latter parameters nothing is written into *pCurrent.)^
56635816
**
5664
-** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5817
+** ^The sqlite3_status() routine returns SQLITE_OK on success and a
56655818
** non-zero [error code] on failure.
56665819
**
56675820
** This routine is threadsafe but is not atomic. This routine can be
56685821
** called while other threads are running the same or different SQLite
56695822
** interfaces. However the values returned in *pCurrent and
@@ -5709,11 +5862,11 @@
57095862
** [SQLITE_CONFIG_PAGECACHE]. The
57105863
** value returned is in pages, not in bytes.</dd>)^
57115864
**
57125865
** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
57135866
** <dd>This parameter returns the number of bytes of page cache
5714
-** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5867
+** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
57155868
** buffer and where forced to overflow to [sqlite3_malloc()]. The
57165869
** returned value includes allocations that overflowed because they
57175870
** where too large (they were larger than the "sz" parameter to
57185871
** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
57195872
** no space was left in the page cache.</dd>)^
@@ -5732,11 +5885,11 @@
57325885
** outstanding at time, this parameter also reports the number of threads
57335886
** using scratch memory at the same time.</dd>)^
57345887
**
57355888
** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
57365889
** <dd>This parameter returns the number of bytes of scratch memory
5737
-** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5890
+** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
57385891
** buffer and where forced to overflow to [sqlite3_malloc()]. The values
57395892
** returned include overflows because the requested allocation was too
57405893
** larger (that is, because the requested allocation was larger than the
57415894
** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
57425895
** slots were available.
@@ -5780,10 +5933,13 @@
57805933
**
57815934
** ^The current value of the requested parameter is written into *pCur
57825935
** and the highest instantaneous value is written into *pHiwtr. ^If
57835936
** the resetFlg is true, then the highest instantaneous value is
57845937
** reset back down to the current value.
5938
+**
5939
+** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5940
+** non-zero [error code] on failure.
57855941
**
57865942
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
57875943
*/
57885944
SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
57895945
@@ -5907,122 +6063,134 @@
59076063
** CAPI3REF: Application Defined Page Cache.
59086064
** KEYWORDS: {page cache}
59096065
**
59106066
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
59116067
** register an alternative page cache implementation by passing in an
5912
-** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5913
-** heap memory used by SQLite is used by the page cache to cache data read
5914
-** from, or ready to be written to, the database file. By implementing a
5915
-** custom page cache using this API, an application can control more
5916
-** precisely the amount of memory consumed by SQLite, the way in which
6068
+** instance of the sqlite3_pcache_methods structure.)^
6069
+** In many applications, most of the heap memory allocated by
6070
+** SQLite is used for the page cache.
6071
+** By implementing a
6072
+** custom page cache using this API, an application can better control
6073
+** the amount of memory consumed by SQLite, the way in which
59176074
** that memory is allocated and released, and the policies used to
59186075
** determine exactly which parts of a database file are cached and for
59196076
** how long.
59206077
**
6078
+** The alternative page cache mechanism is an
6079
+** extreme measure that is only needed by the most demanding applications.
6080
+** The built-in page cache is recommended for most uses.
6081
+**
59216082
** ^(The contents of the sqlite3_pcache_methods structure are copied to an
59226083
** internal buffer by SQLite within the call to [sqlite3_config]. Hence
59236084
** the application may discard the parameter after the call to
59246085
** [sqlite3_config()] returns.)^
59256086
**
5926
-** ^The xInit() method is called once for each call to [sqlite3_initialize()]
6087
+** ^(The xInit() method is called once for each effective
6088
+** call to [sqlite3_initialize()])^
59276089
** (usually only once during the lifetime of the process). ^(The xInit()
59286090
** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5929
-** ^The xInit() method can set up up global structures and/or any mutexes
6091
+** The intent of the xInit() method is to set up global data structures
59306092
** required by the custom page cache implementation.
6093
+** ^(If the xInit() method is NULL, then the
6094
+** built-in default page cache is used instead of the application defined
6095
+** page cache.)^
59316096
**
5932
-** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5933
-** if the application invokes this API. It can be used to clean up
6097
+** ^The xShutdown() method is called by [sqlite3_shutdown()].
6098
+** It can be used to clean up
59346099
** any outstanding resources before process shutdown, if required.
6100
+** ^The xShutdown() method may be NULL.
59356101
**
5936
-** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5937
-** the xInit method, so the xInit method need not be threadsafe. ^The
6102
+** ^SQLite automatically serializes calls to the xInit method,
6103
+** so the xInit method need not be threadsafe. ^The
59386104
** xShutdown method is only called from [sqlite3_shutdown()] so it does
59396105
** not need to be threadsafe either. All other methods must be threadsafe
59406106
** in multithreaded applications.
59416107
**
59426108
** ^SQLite will never invoke xInit() more than once without an intervening
59436109
** call to xShutdown().
59446110
**
5945
-** ^The xCreate() method is used to construct a new cache instance. SQLite
5946
-** will typically create one cache instance for each open database file,
6111
+** ^SQLite invokes the xCreate() method to construct a new cache instance.
6112
+** SQLite will typically create one cache instance for each open database file,
59476113
** though this is not guaranteed. ^The
59486114
** first parameter, szPage, is the size in bytes of the pages that must
59496115
** be allocated by the cache. ^szPage will not be a power of two. ^szPage
59506116
** will the page size of the database file that is to be cached plus an
5951
-** increment (here called "R") of about 100 or 200. ^SQLite will use the
6117
+** increment (here called "R") of about 100 or 200. SQLite will use the
59526118
** extra R bytes on each page to store metadata about the underlying
59536119
** database page on disk. The value of R depends
59546120
** on the SQLite version, the target platform, and how SQLite was compiled.
59556121
** ^R is constant for a particular build of SQLite. ^The second argument to
59566122
** xCreate(), bPurgeable, is true if the cache being created will
59576123
** be used to cache database pages of a file stored on disk, or
5958
-** false if it is used for an in-memory database. ^The cache implementation
6124
+** false if it is used for an in-memory database. The cache implementation
59596125
** does not have to do anything special based with the value of bPurgeable;
59606126
** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
59616127
** never invoke xUnpin() except to deliberately delete a page.
5962
-** ^In other words, a cache created with bPurgeable set to false will
6128
+** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6129
+** false will always have the "discard" flag set to true.
6130
+** ^Hence, a cache created with bPurgeable false will
59636131
** never contain any unpinned pages.
59646132
**
59656133
** ^(The xCachesize() method may be called at any time by SQLite to set the
59666134
** suggested maximum cache-size (number of pages stored by) the cache
59676135
** instance passed as the first argument. This is the value configured using
5968
-** the SQLite "[PRAGMA cache_size]" command.)^ ^As with the bPurgeable
6136
+** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
59696137
** parameter, the implementation is not required to do anything with this
59706138
** value; it is advisory only.
59716139
**
5972
-** ^The xPagecount() method should return the number of pages currently
5973
-** stored in the cache.
6140
+** The xPagecount() method must return the number of pages currently
6141
+** stored in the cache, both pinned and unpinned.
59746142
**
5975
-** ^The xFetch() method is used to fetch a page and return a pointer to it.
5976
-** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5977
-** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5978
-** mimimum key value is 1. After it has been retrieved using xFetch, the page
6143
+** The xFetch() method locates a page in the cache and returns a pointer to
6144
+** the page, or a NULL pointer.
6145
+** A "page", in this context, means a buffer of szPage bytes aligned at an
6146
+** 8-byte boundary. The page to be fetched is determined by the key. ^The
6147
+** mimimum key value is 1. After it has been retrieved using xFetch, the page
59796148
** is considered to be "pinned".
59806149
**
5981
-** ^If the requested page is already in the page cache, then the page cache
6150
+** If the requested page is already in the page cache, then the page cache
59826151
** implementation must return a pointer to the page buffer with its content
5983
-** intact. ^(If the requested page is not already in the cache, then the
5984
-** behavior of the cache implementation is determined by the value of the
5985
-** createFlag parameter passed to xFetch, according to the following table:
6152
+** intact. If the requested page is not already in the cache, then the
6153
+** behavior of the cache implementation should use the value of the createFlag
6154
+** parameter to help it determined what action to take:
59866155
**
59876156
** <table border=1 width=85% align=center>
59886157
** <tr><th> createFlag <th> Behaviour when page is not already in cache
59896158
** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
59906159
** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
59916160
** Otherwise return NULL.
59926161
** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
59936162
** NULL if allocating a new page is effectively impossible.
5994
-** </table>)^
6163
+** </table>
59956164
**
5996
-** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If
5997
-** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
6165
+** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6166
+** will only use a createFlag of 2 after a prior call with a createFlag of 1
6167
+** failed.)^ In between the to xFetch() calls, SQLite may
59986168
** attempt to unpin one or more cache pages by spilling the content of
5999
-** pinned pages to disk and synching the operating system disk cache. After
6000
-** attempting to unpin pages, the xFetch() method will be invoked again with
6001
-** a createFlag of 2.
6169
+** pinned pages to disk and synching the operating system disk cache.
60026170
**
60036171
** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6004
-** as its second argument. ^(If the third parameter, discard, is non-zero,
6005
-** then the page should be evicted from the cache. In this case SQLite
6006
-** assumes that the next time the page is retrieved from the cache using
6007
-** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
6008
-** zero, then the page is considered to be unpinned. ^The cache implementation
6172
+** as its second argument. If the third parameter, discard, is non-zero,
6173
+** then the page must be evicted from the cache.
6174
+** ^If the discard parameter is
6175
+** zero, then the page may be discarded or retained at the discretion of
6176
+** page cache implementation. ^The page cache implementation
60096177
** may choose to evict unpinned pages at any time.
60106178
**
6011
-** ^(The cache is not required to perform any reference counting. A single
6179
+** The cache must not perform any reference counting. A single
60126180
** call to xUnpin() unpins the page regardless of the number of prior calls
6013
-** to xFetch().)^
6181
+** to xFetch().
60146182
**
6015
-** ^The xRekey() method is used to change the key value associated with the
6016
-** page passed as the second argument from oldKey to newKey. ^If the cache
6017
-** previously contains an entry associated with newKey, it should be
6183
+** The xRekey() method is used to change the key value associated with the
6184
+** page passed as the second argument. If the cache
6185
+** previously contains an entry associated with newKey, it must be
60186186
** discarded. ^Any prior cache entry associated with newKey is guaranteed not
60196187
** to be pinned.
60206188
**
6021
-** ^When SQLite calls the xTruncate() method, the cache must discard all
6189
+** When SQLite calls the xTruncate() method, the cache must discard all
60226190
** existing cache entries with page numbers (keys) greater than or equal
6023
-** to the value of the iLimit parameter passed to xTruncate(). ^If any
6191
+** to the value of the iLimit parameter passed to xTruncate(). If any
60246192
** of these pages are pinned, they are implicitly unpinned, meaning that
60256193
** they can be safely discarded.
60266194
**
60276195
** ^The xDestroy() method is used to delete a cache allocated by xCreate().
60286196
** All resources associated with the specified cache should be freed. ^After
@@ -6496,10 +6664,66 @@
64966664
#if 0
64976665
} /* End of the 'extern "C"' block */
64986666
#endif
64996667
#endif
65006668
6669
+/*
6670
+** 2010 August 30
6671
+**
6672
+** The author disclaims copyright to this source code. In place of
6673
+** a legal notice, here is a blessing:
6674
+**
6675
+** May you do good and not evil.
6676
+** May you find forgiveness for yourself and forgive others.
6677
+** May you share freely, never taking more than you give.
6678
+**
6679
+*************************************************************************
6680
+*/
6681
+
6682
+#ifndef _SQLITE3RTREE_H_
6683
+#define _SQLITE3RTREE_H_
6684
+
6685
+
6686
+#if 0
6687
+extern "C" {
6688
+#endif
6689
+
6690
+typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6691
+
6692
+/*
6693
+** Register a geometry callback named zGeom that can be used as part of an
6694
+** R-Tree geometry query as follows:
6695
+**
6696
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6697
+*/
6698
+SQLITE_API int sqlite3_rtree_geometry_callback(
6699
+ sqlite3 *db,
6700
+ const char *zGeom,
6701
+ int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6702
+ void *pContext
6703
+);
6704
+
6705
+
6706
+/*
6707
+** A pointer to a structure of the following type is passed as the first
6708
+** argument to callbacks registered using rtree_geometry_callback().
6709
+*/
6710
+struct sqlite3_rtree_geometry {
6711
+ void *pContext; /* Copy of pContext passed to s_r_g_c() */
6712
+ int nParam; /* Size of array aParam[] */
6713
+ double *aParam; /* Parameters passed to SQL geom function */
6714
+ void *pUser; /* Callback implementation user data */
6715
+ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
6716
+};
6717
+
6718
+
6719
+#if 0
6720
+} /* end of the 'extern "C"' block */
6721
+#endif
6722
+
6723
+#endif /* ifndef _SQLITE3RTREE_H_ */
6724
+
65016725
65026726
/************** End of sqlite3.h *********************************************/
65036727
/************** Continuing where we left off in sqliteInt.h ******************/
65046728
/************** Include hash.h in the middle of sqliteInt.h ******************/
65056729
/************** Begin file hash.h ********************************************/
@@ -7066,10 +7290,11 @@
70667290
typedef struct Schema Schema;
70677291
typedef struct Expr Expr;
70687292
typedef struct ExprList ExprList;
70697293
typedef struct ExprSpan ExprSpan;
70707294
typedef struct FKey FKey;
7295
+typedef struct FuncDestructor FuncDestructor;
70717296
typedef struct FuncDef FuncDef;
70727297
typedef struct FuncDefHash FuncDefHash;
70737298
typedef struct IdList IdList;
70747299
typedef struct Index Index;
70757300
typedef struct IndexSample IndexSample;
@@ -7172,16 +7397,15 @@
71727397
** following values.
71737398
**
71747399
** NOTE: These values must match the corresponding PAGER_ values in
71757400
** pager.h.
71767401
*/
7177
-#define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
7402
+#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
71787403
#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
7179
-#define BTREE_MEMORY 4 /* In-memory DB. No argument */
7180
-#define BTREE_READONLY 8 /* Open the database in read-only mode */
7181
-#define BTREE_READWRITE 16 /* Open for both reading and writing */
7182
-#define BTREE_CREATE 32 /* Create the database if it does not exist */
7404
+#define BTREE_MEMORY 4 /* This is an in-memory DB */
7405
+#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
7406
+#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
71837407
71847408
SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
71857409
SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
71867410
SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
71877411
SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
@@ -7213,15 +7437,21 @@
72137437
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
72147438
72157439
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
72167440
72177441
/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7218
-** of the following flags:
7442
+** of the flags shown below.
7443
+**
7444
+** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7445
+** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7446
+** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
7447
+** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7448
+** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
7449
+** indices.)
72197450
*/
72207451
#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
7221
-#define BTREE_ZERODATA 2 /* Table has keys only - no data */
7222
-#define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
7452
+#define BTREE_BLOBKEY 2 /* Table has keys only - no data */
72237453
72247454
SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
72257455
SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
72267456
SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
72277457
@@ -7838,10 +8068,11 @@
78388068
**
78398069
** NOTE: These values must match the corresponding BTREE_ values in btree.h.
78408070
*/
78418071
#define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
78428072
#define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
8073
+#define PAGER_MEMORY 0x0004 /* In-memory database */
78438074
78448075
/*
78458076
** Valid values for the second argument to sqlite3PagerLockingMode().
78468077
*/
78478078
#define PAGER_LOCKINGMODE_QUERY -1
@@ -8472,12 +8703,12 @@
84728703
#define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
84738704
#define sqlite3_mutex_free(X)
84748705
#define sqlite3_mutex_enter(X)
84758706
#define sqlite3_mutex_try(X) SQLITE_OK
84768707
#define sqlite3_mutex_leave(X)
8477
-#define sqlite3_mutex_held(X) 1
8478
-#define sqlite3_mutex_notheld(X) 1
8708
+#define sqlite3_mutex_held(X) ((void)(X),1)
8709
+#define sqlite3_mutex_notheld(X) ((void)(X),1)
84798710
#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
84808711
#define sqlite3MutexInit() SQLITE_OK
84818712
#define sqlite3MutexEnd()
84828713
#endif /* defined(SQLITE_MUTEX_OMIT) */
84838714
@@ -8795,10 +9026,31 @@
87959026
void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
87969027
void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
87979028
void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
87989029
char *zName; /* SQL name of the function. */
87999030
FuncDef *pHash; /* Next with a different name but the same hash */
9031
+ FuncDestructor *pDestructor; /* Reference counted destructor function */
9032
+};
9033
+
9034
+/*
9035
+** This structure encapsulates a user-function destructor callback (as
9036
+** configured using create_function_v2()) and a reference counter. When
9037
+** create_function_v2() is called to create a function with a destructor,
9038
+** a single object of this type is allocated. FuncDestructor.nRef is set to
9039
+** the number of FuncDef objects created (either 1 or 3, depending on whether
9040
+** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9041
+** member of each of the new FuncDef objects is set to point to the allocated
9042
+** FuncDestructor.
9043
+**
9044
+** Thereafter, when one of the FuncDef objects is deleted, the reference
9045
+** count on this object is decremented. When it reaches 0, the destructor
9046
+** is invoked and the FuncDestructor structure freed.
9047
+*/
9048
+struct FuncDestructor {
9049
+ int nRef;
9050
+ void (*xDestroy)(void *);
9051
+ void *pUserData;
88009052
};
88019053
88029054
/*
88039055
** Possible values for FuncDef.flags
88049056
*/
@@ -8835,19 +9087,19 @@
88359087
** FuncDef.flags variable is set to the value passed as the flags
88369088
** parameter.
88379089
*/
88389090
#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
88399091
{nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8840
- SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
9092
+ SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
88419093
#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
88429094
{nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8843
- pArg, 0, xFunc, 0, 0, #zName, 0}
9095
+ pArg, 0, xFunc, 0, 0, #zName, 0, 0}
88449096
#define LIKEFUNC(zName, nArg, arg, flags) \
8845
- {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
9097
+ {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
88469098
#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
88479099
{nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8848
- SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
9100
+ SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
88499101
88509102
/*
88519103
** All current savepoints are stored in a linked list starting at
88529104
** sqlite3.pSavepoint. The first element in the list is the most recently
88539105
** opened savepoint. Savepoints are added to the list by the vdbe
@@ -9063,10 +9315,11 @@
90639315
int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
90649316
int nCol; /* Number of columns in this table */
90659317
Column *aCol; /* Information about each column */
90669318
Index *pIndex; /* List of SQL indexes on this table. */
90679319
int tnum; /* Root BTree node for this table (see note above) */
9320
+ unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
90689321
Select *pSelect; /* NULL for tables. Points to definition if a view. */
90699322
u16 nRef; /* Number of pointers to this Table */
90709323
u8 tabFlags; /* Mask of TF_* values */
90719324
u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
90729325
FKey *pFKey; /* Linked list of all foreign keys in this table */
@@ -10341,11 +10594,11 @@
1034110594
SQLITE_PRIVATE void sqlite3ScratchFree(void*);
1034210595
SQLITE_PRIVATE void *sqlite3PageMalloc(int);
1034310596
SQLITE_PRIVATE void sqlite3PageFree(void*);
1034410597
SQLITE_PRIVATE void sqlite3MemSetDefault(void);
1034510598
SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10346
-SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10599
+SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
1034710600
1034810601
/*
1034910602
** On systems with ample stack space and that support alloca(), make
1035010603
** use of alloca() to obtain space for large automatic objects. By default,
1035110604
** obtain space from malloc().
@@ -10512,11 +10765,10 @@
1051210765
SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
1051310766
SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
1051410767
SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
1051510768
SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
1051610769
SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10517
-SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
1051810770
SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
1051910771
SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
1052010772
SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
1052110773
SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
1052210774
SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
@@ -10632,12 +10884,10 @@
1063210884
# define sqlite3AuthContextPush(a,b,c)
1063310885
# define sqlite3AuthContextPop(a) ((void)(a))
1063410886
#endif
1063510887
SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
1063610888
SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10637
-SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10638
- int omitJournal, int nCache, int flags, Btree **ppBtree);
1063910889
SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
1064010890
SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
1064110891
SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
1064210892
SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
1064310893
SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
@@ -10759,11 +11009,13 @@
1075911009
SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
1076011010
SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
1076111011
SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
1076211012
SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
1076311013
void (*)(sqlite3_context*,int,sqlite3_value **),
10764
- void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
11014
+ void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11015
+ FuncDestructor *pDestructor
11016
+);
1076511017
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
1076611018
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
1076711019
1076811020
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
1076911021
SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
@@ -11679,10 +11931,11 @@
1167911931
Bool useRandomRowid; /* Generate new record numbers semi-randomly */
1168011932
Bool nullRow; /* True if pointing to a row with no data */
1168111933
Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
1168211934
Bool isTable; /* True if a table requiring integer keys */
1168311935
Bool isIndex; /* True if an index containing keys only - no data */
11936
+ Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
1168411937
i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
1168511938
Btree *pBt; /* Separate file holding temporary table */
1168611939
int pseudoTableReg; /* Register holding pseudotable content. */
1168711940
KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
1168811941
int nField; /* Number of fields in the header */
@@ -11773,10 +12026,14 @@
1177312026
char *z; /* String or BLOB value */
1177412027
int n; /* Number of characters in string value, excluding '\0' */
1177512028
u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
1177612029
u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
1177712030
u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12031
+#ifdef SQLITE_DEBUG
12032
+ Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
12033
+ void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
12034
+#endif
1177812035
void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
1177912036
char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
1178012037
};
1178112038
1178212039
/* One or more of the following flags are set to indicate the validOK
@@ -11799,10 +12056,11 @@
1179912056
#define MEM_Int 0x0004 /* Value is an integer */
1180012057
#define MEM_Real 0x0008 /* Value is a real number */
1180112058
#define MEM_Blob 0x0010 /* Value is a BLOB */
1180212059
#define MEM_RowSet 0x0020 /* Value is a RowSet object */
1180312060
#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
12061
+#define MEM_Invalid 0x0080 /* Value is undefined */
1180412062
#define MEM_TypeMask 0x00ff /* Mask of type bits */
1180512063
1180612064
/* Whenever Mem contains a valid string or blob representation, one of
1180712065
** the following flags must be set to determine the memory management
1180812066
** policy for Mem.z. The MEM_Term flag tells us whether or not the
@@ -11812,23 +12070,29 @@
1181212070
#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
1181312071
#define MEM_Static 0x0800 /* Mem.z points to a static string */
1181412072
#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
1181512073
#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
1181612074
#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
11817
-
1181812075
#ifdef SQLITE_OMIT_INCRBLOB
1181912076
#undef MEM_Zero
1182012077
#define MEM_Zero 0x0000
1182112078
#endif
11822
-
1182312079
1182412080
/*
1182512081
** Clear any existing type flags from a Mem and replace them with f
1182612082
*/
1182712083
#define MemSetTypeFlag(p, f) \
1182812084
((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
1182912085
12086
+/*
12087
+** Return true if a memory cell is not marked as invalid. This macro
12088
+** is for use inside assert() statements only.
12089
+*/
12090
+#ifdef SQLITE_DEBUG
12091
+#define memIsValid(M) ((M)->flags & MEM_Invalid)==0
12092
+#endif
12093
+
1183012094
1183112095
/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
1183212096
** additional information about auxiliary information bound to arguments
1183312097
** of the function. This is used to implement the sqlite3_get_auxdata()
1183412098
** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
@@ -12012,10 +12276,14 @@
1201212276
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
1201312277
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
1201412278
SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
1201512279
SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
1201612280
SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12281
+
12282
+#ifdef SQLITE_DEBUG
12283
+SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12284
+#endif
1201712285
1201812286
#ifndef SQLITE_OMIT_FOREIGN_KEY
1201912287
SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
1202012288
#else
1202112289
# define sqlite3VdbeCheckFk(p,i) 0
@@ -13518,10 +13786,16 @@
1351813786
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
1351913787
return pVfs->xSleep(pVfs, nMicro);
1352013788
}
1352113789
SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
1352213790
int rc;
13791
+ /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
13792
+ ** method to get the current date and time if that method is available
13793
+ ** (if iVersion is 2 or greater and the function pointer is not NULL) and
13794
+ ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
13795
+ ** unavailable.
13796
+ */
1352313797
if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
1352413798
rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
1352513799
}else{
1352613800
double r;
1352713801
rc = pVfs->xCurrentTime(pVfs, &r);
@@ -13901,11 +14175,11 @@
1390114175
** routines and redirected to xFree.
1390214176
*/
1390314177
static void *sqlite3MemRealloc(void *pPrior, int nByte){
1390414178
sqlite3_int64 *p = (sqlite3_int64*)pPrior;
1390514179
assert( pPrior!=0 && nByte>0 );
13906
- nByte = ROUND8(nByte);
14180
+ assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
1390714181
p--;
1390814182
p = realloc(p, nByte+8 );
1390914183
if( p ){
1391014184
p[0] = nByte;
1391114185
p++;
@@ -14307,10 +14581,11 @@
1430714581
*/
1430814582
static void *sqlite3MemRealloc(void *pPrior, int nByte){
1430914583
struct MemBlockHdr *pOldHdr;
1431014584
void *pNew;
1431114585
assert( mem.disallow==0 );
14586
+ assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
1431214587
pOldHdr = sqlite3MemsysGetHeader(pPrior);
1431314588
pNew = sqlite3MemMalloc(nByte);
1431414589
if( pNew ){
1431514590
memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
1431614591
if( nByte>pOldHdr->iSize ){
@@ -15576,11 +15851,11 @@
1557615851
*/
1557715852
static void *memsys5Realloc(void *pPrior, int nBytes){
1557815853
int nOld;
1557915854
void *p;
1558015855
assert( pPrior!=0 );
15581
- assert( (nBytes&(nBytes-1))==0 );
15856
+ assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
1558215857
assert( nBytes>=0 );
1558315858
if( nBytes==0 ){
1558415859
return 0;
1558515860
}
1558615861
nOld = memsys5Size(pPrior);
@@ -17100,10 +17375,70 @@
1710017375
*************************************************************************
1710117376
**
1710217377
** Memory allocation functions used throughout sqlite.
1710317378
*/
1710417379
17380
+/*
17381
+** Attempt to release up to n bytes of non-essential memory currently
17382
+** held by SQLite. An example of non-essential memory is memory used to
17383
+** cache database pages that are not currently in use.
17384
+*/
17385
+SQLITE_API int sqlite3_release_memory(int n){
17386
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17387
+ return sqlite3PcacheReleaseMemory(n);
17388
+#else
17389
+ /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17390
+ ** is a no-op returning zero if SQLite is not compiled with
17391
+ ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17392
+ UNUSED_PARAMETER(n);
17393
+ return 0;
17394
+#endif
17395
+}
17396
+
17397
+/*
17398
+** An instance of the following object records the location of
17399
+** each unused scratch buffer.
17400
+*/
17401
+typedef struct ScratchFreeslot {
17402
+ struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
17403
+} ScratchFreeslot;
17404
+
17405
+/*
17406
+** State information local to the memory allocation subsystem.
17407
+*/
17408
+static SQLITE_WSD struct Mem0Global {
17409
+ sqlite3_mutex *mutex; /* Mutex to serialize access */
17410
+
17411
+ /*
17412
+ ** The alarm callback and its arguments. The mem0.mutex lock will
17413
+ ** be held while the callback is running. Recursive calls into
17414
+ ** the memory subsystem are allowed, but no new callbacks will be
17415
+ ** issued.
17416
+ */
17417
+ sqlite3_int64 alarmThreshold;
17418
+ void (*alarmCallback)(void*, sqlite3_int64,int);
17419
+ void *alarmArg;
17420
+
17421
+ /*
17422
+ ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17423
+ ** (so that a range test can be used to determine if an allocation
17424
+ ** being freed came from pScratch) and a pointer to the list of
17425
+ ** unused scratch allocations.
17426
+ */
17427
+ void *pScratchEnd;
17428
+ ScratchFreeslot *pScratchFree;
17429
+ u32 nScratchFree;
17430
+
17431
+ /*
17432
+ ** True if heap is nearly "full" where "full" is defined by the
17433
+ ** sqlite3_soft_heap_limit() setting.
17434
+ */
17435
+ int nearlyFull;
17436
+} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17437
+
17438
+#define mem0 GLOBAL(struct Mem0Global, mem0)
17439
+
1710517440
/*
1710617441
** This routine runs when the memory allocator sees that the
1710717442
** total memory allocation is about to exceed the soft heap
1710817443
** limit.
1710917444
*/
@@ -17114,82 +17449,70 @@
1711417449
){
1711517450
UNUSED_PARAMETER2(NotUsed, NotUsed2);
1711617451
sqlite3_release_memory(allocSize);
1711717452
}
1711817453
17454
+/*
17455
+** Change the alarm callback
17456
+*/
17457
+static int sqlite3MemoryAlarm(
17458
+ void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17459
+ void *pArg,
17460
+ sqlite3_int64 iThreshold
17461
+){
17462
+ int nUsed;
17463
+ sqlite3_mutex_enter(mem0.mutex);
17464
+ mem0.alarmCallback = xCallback;
17465
+ mem0.alarmArg = pArg;
17466
+ mem0.alarmThreshold = iThreshold;
17467
+ nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17468
+ mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17469
+ sqlite3_mutex_leave(mem0.mutex);
17470
+ return SQLITE_OK;
17471
+}
17472
+
17473
+#ifndef SQLITE_OMIT_DEPRECATED
17474
+/*
17475
+** Deprecated external interface. Internal/core SQLite code
17476
+** should call sqlite3MemoryAlarm.
17477
+*/
17478
+SQLITE_API int sqlite3_memory_alarm(
17479
+ void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17480
+ void *pArg,
17481
+ sqlite3_int64 iThreshold
17482
+){
17483
+ return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17484
+}
17485
+#endif
17486
+
1711917487
/*
1712017488
** Set the soft heap-size limit for the library. Passing a zero or
1712117489
** negative value indicates no limit.
1712217490
*/
17123
-SQLITE_API void sqlite3_soft_heap_limit(int n){
17124
- sqlite3_uint64 iLimit;
17125
- int overage;
17126
- if( n<0 ){
17127
- iLimit = 0;
17128
- }else{
17129
- iLimit = n;
17130
- }
17491
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17492
+ sqlite3_int64 priorLimit;
17493
+ sqlite3_int64 excess;
1713117494
#ifndef SQLITE_OMIT_AUTOINIT
1713217495
sqlite3_initialize();
1713317496
#endif
17134
- if( iLimit>0 ){
17135
- sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
17497
+ sqlite3_mutex_enter(mem0.mutex);
17498
+ priorLimit = mem0.alarmThreshold;
17499
+ sqlite3_mutex_leave(mem0.mutex);
17500
+ if( n<0 ) return priorLimit;
17501
+ if( n>0 ){
17502
+ sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
1713617503
}else{
1713717504
sqlite3MemoryAlarm(0, 0, 0);
1713817505
}
17139
- overage = (int)(sqlite3_memory_used() - (i64)n);
17140
- if( overage>0 ){
17141
- sqlite3_release_memory(overage);
17142
- }
17143
-}
17144
-
17145
-/*
17146
-** Attempt to release up to n bytes of non-essential memory currently
17147
-** held by SQLite. An example of non-essential memory is memory used to
17148
-** cache database pages that are not currently in use.
17149
-*/
17150
-SQLITE_API int sqlite3_release_memory(int n){
17151
-#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17152
- int nRet = 0;
17153
- nRet += sqlite3PcacheReleaseMemory(n-nRet);
17154
- return nRet;
17155
-#else
17156
- UNUSED_PARAMETER(n);
17157
- return SQLITE_OK;
17158
-#endif
17159
-}
17160
-
17161
-/*
17162
-** State information local to the memory allocation subsystem.
17163
-*/
17164
-static SQLITE_WSD struct Mem0Global {
17165
- /* Number of free pages for scratch and page-cache memory */
17166
- u32 nScratchFree;
17167
- u32 nPageFree;
17168
-
17169
- sqlite3_mutex *mutex; /* Mutex to serialize access */
17170
-
17171
- /*
17172
- ** The alarm callback and its arguments. The mem0.mutex lock will
17173
- ** be held while the callback is running. Recursive calls into
17174
- ** the memory subsystem are allowed, but no new callbacks will be
17175
- ** issued.
17176
- */
17177
- sqlite3_int64 alarmThreshold;
17178
- void (*alarmCallback)(void*, sqlite3_int64,int);
17179
- void *alarmArg;
17180
-
17181
- /*
17182
- ** Pointers to the end of sqlite3GlobalConfig.pScratch and
17183
- ** sqlite3GlobalConfig.pPage to a block of memory that records
17184
- ** which pages are available.
17185
- */
17186
- u32 *aScratchFree;
17187
- u32 *aPageFree;
17188
-} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17189
-
17190
-#define mem0 GLOBAL(struct Mem0Global, mem0)
17506
+ excess = sqlite3_memory_used() - n;
17507
+ if( excess>0 ) sqlite3_release_memory(excess & 0x7fffffff);
17508
+ return priorLimit;
17509
+}
17510
+SQLITE_API void sqlite3_soft_heap_limit(int n){
17511
+ if( n<0 ) n = 0;
17512
+ sqlite3_soft_heap_limit64(n);
17513
+}
1719117514
1719217515
/*
1719317516
** Initialize the memory allocation subsystem.
1719417517
*/
1719517518
SQLITE_PRIVATE int sqlite3MallocInit(void){
@@ -17199,39 +17522,48 @@
1719917522
memset(&mem0, 0, sizeof(mem0));
1720017523
if( sqlite3GlobalConfig.bCoreMutex ){
1720117524
mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
1720217525
}
1720317526
if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17204
- && sqlite3GlobalConfig.nScratch>=0 ){
17205
- int i;
17206
- sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
17207
- mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
17208
- [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
17209
- for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
17210
- mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
17527
+ && sqlite3GlobalConfig.nScratch>0 ){
17528
+ int i, n, sz;
17529
+ ScratchFreeslot *pSlot;
17530
+ sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17531
+ sqlite3GlobalConfig.szScratch = sz;
17532
+ pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17533
+ n = sqlite3GlobalConfig.nScratch;
17534
+ mem0.pScratchFree = pSlot;
17535
+ mem0.nScratchFree = n;
17536
+ for(i=0; i<n-1; i++){
17537
+ pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17538
+ pSlot = pSlot->pNext;
17539
+ }
17540
+ pSlot->pNext = 0;
17541
+ mem0.pScratchEnd = (void*)&pSlot[1];
1721117542
}else{
17543
+ mem0.pScratchEnd = 0;
1721217544
sqlite3GlobalConfig.pScratch = 0;
1721317545
sqlite3GlobalConfig.szScratch = 0;
17214
- }
17215
- if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
17216
- && sqlite3GlobalConfig.nPage>=1 ){
17217
- int i;
17218
- int overhead;
17219
- int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
17220
- int n = sqlite3GlobalConfig.nPage;
17221
- overhead = (4*n + sz - 1)/sz;
17222
- sqlite3GlobalConfig.nPage -= overhead;
17223
- mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
17224
- [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
17225
- for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
17226
- mem0.nPageFree = sqlite3GlobalConfig.nPage;
17227
- }else{
17546
+ sqlite3GlobalConfig.nScratch = 0;
17547
+ }
17548
+ if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17549
+ || sqlite3GlobalConfig.nPage<1 ){
1722817550
sqlite3GlobalConfig.pPage = 0;
1722917551
sqlite3GlobalConfig.szPage = 0;
17552
+ sqlite3GlobalConfig.nPage = 0;
1723017553
}
1723117554
return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
1723217555
}
17556
+
17557
+/*
17558
+** Return true if the heap is currently under memory pressure - in other
17559
+** words if the amount of heap used is close to the limit set by
17560
+** sqlite3_soft_heap_limit().
17561
+*/
17562
+SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17563
+ return mem0.nearlyFull;
17564
+}
1723317565
1723417566
/*
1723517567
** Deinitialize the memory allocation subsystem.
1723617568
*/
1723717569
SQLITE_PRIVATE void sqlite3MallocEnd(void){
@@ -17263,40 +17595,10 @@
1726317595
sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
1726417596
res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
1726517597
return res;
1726617598
}
1726717599
17268
-/*
17269
-** Change the alarm callback
17270
-*/
17271
-SQLITE_PRIVATE int sqlite3MemoryAlarm(
17272
- void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17273
- void *pArg,
17274
- sqlite3_int64 iThreshold
17275
-){
17276
- sqlite3_mutex_enter(mem0.mutex);
17277
- mem0.alarmCallback = xCallback;
17278
- mem0.alarmArg = pArg;
17279
- mem0.alarmThreshold = iThreshold;
17280
- sqlite3_mutex_leave(mem0.mutex);
17281
- return SQLITE_OK;
17282
-}
17283
-
17284
-#ifndef SQLITE_OMIT_DEPRECATED
17285
-/*
17286
-** Deprecated external interface. Internal/core SQLite code
17287
-** should call sqlite3MemoryAlarm.
17288
-*/
17289
-SQLITE_API int sqlite3_memory_alarm(
17290
- void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17291
- void *pArg,
17292
- sqlite3_int64 iThreshold
17293
-){
17294
- return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17295
-}
17296
-#endif
17297
-
1729817600
/*
1729917601
** Trigger the alarm
1730017602
*/
1730117603
static void sqlite3MallocAlarm(int nByte){
1730217604
void (*xCallback)(void*,sqlite3_int64,int);
@@ -17325,18 +17627,23 @@
1732517627
nFull = sqlite3GlobalConfig.m.xRoundup(n);
1732617628
sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
1732717629
if( mem0.alarmCallback!=0 ){
1732817630
int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
1732917631
if( nUsed+nFull >= mem0.alarmThreshold ){
17632
+ mem0.nearlyFull = 1;
1733017633
sqlite3MallocAlarm(nFull);
17634
+ }else{
17635
+ mem0.nearlyFull = 0;
1733117636
}
1733217637
}
1733317638
p = sqlite3GlobalConfig.m.xMalloc(nFull);
17639
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
1733417640
if( p==0 && mem0.alarmCallback ){
1733517641
sqlite3MallocAlarm(nFull);
1733617642
p = sqlite3GlobalConfig.m.xMalloc(nFull);
1733717643
}
17644
+#endif
1733817645
if( p ){
1733917646
nFull = sqlite3MallocSize(p);
1734017647
sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
1734117648
sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
1734217649
}
@@ -17348,11 +17655,13 @@
1734817655
** Allocate memory. This routine is like sqlite3_malloc() except that it
1734917656
** assumes the memory subsystem has already been initialized.
1735017657
*/
1735117658
SQLITE_PRIVATE void *sqlite3Malloc(int n){
1735217659
void *p;
17353
- if( n<=0 || n>=0x7fffff00 ){
17660
+ if( n<=0 /* IMP: R-65312-04917 */
17661
+ || n>=0x7fffff00
17662
+ ){
1735417663
/* A memory allocation of a number of bytes which is near the maximum
1735517664
** signed integer value might cause an integer overflow inside of the
1735617665
** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
1735717666
** 255 bytes of overhead. SQLite itself will never use anything near
1735817667
** this amount. The only way to reach the limit is with sqlite3_malloc() */
@@ -17362,10 +17671,11 @@
1736217671
mallocWithAlarm(n, &p);
1736317672
sqlite3_mutex_leave(mem0.mutex);
1736417673
}else{
1736517674
p = sqlite3GlobalConfig.m.xMalloc(n);
1736617675
}
17676
+ assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
1736717677
return p;
1736817678
}
1736917679
1737017680
/*
1737117681
** This version of the memory allocation is for use by the application.
@@ -17399,64 +17709,70 @@
1739917709
** embedded processor.
1740017710
*/
1740117711
SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
1740217712
void *p;
1740317713
assert( n>0 );
17714
+
17715
+ sqlite3_mutex_enter(mem0.mutex);
17716
+ if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
17717
+ p = mem0.pScratchFree;
17718
+ mem0.pScratchFree = mem0.pScratchFree->pNext;
17719
+ mem0.nScratchFree--;
17720
+ sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17721
+ sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17722
+ sqlite3_mutex_leave(mem0.mutex);
17723
+ }else{
17724
+ if( sqlite3GlobalConfig.bMemstat ){
17725
+ sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17726
+ n = mallocWithAlarm(n, &p);
17727
+ if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17728
+ sqlite3_mutex_leave(mem0.mutex);
17729
+ }else{
17730
+ sqlite3_mutex_leave(mem0.mutex);
17731
+ p = sqlite3GlobalConfig.m.xMalloc(n);
17732
+ }
17733
+ sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17734
+ }
17735
+ assert( sqlite3_mutex_notheld(mem0.mutex) );
17736
+
1740417737
1740517738
#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17406
- /* Verify that no more than two scratch allocation per thread
17407
- ** is outstanding at one time. (This is only checked in the
17739
+ /* Verify that no more than two scratch allocations per thread
17740
+ ** are outstanding at one time. (This is only checked in the
1740817741
** single-threaded case since checking in the multi-threaded case
1740917742
** would be much more complicated.) */
1741017743
assert( scratchAllocOut<=1 );
17411
-#endif
17412
-
17413
- if( sqlite3GlobalConfig.szScratch<n ){
17414
- goto scratch_overflow;
17415
- }else{
17416
- sqlite3_mutex_enter(mem0.mutex);
17417
- if( mem0.nScratchFree==0 ){
17418
- sqlite3_mutex_leave(mem0.mutex);
17419
- goto scratch_overflow;
17420
- }else{
17421
- int i;
17422
- i = mem0.aScratchFree[--mem0.nScratchFree];
17423
- i *= sqlite3GlobalConfig.szScratch;
17424
- sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17425
- sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17426
- sqlite3_mutex_leave(mem0.mutex);
17427
- p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
17428
- assert( (((u8*)p - (u8*)0) & 7)==0 );
17429
- }
17430
- }
17431
-#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17432
- scratchAllocOut = p!=0;
17433
-#endif
17434
-
17435
- return p;
17436
-
17437
-scratch_overflow:
17438
- if( sqlite3GlobalConfig.bMemstat ){
17439
- sqlite3_mutex_enter(mem0.mutex);
17440
- sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17441
- n = mallocWithAlarm(n, &p);
17442
- if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17443
- sqlite3_mutex_leave(mem0.mutex);
17444
- }else{
17445
- p = sqlite3GlobalConfig.m.xMalloc(n);
17446
- }
17447
- sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17448
-#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17449
- scratchAllocOut = p!=0;
17450
-#endif
17451
- return p;
17744
+ if( p ) scratchAllocOut++;
17745
+#endif
17746
+
17747
+ return p;
1745217748
}
1745317749
SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
1745417750
if( p ){
17455
- if( sqlite3GlobalConfig.pScratch==0
17456
- || p<sqlite3GlobalConfig.pScratch
17457
- || p>=(void*)mem0.aScratchFree ){
17751
+
17752
+#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17753
+ /* Verify that no more than two scratch allocation per thread
17754
+ ** is outstanding at one time. (This is only checked in the
17755
+ ** single-threaded case since checking in the multi-threaded case
17756
+ ** would be much more complicated.) */
17757
+ assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17758
+ scratchAllocOut--;
17759
+#endif
17760
+
17761
+ if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
17762
+ /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
17763
+ ScratchFreeslot *pSlot;
17764
+ pSlot = (ScratchFreeslot*)p;
17765
+ sqlite3_mutex_enter(mem0.mutex);
17766
+ pSlot->pNext = mem0.pScratchFree;
17767
+ mem0.pScratchFree = pSlot;
17768
+ mem0.nScratchFree++;
17769
+ assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
17770
+ sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17771
+ sqlite3_mutex_leave(mem0.mutex);
17772
+ }else{
17773
+ /* Release memory back to the heap */
1745817774
assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
1745917775
assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
1746017776
sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
1746117777
if( sqlite3GlobalConfig.bMemstat ){
1746217778
int iSize = sqlite3MallocSize(p);
@@ -17467,30 +17783,10 @@
1746717783
sqlite3GlobalConfig.m.xFree(p);
1746817784
sqlite3_mutex_leave(mem0.mutex);
1746917785
}else{
1747017786
sqlite3GlobalConfig.m.xFree(p);
1747117787
}
17472
- }else{
17473
- int i;
17474
- i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
17475
- i /= sqlite3GlobalConfig.szScratch;
17476
- assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
17477
- sqlite3_mutex_enter(mem0.mutex);
17478
- assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
17479
- mem0.aScratchFree[mem0.nScratchFree++] = i;
17480
- sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17481
- sqlite3_mutex_leave(mem0.mutex);
17482
-
17483
-#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17484
- /* Verify that no more than two scratch allocation per thread
17485
- ** is outstanding at one time. (This is only checked in the
17486
- ** single-threaded case since checking in the multi-threaded case
17487
- ** would be much more complicated.) */
17488
- assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17489
- scratchAllocOut = 0;
17490
-#endif
17491
-
1749217788
}
1749317789
}
1749417790
}
1749517791
1749617792
/*
@@ -17527,11 +17823,11 @@
1752717823
1752817824
/*
1752917825
** Free memory previously obtained from sqlite3Malloc().
1753017826
*/
1753117827
SQLITE_API void sqlite3_free(void *p){
17532
- if( p==0 ) return;
17828
+ if( p==0 ) return; /* IMP: R-49053-54554 */
1753317829
assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
1753417830
assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
1753517831
if( sqlite3GlobalConfig.bMemstat ){
1753617832
sqlite3_mutex_enter(mem0.mutex);
1753717833
sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
@@ -17574,21 +17870,24 @@
1757417870
*/
1757517871
SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
1757617872
int nOld, nNew;
1757717873
void *pNew;
1757817874
if( pOld==0 ){
17579
- return sqlite3Malloc(nBytes);
17875
+ return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
1758017876
}
1758117877
if( nBytes<=0 ){
17582
- sqlite3_free(pOld);
17878
+ sqlite3_free(pOld); /* IMP: R-31593-10574 */
1758317879
return 0;
1758417880
}
1758517881
if( nBytes>=0x7fffff00 ){
1758617882
/* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
1758717883
return 0;
1758817884
}
1758917885
nOld = sqlite3MallocSize(pOld);
17886
+ /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
17887
+ ** argument to xRealloc is always a value returned by a prior call to
17888
+ ** xRoundup. */
1759017889
nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
1759117890
if( nOld==nNew ){
1759217891
pNew = pOld;
1759317892
}else if( sqlite3GlobalConfig.bMemstat ){
1759417893
sqlite3_mutex_enter(mem0.mutex);
@@ -17610,10 +17909,11 @@
1761017909
}
1761117910
sqlite3_mutex_leave(mem0.mutex);
1761217911
}else{
1761317912
pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
1761417913
}
17914
+ assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
1761517915
return pNew;
1761617916
}
1761717917
1761817918
/*
1761917919
** The public interface to sqlite3Realloc. Make sure that the memory
@@ -19773,10 +20073,16 @@
1977320073
#define UpperToLower sqlite3UpperToLower
1977420074
1977520075
/*
1977620076
** Some systems have stricmp(). Others have strcasecmp(). Because
1977720077
** there is no consistency, we will define our own.
20078
+**
20079
+** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20080
+** applications and extensions to compare the contents of two buffers
20081
+** containing UTF-8 strings in a case-independent fashion, using the same
20082
+** definition of case independence that SQLite uses internally when
20083
+** comparing identifiers.
1977820084
*/
1977920085
SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
1978020086
register unsigned char *a, *b;
1978120087
a = (unsigned char *)zLeft;
1978220088
b = (unsigned char *)zRight;
@@ -26177,11 +26483,11 @@
2617726483
goto shmpage_out;
2617826484
}
2617926485
pShmNode->apRegion = apNew;
2618026486
while(pShmNode->nRegion<=iRegion){
2618126487
void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
26182
- MAP_SHARED, pShmNode->h, iRegion*szRegion
26488
+ MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
2618326489
);
2618426490
if( pMem==MAP_FAILED ){
2618526491
rc = SQLITE_IOERR;
2618626492
goto shmpage_out;
2618726493
}
@@ -28000,17 +28306,20 @@
2800028306
static int proxyGetHostID(unsigned char *pHostID, int *pError){
2800128307
struct timespec timeout = {1, 0}; /* 1 sec timeout */
2800228308
2800328309
assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
2800428310
memset(pHostID, 0, PROXY_HOSTIDLEN);
28311
+#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28312
+ && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
2800528313
if( gethostuuid(pHostID, &timeout) ){
2800628314
int err = errno;
2800728315
if( pError ){
2800828316
*pError = err;
2800928317
}
2801028318
return SQLITE_IOERR;
2801128319
}
28320
+#endif
2801228321
#ifdef SQLITE_TEST
2801328322
/* simulate multiple hosts by creating unique hostid file paths */
2801428323
if( sqlite3_hostid_num != 0){
2801528324
pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
2801628325
}
@@ -30339,10 +30648,18 @@
3033930648
return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
3034030649
}
3034130650
3034230651
#ifndef SQLITE_OMIT_WAL
3034330652
30653
+/*
30654
+** Windows will only let you create file view mappings
30655
+** on allocation size granularity boundaries.
30656
+** During sqlite3_os_init() we do a GetSystemInfo()
30657
+** to get the granularity size.
30658
+*/
30659
+SYSTEM_INFO winSysInfo;
30660
+
3034430661
/*
3034530662
** Helper functions to obtain and relinquish the global mutex. The
3034630663
** global mutex is used to protect the winLockInfo objects used by
3034730664
** this file, all of which may be shared by multiple threads.
3034830665
**
@@ -30507,19 +30824,26 @@
3050730824
** by VFS shared-memory methods.
3050830825
*/
3050930826
static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
3051030827
winShmNode **pp;
3051130828
winShmNode *p;
30829
+ BOOL bRc;
3051230830
assert( winShmMutexHeld() );
3051330831
pp = &winShmNodeList;
3051430832
while( (p = *pp)!=0 ){
3051530833
if( p->nRef==0 ){
3051630834
int i;
3051730835
if( p->mutex ) sqlite3_mutex_free(p->mutex);
3051830836
for(i=0; i<p->nRegion; i++){
30519
- UnmapViewOfFile(p->aRegion[i].pMap);
30520
- CloseHandle(p->aRegion[i].hMap);
30837
+ bRc = UnmapViewOfFile(p->aRegion[i].pMap);
30838
+ OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
30839
+ (int)GetCurrentProcessId(), i,
30840
+ bRc ? "ok" : "failed"));
30841
+ bRc = CloseHandle(p->aRegion[i].hMap);
30842
+ OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
30843
+ (int)GetCurrentProcessId(), i,
30844
+ bRc ? "ok" : "failed"));
3052130845
}
3052230846
if( p->hFile.h != INVALID_HANDLE_VALUE ){
3052330847
SimulateIOErrorBenign(1);
3052430848
winClose((sqlite3_file *)&p->hFile);
3052530849
SimulateIOErrorBenign(0);
@@ -30592,14 +30916,15 @@
3059230916
pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3059330917
if( pShmNode->mutex==0 ){
3059430918
rc = SQLITE_NOMEM;
3059530919
goto shm_open_err;
3059630920
}
30921
+
3059730922
rc = winOpen(pDbFd->pVfs,
3059830923
pShmNode->zFilename, /* Name of the file (UTF-8) */
3059930924
(sqlite3_file*)&pShmNode->hFile, /* File handle here */
30600
- SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30925
+ SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
3060130926
0);
3060230927
if( SQLITE_OK!=rc ){
3060330928
rc = SQLITE_CANTOPEN_BKPT;
3060430929
goto shm_open_err;
3060530930
}
@@ -30903,14 +31228,22 @@
3090331228
void *pMap = 0; /* Mapped memory region */
3090431229
3090531230
hMap = CreateFileMapping(pShmNode->hFile.h,
3090631231
NULL, PAGE_READWRITE, 0, nByte, NULL
3090731232
);
31233
+ OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
31234
+ (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
31235
+ hMap ? "ok" : "failed"));
3090831236
if( hMap ){
31237
+ int iOffset = pShmNode->nRegion*szRegion;
31238
+ int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
3090931239
pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30910
- 0, 0, nByte
31240
+ 0, iOffset - iOffsetShift, szRegion + iOffsetShift
3091131241
);
31242
+ OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
31243
+ (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
31244
+ pMap ? "ok" : "failed"));
3091231245
}
3091331246
if( !pMap ){
3091431247
pShmNode->lastErrno = GetLastError();
3091531248
rc = SQLITE_IOERR;
3091631249
if( hMap ) CloseHandle(hMap);
@@ -30923,12 +31256,14 @@
3092331256
}
3092431257
}
3092531258
3092631259
shmpage_out:
3092731260
if( pShmNode->nRegion>iRegion ){
31261
+ int iOffset = iRegion*szRegion;
31262
+ int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
3092831263
char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30929
- *pp = (void *)&p[iRegion*szRegion];
31264
+ *pp = (void *)&p[iOffsetShift];
3093031265
}else{
3093131266
*pp = 0;
3093231267
}
3093331268
sqlite3_mutex_leave(pShmNode->mutex);
3093431269
return rc;
@@ -31151,13 +31486,64 @@
3115131486
DWORD dwFlagsAndAttributes = 0;
3115231487
#if SQLITE_OS_WINCE
3115331488
int isTemp = 0;
3115431489
#endif
3115531490
winFile *pFile = (winFile*)id;
31156
- void *zConverted; /* Filename in OS encoding */
31157
- const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31158
- char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
31491
+ void *zConverted; /* Filename in OS encoding */
31492
+ const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31493
+
31494
+ /* If argument zPath is a NULL pointer, this function is required to open
31495
+ ** a temporary file. Use this buffer to store the file name in.
31496
+ */
31497
+ char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
31498
+
31499
+ int rc = SQLITE_OK; /* Function Return Code */
31500
+#if !defined(NDEBUG) || SQLITE_OS_WINCE
31501
+ int eType = flags&0xFFFFFF00; /* Type of file to open */
31502
+#endif
31503
+
31504
+ int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
31505
+ int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
31506
+ int isCreate = (flags & SQLITE_OPEN_CREATE);
31507
+#ifndef NDEBUG
31508
+ int isReadonly = (flags & SQLITE_OPEN_READONLY);
31509
+#endif
31510
+ int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
31511
+
31512
+#ifndef NDEBUG
31513
+ int isOpenJournal = (isCreate && (
31514
+ eType==SQLITE_OPEN_MASTER_JOURNAL
31515
+ || eType==SQLITE_OPEN_MAIN_JOURNAL
31516
+ || eType==SQLITE_OPEN_WAL
31517
+ ));
31518
+#endif
31519
+
31520
+ /* Check the following statements are true:
31521
+ **
31522
+ ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
31523
+ ** (b) if CREATE is set, then READWRITE must also be set, and
31524
+ ** (c) if EXCLUSIVE is set, then CREATE must also be set.
31525
+ ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
31526
+ */
31527
+ assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31528
+ assert(isCreate==0 || isReadWrite);
31529
+ assert(isExclusive==0 || isCreate);
31530
+ assert(isDelete==0 || isCreate);
31531
+
31532
+ /* The main DB, main journal, WAL file and master journal are never
31533
+ ** automatically deleted. Nor are they ever temporary files. */
31534
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31535
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31536
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31537
+ assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31538
+
31539
+ /* Assert that the upper layer has set one of the "file-type" flags. */
31540
+ assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
31541
+ || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
31542
+ || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
31543
+ || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31544
+ );
3115931545
3116031546
assert( id!=0 );
3116131547
UNUSED_PARAMETER(pVfs);
3116231548
3116331549
pFile->h = INVALID_HANDLE_VALUE;
@@ -31164,11 +31550,12 @@
3116431550
3116531551
/* If the second argument to this function is NULL, generate a
3116631552
** temporary file name to use
3116731553
*/
3116831554
if( !zUtf8Name ){
31169
- int rc = getTempname(MAX_PATH+1, zTmpname);
31555
+ assert(isDelete && !isOpenJournal);
31556
+ rc = getTempname(MAX_PATH+1, zTmpname);
3117031557
if( rc!=SQLITE_OK ){
3117131558
return rc;
3117231559
}
3117331560
zUtf8Name = zTmpname;
3117431561
}
@@ -31177,33 +31564,35 @@
3117731564
zConverted = convertUtf8Filename(zUtf8Name);
3117831565
if( zConverted==0 ){
3117931566
return SQLITE_NOMEM;
3118031567
}
3118131568
31182
- if( flags & SQLITE_OPEN_READWRITE ){
31569
+ if( isReadWrite ){
3118331570
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
3118431571
}else{
3118531572
dwDesiredAccess = GENERIC_READ;
3118631573
}
31574
+
3118731575
/* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
3118831576
** created. SQLite doesn't use it to indicate "exclusive access"
3118931577
** as it is usually understood.
3119031578
*/
31191
- assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
31192
- if( flags & SQLITE_OPEN_EXCLUSIVE ){
31579
+ if( isExclusive ){
3119331580
/* Creates a new file, only if it does not already exist. */
3119431581
/* If the file exists, it fails. */
3119531582
dwCreationDisposition = CREATE_NEW;
31196
- }else if( flags & SQLITE_OPEN_CREATE ){
31583
+ }else if( isCreate ){
3119731584
/* Open existing file, or create if it doesn't exist */
3119831585
dwCreationDisposition = OPEN_ALWAYS;
3119931586
}else{
3120031587
/* Opens a file, only if it exists. */
3120131588
dwCreationDisposition = OPEN_EXISTING;
3120231589
}
31590
+
3120331591
dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31204
- if( flags & SQLITE_OPEN_DELETEONCLOSE ){
31592
+
31593
+ if( isDelete ){
3120531594
#if SQLITE_OS_WINCE
3120631595
dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
3120731596
isTemp = 1;
3120831597
#else
3120931598
dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
@@ -31216,10 +31605,11 @@
3121631605
/* Reports from the internet are that performance is always
3121731606
** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
3121831607
#if SQLITE_OS_WINCE
3121931608
dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
3122031609
#endif
31610
+
3122131611
if( isNT() ){
3122231612
h = CreateFileW((WCHAR*)zConverted,
3122331613
dwDesiredAccess,
3122431614
dwShareMode,
3122531615
NULL,
@@ -31241,41 +31631,45 @@
3124131631
dwFlagsAndAttributes,
3124231632
NULL
3124331633
);
3124431634
#endif
3124531635
}
31636
+
3124631637
OSTRACE(("OPEN %d %s 0x%lx %s\n",
3124731638
h, zName, dwDesiredAccess,
3124831639
h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31640
+
3124931641
if( h==INVALID_HANDLE_VALUE ){
3125031642
pFile->lastErrno = GetLastError();
3125131643
free(zConverted);
31252
- if( flags & SQLITE_OPEN_READWRITE ){
31644
+ if( isReadWrite ){
3125331645
return winOpen(pVfs, zName, id,
31254
- ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
31646
+ ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
3125531647
}else{
3125631648
return SQLITE_CANTOPEN_BKPT;
3125731649
}
3125831650
}
31651
+
3125931652
if( pOutFlags ){
31260
- if( flags & SQLITE_OPEN_READWRITE ){
31653
+ if( isReadWrite ){
3126131654
*pOutFlags = SQLITE_OPEN_READWRITE;
3126231655
}else{
3126331656
*pOutFlags = SQLITE_OPEN_READONLY;
3126431657
}
3126531658
}
31659
+
3126631660
memset(pFile, 0, sizeof(*pFile));
3126731661
pFile->pMethod = &winIoMethod;
3126831662
pFile->h = h;
3126931663
pFile->lastErrno = NO_ERROR;
3127031664
pFile->pVfs = pVfs;
3127131665
pFile->pShm = 0;
3127231666
pFile->zPath = zName;
3127331667
pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31668
+
3127431669
#if SQLITE_OS_WINCE
31275
- if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31276
- (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
31670
+ if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
3127731671
&& !winceCreateLock(zName, pFile)
3127831672
){
3127931673
CloseHandle(h);
3128031674
free(zConverted);
3128131675
return SQLITE_CANTOPEN_BKPT;
@@ -31285,12 +31679,13 @@
3128531679
}else
3128631680
#endif
3128731681
{
3128831682
free(zConverted);
3128931683
}
31684
+
3129031685
OpenCounter(+1);
31291
- return SQLITE_OK;
31686
+ return rc;
3129231687
}
3129331688
3129431689
/*
3129531690
** Delete the named file.
3129631691
**
@@ -31804,10 +32199,17 @@
3180432199
winSleep, /* xSleep */
3180532200
winCurrentTime, /* xCurrentTime */
3180632201
winGetLastError, /* xGetLastError */
3180732202
winCurrentTimeInt64, /* xCurrentTimeInt64 */
3180832203
};
32204
+
32205
+#ifndef SQLITE_OMIT_WAL
32206
+ /* get memory map allocation granularity */
32207
+ memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
32208
+ GetSystemInfo(&winSysInfo);
32209
+ assert(winSysInfo.dwAllocationGranularity > 0);
32210
+#endif
3180932211
3181032212
sqlite3_vfs_register(&winVfs, 1);
3181132213
return SQLITE_OK;
3181232214
}
3181332215
SQLITE_API int sqlite3_os_end(void){
@@ -32369,16 +32771,20 @@
3236932771
** Initialize and shutdown the page cache subsystem. Neither of these
3237032772
** functions are threadsafe.
3237132773
*/
3237232774
SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
3237332775
if( sqlite3GlobalConfig.pcache.xInit==0 ){
32776
+ /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
32777
+ ** built-in default page cache is used instead of the application defined
32778
+ ** page cache. */
3237432779
sqlite3PCacheSetDefault();
3237532780
}
3237632781
return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
3237732782
}
3237832783
SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
3237932784
if( sqlite3GlobalConfig.pcache.xShutdown ){
32785
+ /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
3238032786
sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
3238132787
}
3238232788
}
3238332789
3238432790
/*
@@ -32835,12 +33241,17 @@
3283533241
3283633242
typedef struct PCache1 PCache1;
3283733243
typedef struct PgHdr1 PgHdr1;
3283833244
typedef struct PgFreeslot PgFreeslot;
3283933245
32840
-/* Pointers to structures of this type are cast and returned as
32841
-** opaque sqlite3_pcache* handles
33246
+/* Each page cache is an instance of the following object. Every
33247
+** open database file (including each in-memory database and each
33248
+** temporary or transient database) has a single page cache which
33249
+** is an instance of this object.
33250
+**
33251
+** Pointers to structures of this type are cast and returned as
33252
+** opaque sqlite3_pcache* handles.
3284233253
*/
3284333254
struct PCache1 {
3284433255
/* Cache configuration parameters. Page size (szPage) and the purgeable
3284533256
** flag (bPurgeable) are set when the cache is created. nMax may be
3284633257
** modified at any time by a call to the pcache1CacheSize() method.
@@ -32896,10 +33307,13 @@
3289633307
int nCurrentPage; /* Number of purgeable pages allocated */
3289733308
PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
3289833309
3289933310
/* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
3290033311
int szSlot; /* Size of each free slot */
33312
+ int nSlot; /* The number of pcache slots */
33313
+ int nFreeSlot; /* Number of unused pcache slots */
33314
+ int nReserve; /* Try to keep nFreeSlot above this */
3290133315
void *pStart, *pEnd; /* Bounds of pagecache malloc range */
3290233316
PgFreeslot *pFree; /* Free page blocks */
3290333317
int isInit; /* True if initialized */
3290433318
} pcache1_g;
3290533319
@@ -32943,10 +33357,12 @@
3294333357
SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
3294433358
if( pcache1.isInit ){
3294533359
PgFreeslot *p;
3294633360
sz = ROUNDDOWN8(sz);
3294733361
pcache1.szSlot = sz;
33362
+ pcache1.nSlot = pcache1.nFreeSlot = n;
33363
+ pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
3294833364
pcache1.pStart = pBuf;
3294933365
pcache1.pFree = 0;
3295033366
while( n-- ){
3295133367
p = (PgFreeslot*)pBuf;
3295233368
p->pNext = pcache1.pFree;
@@ -32969,10 +33385,12 @@
3296933385
sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
3297033386
if( nByte<=pcache1.szSlot && pcache1.pFree ){
3297133387
assert( pcache1.isInit );
3297233388
p = (PgHdr1 *)pcache1.pFree;
3297333389
pcache1.pFree = pcache1.pFree->pNext;
33390
+ pcache1.nFreeSlot--;
33391
+ assert( pcache1.nFreeSlot>=0 );
3297433392
sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
3297533393
}else{
3297633394
3297733395
/* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
3297833396
** global pcache mutex and unlock the pager-cache object pCache. This is
@@ -33002,10 +33420,12 @@
3300233420
PgFreeslot *pSlot;
3300333421
sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
3300433422
pSlot = (PgFreeslot*)p;
3300533423
pSlot->pNext = pcache1.pFree;
3300633424
pcache1.pFree = pSlot;
33425
+ pcache1.nFreeSlot++;
33426
+ assert( pcache1.nFreeSlot<=pcache1.nSlot );
3300733427
}else{
3300833428
int iSize;
3300933429
assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
3301033430
sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
3301133431
iSize = sqlite3MallocSize(p);
@@ -33014,11 +33434,11 @@
3301433434
}
3301533435
}
3301633436
3301733437
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
3301833438
/*
33019
-** Return the size of a pache allocation
33439
+** Return the size of a pcache allocation
3302033440
*/
3302133441
static int pcache1MemSize(void *p){
3302233442
assert( sqlite3_mutex_held(pcache1.mutex) );
3302333443
if( p>=pcache1.pStart && p<pcache1.pEnd ){
3302433444
return pcache1.szSlot;
@@ -33087,10 +33507,36 @@
3308733507
pcache1EnterMutex();
3308833508
pcache1Free(p);
3308933509
pcache1LeaveMutex();
3309033510
}
3309133511
33512
+
33513
+/*
33514
+** Return true if it desirable to avoid allocating a new page cache
33515
+** entry.
33516
+**
33517
+** If memory was allocated specifically to the page cache using
33518
+** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
33519
+** it is desirable to avoid allocating a new page cache entry because
33520
+** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
33521
+** for all page cache needs and we should not need to spill the
33522
+** allocation onto the heap.
33523
+**
33524
+** Or, the heap is used for all page cache memory put the heap is
33525
+** under memory pressure, then again it is desirable to avoid
33526
+** allocating a new page cache entry in order to avoid stressing
33527
+** the heap even further.
33528
+*/
33529
+static int pcache1UnderMemoryPressure(PCache1 *pCache){
33530
+ assert( sqlite3_mutex_held(pcache1.mutex) );
33531
+ if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
33532
+ return pcache1.nFreeSlot<pcache1.nReserve;
33533
+ }else{
33534
+ return sqlite3HeapNearlyFull();
33535
+ }
33536
+}
33537
+
3309233538
/******************************************************************************/
3309333539
/******** General Implementation Functions ************************************/
3309433540
3309533541
/*
3309633542
** This function is used to resize the hash table used by the cache passed
@@ -33328,18 +33774,20 @@
3332833774
** copy of the requested page. If one is found, it is returned.
3332933775
**
3333033776
** 2. If createFlag==0 and the page is not already in the cache, NULL is
3333133777
** returned.
3333233778
**
33333
-** 3. If createFlag is 1, and the page is not already in the cache,
33334
-** and if either of the following are true, return NULL:
33779
+** 3. If createFlag is 1, and the page is not already in the cache, then
33780
+** return NULL (do not allocate a new page) if any of the following
33781
+** conditions are true:
3333533782
**
3333633783
** (a) the number of pages pinned by the cache is greater than
3333733784
** PCache1.nMax, or
33785
+**
3333833786
** (b) the number of pages pinned by the cache is greater than
3333933787
** the sum of nMax for all purgeable caches, less the sum of
33340
-** nMin for all other purgeable caches.
33788
+** nMin for all other purgeable caches, or
3334133789
**
3334233790
** 4. If none of the first three conditions apply and the cache is marked
3334333791
** as purgeable, and if one of the following is true:
3334433792
**
3334533793
** (a) The number of pages allocated for the cache is already
@@ -33346,10 +33794,13 @@
3334633794
** PCache1.nMax, or
3334733795
**
3334833796
** (b) The number of pages allocated for all purgeable caches is
3334933797
** already equal to or greater than the sum of nMax for all
3335033798
** purgeable caches,
33799
+**
33800
+** (c) The system is under memory pressure and wants to avoid
33801
+** unnecessary pages cache entry allocations
3335133802
**
3335233803
** then attempt to recycle a page from the LRU list. If it is the right
3335333804
** size, return the recycled buffer. Otherwise, free the buffer and
3335433805
** proceed to step 5.
3335533806
**
@@ -33378,10 +33829,11 @@
3337833829
/* Step 3 of header comment. */
3337933830
nPinned = pCache->nPage - pCache->nRecyclable;
3338033831
if( createFlag==1 && (
3338133832
nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
3338233833
|| nPinned>=(pCache->nMax * 9 / 10)
33834
+ || pcache1UnderMemoryPressure(pCache)
3338333835
)){
3338433836
goto fetch_out;
3338533837
}
3338633838
3338733839
if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
@@ -33388,11 +33840,13 @@
3338833840
goto fetch_out;
3338933841
}
3339033842
3339133843
/* Step 4. Try to recycle a page buffer if appropriate. */
3339233844
if( pCache->bPurgeable && pcache1.pLruTail && (
33393
- (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
33845
+ (pCache->nPage+1>=pCache->nMax)
33846
+ || pcache1.nCurrentPage>=pcache1.nMaxPage
33847
+ || pcache1UnderMemoryPressure(pCache)
3339433848
)){
3339533849
pPage = pcache1.pLruTail;
3339633850
pcache1RemoveFromHash(pPage);
3339733851
pcache1PinPage(pPage);
3339833852
if( pPage->pCache->szPage!=pCache->szPage ){
@@ -33531,10 +33985,11 @@
3353133985
**
3353233986
** Destroy a cache allocated using pcache1Create().
3353333987
*/
3353433988
static void pcache1Destroy(sqlite3_pcache *p){
3353533989
PCache1 *pCache = (PCache1 *)p;
33990
+ assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
3353633991
pcache1EnterMutex();
3353733992
pcache1TruncateUnsafe(pCache, 0);
3353833993
pcache1.nMaxPage -= pCache->nMax;
3353933994
pcache1.nMinPage -= pCache->nMin;
3354033995
pcache1EnforceMaxPage();
@@ -33578,11 +34033,11 @@
3357834033
SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
3357934034
int nFree = 0;
3358034035
if( pcache1.pStart==0 ){
3358134036
PgHdr1 *p;
3358234037
pcache1EnterMutex();
33583
- while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
34038
+ while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
3358434039
nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
3358534040
pcache1PinPage(p);
3358634041
pcache1RemoveFromHash(p);
3358734042
pcache1FreePage(p);
3358834043
}
@@ -37120,16 +37575,17 @@
3712037575
** the duplicate call is harmless.
3712137576
*/
3712237577
sqlite3WalEndReadTransaction(pPager->pWal);
3712337578
3712437579
rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37125
- if( rc==SQLITE_OK && changed ){
37580
+ if( rc!=SQLITE_OK || changed ){
3712637581
pager_reset(pPager);
3712737582
}
3712837583
3712937584
return rc;
3713037585
}
37586
+#endif
3713137587
3713237588
/*
3713337589
** This function is called as part of the transition from PAGER_OPEN
3713437590
** to PAGER_READER state to determine the size of the database file
3713537591
** in pages (assuming the page size currently stored in Pager.pageSize).
@@ -37182,11 +37638,11 @@
3718237638
3718337639
*pnPage = nPage;
3718437640
return SQLITE_OK;
3718537641
}
3718637642
37187
-
37643
+#ifndef SQLITE_OMIT_WAL
3718837644
/*
3718937645
** Check if the *-wal file that corresponds to the database opened by pPager
3719037646
** exists if the database is not empy, or verify that the *-wal file does
3719137647
** not exist (by deleting it) if the database file is empty.
3719237648
**
@@ -38374,10 +38830,17 @@
3837438830
journalFileSize = ROUND8(sqlite3MemJournalSize());
3837538831
}
3837638832
3837738833
/* Set the output variable to NULL in case an error occurs. */
3837838834
*ppPager = 0;
38835
+
38836
+#ifndef SQLITE_OMIT_MEMORYDB
38837
+ if( flags & PAGER_MEMORY ){
38838
+ memDb = 1;
38839
+ zFilename = 0;
38840
+ }
38841
+#endif
3837938842
3838038843
/* Compute and store the full pathname in an allocated buffer pointed
3838138844
** to by zPathname, length nPathname. Or, if this is a temporary file,
3838238845
** leave both nPathname and zPathname set to 0.
3838338846
*/
@@ -38385,21 +38848,12 @@
3838538848
nPathname = pVfs->mxPathname+1;
3838638849
zPathname = sqlite3Malloc(nPathname*2);
3838738850
if( zPathname==0 ){
3838838851
return SQLITE_NOMEM;
3838938852
}
38390
-#ifndef SQLITE_OMIT_MEMORYDB
38391
- if( strcmp(zFilename,":memory:")==0 ){
38392
- memDb = 1;
38393
- zPathname[0] = 0;
38394
- }else
38395
-#endif
38396
- {
38397
- zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38398
- rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
38399
- }
38400
-
38853
+ zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38854
+ rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
3840138855
nPathname = sqlite3Strlen30(zPathname);
3840238856
if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
3840338857
/* This branch is taken when the journal path required by
3840438858
** the database being opened will be more than pVfs->mxPathname
3840538859
** bytes in length. This means the database cannot be opened,
@@ -38450,34 +38904,31 @@
3845038904
pPager->zFilename = (char*)(pPtr += journalFileSize);
3845138905
assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
3845238906
3845338907
/* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
3845438908
if( zPathname ){
38909
+ assert( nPathname>0 );
3845538910
pPager->zJournal = (char*)(pPtr += nPathname + 1);
3845638911
memcpy(pPager->zFilename, zPathname, nPathname);
3845738912
memcpy(pPager->zJournal, zPathname, nPathname);
3845838913
memcpy(&pPager->zJournal[nPathname], "-journal", 8);
38459
- if( pPager->zFilename[0]==0 ){
38460
- pPager->zJournal[0] = 0;
38461
- }
3846238914
#ifndef SQLITE_OMIT_WAL
38463
- else{
38464
- pPager->zWal = &pPager->zJournal[nPathname+8+1];
38465
- memcpy(pPager->zWal, zPathname, nPathname);
38466
- memcpy(&pPager->zWal[nPathname], "-wal", 4);
38467
- }
38915
+ pPager->zWal = &pPager->zJournal[nPathname+8+1];
38916
+ memcpy(pPager->zWal, zPathname, nPathname);
38917
+ memcpy(&pPager->zWal[nPathname], "-wal", 4);
3846838918
#endif
3846938919
sqlite3_free(zPathname);
3847038920
}
3847138921
pPager->pVfs = pVfs;
3847238922
pPager->vfsFlags = vfsFlags;
3847338923
3847438924
/* Open the pager file.
3847538925
*/
38476
- if( zFilename && zFilename[0] && !memDb ){
38926
+ if( zFilename && zFilename[0] ){
3847738927
int fout = 0; /* VFS flags returned by xOpen() */
3847838928
rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
38929
+ assert( !memDb );
3847938930
readOnly = (fout&SQLITE_OPEN_READONLY);
3848038931
3848138932
/* If the file was successfully opened for read/write access,
3848238933
** choose a default page size in case we have to create the
3848338934
** database file. The default page size is the maximum of:
@@ -38927,11 +39378,13 @@
3892739378
3892839379
/* If there is a WAL file in the file-system, open this database in WAL
3892939380
** mode. Otherwise, the following function call is a no-op.
3893039381
*/
3893139382
rc = pagerOpenWalIfPresent(pPager);
39383
+#ifndef SQLITE_OMIT_WAL
3893239384
assert( pPager->pWal==0 || rc==SQLITE_OK );
39385
+#endif
3893339386
}
3893439387
3893539388
if( pagerUseWal(pPager) ){
3893639389
assert( rc==SQLITE_OK );
3893739390
rc = pagerBeginReadTransaction(pPager);
@@ -43292,11 +43745,11 @@
4329243745
WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
4329343746
if( rc!=SQLITE_OK ){
4329443747
return rc;
4329543748
}
4329643749
}
43297
- assert( pWal->szPage==szPage );
43750
+ assert( (int)pWal->szPage==szPage );
4329843751
4329943752
/* Write the log file. */
4330043753
for(p=pList; p; p=p->pDirty){
4330143754
u32 nDbsize; /* Db-size field for frame header */
4330243755
i64 iOffset; /* Write offset in log file */
@@ -43952,10 +44405,11 @@
4395244405
MemPage *pPage1; /* First page of the database */
4395344406
u8 readOnly; /* True if the underlying file is readonly */
4395444407
u8 pageSizeFixed; /* True if the page size can no longer be changed */
4395544408
u8 secureDelete; /* True if secure_delete is enabled */
4395644409
u8 initiallyEmpty; /* Database is empty at start of transaction */
44410
+ u8 openFlags; /* Flags to sqlite3BtreeOpen() */
4395744411
#ifndef SQLITE_OMIT_AUTOVACUUM
4395844412
u8 autoVacuum; /* True if auto-vacuum is enabled */
4395944413
u8 incrVacuum; /* True if incr-vacuum is enabled */
4396044414
#endif
4396144415
u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
@@ -46202,15 +46656,24 @@
4620246656
4620346657
/*
4620446658
** Open a database file.
4620546659
**
4620646660
** zFilename is the name of the database file. If zFilename is NULL
46207
-** a new database with a random name is created. This randomly named
46208
-** database file will be deleted when sqlite3BtreeClose() is called.
46661
+** then an ephemeral database is created. The ephemeral database might
46662
+** be exclusively in memory, or it might use a disk-based memory cache.
46663
+** Either way, the ephemeral database will be automatically deleted
46664
+** when sqlite3BtreeClose() is called.
46665
+**
4620946666
** If zFilename is ":memory:" then an in-memory database is created
4621046667
** that is automatically destroyed when it is closed.
4621146668
**
46669
+** The "flags" parameter is a bitmask that might contain bits
46670
+** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
46671
+** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
46672
+** These flags are passed through into sqlite3PagerOpen() and must
46673
+** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
46674
+**
4621246675
** If the database is already opened in the same database connection
4621346676
** and we are in shared cache mode, then the open will fail with an
4621446677
** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
4621546678
** objects in the same database connection since doing so will lead
4621646679
** to problems with locking.
@@ -46227,10 +46690,13 @@
4622746690
Btree *p; /* Handle to return */
4622846691
sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
4622946692
int rc = SQLITE_OK; /* Result code from this function */
4623046693
u8 nReserve; /* Byte of unused space on each page */
4623146694
unsigned char zDbHeader[100]; /* Database header content */
46695
+
46696
+ /* True if opening an ephemeral, temporary database */
46697
+ const int isTempDb = zFilename==0 || zFilename[0]==0;
4623246698
4623346699
/* Set the variable isMemdb to true for an in-memory database, or
4623446700
** false for a file-based database. This symbol is only required if
4623546701
** either of the shared-data or autovacuum features are compiled
4623646702
** into the library.
@@ -46237,17 +46703,34 @@
4623746703
*/
4623846704
#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
4623946705
#ifdef SQLITE_OMIT_MEMORYDB
4624046706
const int isMemdb = 0;
4624146707
#else
46242
- const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
46708
+ const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
46709
+ || (isTempDb && sqlite3TempInMemory(db));
4624346710
#endif
4624446711
#endif
4624546712
4624646713
assert( db!=0 );
4624746714
assert( sqlite3_mutex_held(db->mutex) );
46715
+ assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
4624846716
46717
+ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
46718
+ assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
46719
+
46720
+ /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
46721
+ assert( (flags & BTREE_SINGLE)==0 || isTempDb );
46722
+
46723
+ if( db->flags & SQLITE_NoReadlock ){
46724
+ flags |= BTREE_NO_READLOCK;
46725
+ }
46726
+ if( isMemdb ){
46727
+ flags |= BTREE_MEMORY;
46728
+ }
46729
+ if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
46730
+ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
46731
+ }
4624946732
pVfs = db->pVfs;
4625046733
p = sqlite3MallocZero(sizeof(Btree));
4625146734
if( !p ){
4625246735
return SQLITE_NOMEM;
4625346736
}
@@ -46261,11 +46744,11 @@
4626146744
#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
4626246745
/*
4626346746
** If this Btree is a candidate for shared cache, try to find an
4626446747
** existing BtShared object that we can share with
4626546748
*/
46266
- if( isMemdb==0 && zFilename && zFilename[0] ){
46749
+ if( isMemdb==0 && isTempDb==0 ){
4626746750
if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
4626846751
int nFullPathname = pVfs->mxPathname+1;
4626946752
char *zFullPathname = sqlite3Malloc(nFullPathname);
4627046753
sqlite3_mutex *mutexShared;
4627146754
p->sharable = 1;
@@ -46336,10 +46819,11 @@
4633646819
rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
4633746820
}
4633846821
if( rc!=SQLITE_OK ){
4633946822
goto btree_open_out;
4634046823
}
46824
+ pBt->openFlags = (u8)flags;
4634146825
pBt->db = db;
4634246826
sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
4634346827
p->pBt = pBt;
4634446828
4634546829
pBt->pCursor = 0;
@@ -46440,10 +46924,18 @@
4644046924
sqlite3PagerClose(pBt->pPager);
4644146925
}
4644246926
sqlite3_free(pBt);
4644346927
sqlite3_free(p);
4644446928
*ppBtree = 0;
46929
+ }else{
46930
+ /* If the B-Tree was successfully opened, set the pager-cache size to the
46931
+ ** default value. Except, when opening on an existing shared pager-cache,
46932
+ ** do not change the pager-cache size.
46933
+ */
46934
+ if( sqlite3BtreeSchema(p, 0, 0)==0 ){
46935
+ sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
46936
+ }
4644546937
}
4644646938
if( mutexOpen ){
4644746939
assert( sqlite3_mutex_held(mutexOpen) );
4644846940
sqlite3_mutex_leave(mutexOpen);
4644946941
}
@@ -51390,15 +51882,16 @@
5139051882
** flags might not work:
5139151883
**
5139251884
** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5139351885
** BTREE_ZERODATA Used for SQL indices
5139451886
*/
51395
-static int btreeCreateTable(Btree *p, int *piTable, int flags){
51887
+static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
5139651888
BtShared *pBt = p->pBt;
5139751889
MemPage *pRoot;
5139851890
Pgno pgnoRoot;
5139951891
int rc;
51892
+ int ptfFlags; /* Page-type flage for the root page of new table */
5140051893
5140151894
assert( sqlite3BtreeHoldsMutex(p) );
5140251895
assert( pBt->inTransaction==TRANS_WRITE );
5140351896
assert( !pBt->readOnly );
5140451897
@@ -51513,12 +52006,18 @@
5151352006
rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
5151452007
if( rc ) return rc;
5151552008
}
5151652009
#endif
5151752010
assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51518
- zeroPage(pRoot, flags | PTF_LEAF);
52011
+ if( createTabFlags & BTREE_INTKEY ){
52012
+ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
52013
+ }else{
52014
+ ptfFlags = PTF_ZERODATA | PTF_LEAF;
52015
+ }
52016
+ zeroPage(pRoot, ptfFlags);
5151952017
sqlite3PagerUnref(pRoot->pDbPage);
52018
+ assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
5152052019
*piTable = (int)pgnoRoot;
5152152020
return SQLITE_OK;
5152252021
}
5152352022
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5152452023
int rc;
@@ -52774,11 +53273,14 @@
5277453273
sqlite3Error(
5277553274
pDestDb, SQLITE_ERROR, "source and destination must be distinct"
5277653275
);
5277753276
p = 0;
5277853277
}else {
52779
- /* Allocate space for a new sqlite3_backup object */
53278
+ /* Allocate space for a new sqlite3_backup object...
53279
+ ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53280
+ ** call to sqlite3_backup_init() and is destroyed by a call to
53281
+ ** sqlite3_backup_finish(). */
5278053282
p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
5278153283
if( !p ){
5278253284
sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
5278353285
}
5278453286
}
@@ -53157,10 +53659,13 @@
5315753659
if( p->pDestDb ){
5315853660
sqlite3_mutex_leave(p->pDestDb->mutex);
5315953661
}
5316053662
sqlite3BtreeLeave(p->pSrc);
5316153663
if( p->pDestDb ){
53664
+ /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53665
+ ** call to sqlite3_backup_init() and is destroyed by a call to
53666
+ ** sqlite3_backup_finish(). */
5316253667
sqlite3_free(p);
5316353668
}
5316453669
sqlite3_mutex_leave(mutex);
5316553670
return rc;
5316653671
}
@@ -53408,10 +53913,13 @@
5340853913
return SQLITE_NOMEM;
5340953914
}
5341053915
pMem->z[pMem->n] = 0;
5341153916
pMem->z[pMem->n+1] = 0;
5341253917
pMem->flags |= MEM_Term;
53918
+#ifdef SQLITE_DEBUG
53919
+ pMem->pScopyFrom = 0;
53920
+#endif
5341353921
}
5341453922
5341553923
return SQLITE_OK;
5341653924
}
5341753925
@@ -53528,11 +54036,11 @@
5352854036
memset(&ctx, 0, sizeof(ctx));
5352954037
ctx.s.flags = MEM_Null;
5353054038
ctx.s.db = pMem->db;
5353154039
ctx.pMem = pMem;
5353254040
ctx.pFunc = pFunc;
53533
- pFunc->xFinalize(&ctx);
54041
+ pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
5353454042
assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
5353554043
sqlite3DbFree(pMem->db, pMem->zMalloc);
5353654044
memcpy(pMem, &ctx.s, sizeof(ctx.s));
5353754045
rc = ctx.isError;
5353854046
}
@@ -53869,10 +54377,32 @@
5386954377
return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
5387054378
}
5387154379
return 0;
5387254380
}
5387354381
54382
+#ifdef SQLITE_DEBUG
54383
+/*
54384
+** This routine prepares a memory cell for modication by breaking
54385
+** its link to a shallow copy and by marking any current shallow
54386
+** copies of this cell as invalid.
54387
+**
54388
+** This is used for testing and debugging only - to make sure shallow
54389
+** copies are not misused.
54390
+*/
54391
+SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
54392
+ int i;
54393
+ Mem *pX;
54394
+ for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
54395
+ if( pX->pScopyFrom==pMem ){
54396
+ pX->flags |= MEM_Invalid;
54397
+ pX->pScopyFrom = 0;
54398
+ }
54399
+ }
54400
+ pMem->pScopyFrom = 0;
54401
+}
54402
+#endif /* SQLITE_DEBUG */
54403
+
5387454404
/*
5387554405
** Size of struct Mem not including the Mem.zMalloc member.
5387654406
*/
5387754407
#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
5387854408
@@ -54237,11 +54767,11 @@
5423754767
assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
5423854768
if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
5423954769
return 0;
5424054770
}
5424154771
}
54242
- sqlite3VdbeMemNulTerminate(pVal);
54772
+ sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
5424354773
}else{
5424454774
assert( (pVal->flags&MEM_Blob)==0 );
5424554775
sqlite3VdbeMemStringify(pVal, enc);
5424654776
assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
5424754777
}
@@ -56152,13 +56682,14 @@
5615256682
*/
5615356683
for(i=0; i<db->nDb; i++){
5615456684
Btree *pBt = db->aDb[i].pBt;
5615556685
if( sqlite3BtreeIsInTrans(pBt) ){
5615656686
char const *zFile = sqlite3BtreeGetJournalname(pBt);
56157
- if( zFile==0 || zFile[0]==0 ){
56687
+ if( zFile==0 ){
5615856688
continue; /* Ignore TEMP and :memory: databases */
5615956689
}
56690
+ assert( zFile[0]!=0 );
5616056691
if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
5616156692
needSync = 1;
5616256693
}
5616356694
rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
5616456695
offset += sqlite3Strlen30(zFile)+1;
@@ -57618,10 +58149,12 @@
5761858149
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
5761958150
*/
5762058151
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
5762158152
int rc;
5762258153
if( pStmt==0 ){
58154
+ /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
58155
+ ** pointer is a harmless no-op. */
5762358156
rc = SQLITE_OK;
5762458157
}else{
5762558158
Vdbe *v = (Vdbe*)pStmt;
5762658159
sqlite3 *db = v->db;
5762758160
#if SQLITE_THREADSAFE
@@ -57694,11 +58227,11 @@
5769458227
Mem *p = (Mem*)pVal;
5769558228
if( p->flags & (MEM_Blob|MEM_Str) ){
5769658229
sqlite3VdbeMemExpandBlob(p);
5769758230
p->flags &= ~MEM_Str;
5769858231
p->flags |= MEM_Blob;
57699
- return p->z;
58232
+ return p->n ? p->z : 0;
5770058233
}else{
5770158234
return sqlite3_value_text(pVal);
5770258235
}
5770358236
}
5770458237
SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
@@ -58048,10 +58581,16 @@
5804858581
}
5804958582
5805058583
/*
5805158584
** Extract the user data from a sqlite3_context structure and return a
5805258585
** pointer to it.
58586
+**
58587
+** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
58588
+** returns a copy of the pointer to the database connection (the 1st
58589
+** parameter) of the sqlite3_create_function() and
58590
+** sqlite3_create_function16() routines that originally registered the
58591
+** application defined function.
5805358592
*/
5805458593
SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
5805558594
assert( p && p->pFunc );
5805658595
return p->s.db;
5805758596
}
@@ -58257,12 +58796,11 @@
5825758796
** sqlite3_column_text()
5825858797
** sqlite3_column_text16()
5825958798
** sqlite3_column_real()
5826058799
** sqlite3_column_bytes()
5826158800
** sqlite3_column_bytes16()
58262
-**
58263
-** But not for sqlite3_column_blob(), which never calls malloc().
58801
+** sqiite3_column_blob()
5826458802
*/
5826558803
static void columnMallocFailure(sqlite3_stmt *pStmt)
5826658804
{
5826758805
/* If malloc() failed during an encoding conversion within an
5826858806
** sqlite3_column_XXX API, then set the return code of the statement to
@@ -58526,10 +59064,16 @@
5852659064
pVar->flags = MEM_Null;
5852759065
sqlite3Error(p->db, SQLITE_OK, 0);
5852859066
5852959067
/* If the bit corresponding to this variable in Vdbe.expmask is set, then
5853059068
** binding a new value to this variable invalidates the current query plan.
59069
+ **
59070
+ ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
59071
+ ** parameter in the WHERE clause might influence the choice of query plan
59072
+ ** for a statement, then the statement will be automatically recompiled,
59073
+ ** as if there had been a schema change, on the first sqlite3_step() call
59074
+ ** following any change to the bindings of that parameter.
5853159075
*/
5853259076
if( p->isPrepareV2 &&
5853359077
((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
5853459078
){
5853559079
p->expired = 1;
@@ -59023,10 +59567,21 @@
5902359567
** of the code in this file is, therefore, important. See other comments
5902459568
** in this file for details. If in doubt, do not deviate from existing
5902559569
** commenting and indentation practices when changing or adding code.
5902659570
*/
5902759571
59572
+/*
59573
+** Invoke this macro on memory cells just prior to changing the
59574
+** value of the cell. This macro verifies that shallow copies are
59575
+** not misused.
59576
+*/
59577
+#ifdef SQLITE_DEBUG
59578
+# define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
59579
+#else
59580
+# define memAboutToChange(P,M)
59581
+#endif
59582
+
5902859583
/*
5902959584
** The following global variable is incremented every time a cursor
5903059585
** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
5903159586
** procedures use this information to make sure that indices are
5903259587
** working correctly. This variable has no function other than to
@@ -60132,38 +60687,44 @@
6013260687
assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
6013360688
if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
6013460689
assert( pOp->p2>0 );
6013560690
assert( pOp->p2<=p->nMem );
6013660691
pOut = &aMem[pOp->p2];
60692
+ memAboutToChange(p, pOut);
6013760693
sqlite3VdbeMemReleaseExternal(pOut);
6013860694
pOut->flags = MEM_Int;
6013960695
}
6014060696
6014160697
/* Sanity checking on other operands */
6014260698
#ifdef SQLITE_DEBUG
6014360699
if( (pOp->opflags & OPFLG_IN1)!=0 ){
6014460700
assert( pOp->p1>0 );
6014560701
assert( pOp->p1<=p->nMem );
60702
+ assert( memIsValid(&aMem[pOp->p1]) );
6014660703
REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
6014760704
}
6014860705
if( (pOp->opflags & OPFLG_IN2)!=0 ){
6014960706
assert( pOp->p2>0 );
6015060707
assert( pOp->p2<=p->nMem );
60708
+ assert( memIsValid(&aMem[pOp->p2]) );
6015160709
REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
6015260710
}
6015360711
if( (pOp->opflags & OPFLG_IN3)!=0 ){
6015460712
assert( pOp->p3>0 );
6015560713
assert( pOp->p3<=p->nMem );
60714
+ assert( memIsValid(&aMem[pOp->p3]) );
6015660715
REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
6015760716
}
6015860717
if( (pOp->opflags & OPFLG_OUT2)!=0 ){
6015960718
assert( pOp->p2>0 );
6016060719
assert( pOp->p2<=p->nMem );
60720
+ memAboutToChange(p, &aMem[pOp->p2]);
6016160721
}
6016260722
if( (pOp->opflags & OPFLG_OUT3)!=0 ){
6016360723
assert( pOp->p3>0 );
6016460724
assert( pOp->p3<=p->nMem );
60725
+ memAboutToChange(p, &aMem[pOp->p3]);
6016560726
}
6016660727
#endif
6016760728
6016860729
switch( pOp->opcode ){
6016960730
@@ -60221,10 +60782,11 @@
6022160782
** and then jump to address P2.
6022260783
*/
6022360784
case OP_Gosub: { /* jump, in1 */
6022460785
pIn1 = &aMem[pOp->p1];
6022560786
assert( (pIn1->flags & MEM_Dyn)==0 );
60787
+ memAboutToChange(p, pIn1);
6022660788
pIn1->flags = MEM_Int;
6022760789
pIn1->u.i = pc;
6022860790
REGISTER_TRACE(pOp->p1, pIn1);
6022960791
pc = pOp->p2 - 1;
6023060792
break;
@@ -60428,15 +60990,11 @@
6042860990
6042960991
6043060992
/* Opcode: Blob P1 P2 * P4
6043160993
**
6043260994
** P4 points to a blob of data P1 bytes long. Store this
60433
-** blob in register P2. This instruction is not coded directly
60434
-** by the compiler. Instead, the compiler layer specifies
60435
-** an OP_HexBlob opcode, with the hex string representation of
60436
-** the blob as P4. This opcode is transformed to an OP_Blob
60437
-** the first time it is executed.
60995
+** blob in register P2.
6043860996
*/
6043960997
case OP_Blob: { /* out2-prerelease */
6044060998
assert( pOp->p1 <= SQLITE_MAX_LENGTH );
6044160999
sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
6044261000
pOut->enc = encoding;
@@ -60490,10 +61048,12 @@
6049061048
pIn1 = &aMem[u.ac.p1];
6049161049
pOut = &aMem[u.ac.p2];
6049261050
while( u.ac.n-- ){
6049361051
assert( pOut<=&aMem[p->nMem] );
6049461052
assert( pIn1<=&aMem[p->nMem] );
61053
+ assert( memIsValid(pIn1) );
61054
+ memAboutToChange(p, pOut);
6049561055
u.ac.zMalloc = pOut->zMalloc;
6049661056
pOut->zMalloc = 0;
6049761057
sqlite3VdbeMemMove(pOut, pIn1);
6049861058
pIn1->zMalloc = u.ac.zMalloc;
6049961059
REGISTER_TRACE(u.ac.p2++, pOut);
@@ -60535,10 +61095,13 @@
6053561095
case OP_SCopy: { /* in1, out2 */
6053661096
pIn1 = &aMem[pOp->p1];
6053761097
pOut = &aMem[pOp->p2];
6053861098
assert( pOut!=pIn1 );
6053961099
sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61100
+#ifdef SQLITE_DEBUG
61101
+ if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
61102
+#endif
6054061103
REGISTER_TRACE(pOp->p2, pOut);
6054161104
break;
6054261105
}
6054361106
6054461107
/* Opcode: ResultRow P1 P2 * * *
@@ -60595,10 +61158,14 @@
6059561158
** and have an assigned type. The results are de-ephemeralized as
6059661159
** as side effect.
6059761160
*/
6059861161
u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
6059961162
for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
61163
+ assert( memIsValid(&u.ad.pMem[u.ad.i]) );
61164
+ Deephemeralize(&u.ad.pMem[u.ad.i]);
61165
+ assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
61166
+ || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
6060061167
sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
6060161168
sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
6060261169
REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
6060361170
}
6060461171
if( db->mallocFailed ) goto no_mem;
@@ -60826,16 +61393,21 @@
6082661393
#endif /* local variables moved into u.ag */
6082761394
6082861395
u.ag.n = pOp->p5;
6082961396
u.ag.apVal = p->apArg;
6083061397
assert( u.ag.apVal || u.ag.n==0 );
61398
+ assert( pOp->p3>0 && pOp->p3<=p->nMem );
61399
+ pOut = &aMem[pOp->p3];
61400
+ memAboutToChange(p, pOut);
6083161401
6083261402
assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
6083361403
assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
6083461404
u.ag.pArg = &aMem[pOp->p2];
6083561405
for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
61406
+ assert( memIsValid(u.ag.pArg) );
6083661407
u.ag.apVal[u.ag.i] = u.ag.pArg;
61408
+ Deephemeralize(u.ag.pArg);
6083761409
sqlite3VdbeMemStoreType(u.ag.pArg);
6083861410
REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
6083961411
}
6084061412
6084161413
assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
@@ -60845,12 +61417,10 @@
6084561417
}else{
6084661418
u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
6084761419
u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
6084861420
}
6084961421
60850
- assert( pOp->p3>0 && pOp->p3<=p->nMem );
60851
- pOut = &aMem[pOp->p3];
6085261422
u.ag.ctx.s.flags = MEM_Null;
6085361423
u.ag.ctx.s.db = db;
6085461424
u.ag.ctx.s.xDel = 0;
6085561425
u.ag.ctx.s.zMalloc = 0;
6085661426
@@ -60866,11 +61436,11 @@
6086661436
assert( pOp>aOp );
6086761437
assert( pOp[-1].p4type==P4_COLLSEQ );
6086861438
assert( pOp[-1].opcode==OP_CollSeq );
6086961439
u.ag.ctx.pColl = pOp[-1].p4.pColl;
6087061440
}
60871
- (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
61441
+ (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
6087261442
if( db->mallocFailed ){
6087361443
/* Even though a malloc() has failed, the implementation of the
6087461444
** user function may have called an sqlite3_result_XXX() function
6087561445
** to return a value. The following call releases any resources
6087661446
** associated with such a value.
@@ -60918,11 +61488,11 @@
6091861488
** If either input is NULL, the result is NULL.
6091961489
*/
6092061490
/* Opcode: ShiftLeft P1 P2 P3 * *
6092161491
**
6092261492
** Shift the integer value in register P2 to the left by the
60923
-** number of bits specified by the integer in regiser P1.
61493
+** number of bits specified by the integer in register P1.
6092461494
** Store the result in register P3.
6092561495
** If either input is NULL, the result is NULL.
6092661496
*/
6092761497
/* Opcode: ShiftRight P1 P2 P3 * *
6092861498
**
@@ -60968,10 +61538,11 @@
6096861538
**
6096961539
** To force any register to be an integer, just add 0.
6097061540
*/
6097161541
case OP_AddImm: { /* in1 */
6097261542
pIn1 = &aMem[pOp->p1];
61543
+ memAboutToChange(p, pIn1);
6097361544
sqlite3VdbeMemIntegerify(pIn1);
6097461545
pIn1->u.i += pOp->p2;
6097561546
break;
6097661547
}
6097761548
@@ -60982,10 +61553,11 @@
6098261553
** without data loss, then jump immediately to P2, or if P2==0
6098361554
** raise an SQLITE_MISMATCH exception.
6098461555
*/
6098561556
case OP_MustBeInt: { /* jump, in1 */
6098661557
pIn1 = &aMem[pOp->p1];
61558
+ memAboutToChange(p, pIn1);
6098761559
applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
6098861560
if( (pIn1->flags & MEM_Int)==0 ){
6098961561
if( pOp->p2==0 ){
6099061562
rc = SQLITE_MISMATCH;
6099161563
goto abort_due_to_error;
@@ -61008,10 +61580,11 @@
6100861580
** integers, for space efficiency, but after extraction we want them
6100961581
** to have only a real value.
6101061582
*/
6101161583
case OP_RealAffinity: { /* in1 */
6101261584
pIn1 = &aMem[pOp->p1];
61585
+ memAboutToChange(p, pIn1);
6101361586
if( pIn1->flags & MEM_Int ){
6101461587
sqlite3VdbeMemRealify(pIn1);
6101561588
}
6101661589
break;
6101761590
}
@@ -61027,10 +61600,11 @@
6102761600
**
6102861601
** A NULL value is not changed by this routine. It remains NULL.
6102961602
*/
6103061603
case OP_ToText: { /* same as TK_TO_TEXT, in1 */
6103161604
pIn1 = &aMem[pOp->p1];
61605
+ memAboutToChange(p, pIn1);
6103261606
if( pIn1->flags & MEM_Null ) break;
6103361607
assert( MEM_Str==(MEM_Blob>>3) );
6103461608
pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
6103561609
applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
6103661610
rc = ExpandBlob(pIn1);
@@ -61049,10 +61623,11 @@
6104961623
**
6105061624
** A NULL value is not changed by this routine. It remains NULL.
6105161625
*/
6105261626
case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
6105361627
pIn1 = &aMem[pOp->p1];
61628
+ memAboutToChange(p, pIn1);
6105461629
if( pIn1->flags & MEM_Null ) break;
6105561630
if( (pIn1->flags & MEM_Blob)==0 ){
6105661631
applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
6105761632
assert( pIn1->flags & MEM_Str || db->mallocFailed );
6105861633
MemSetTypeFlag(pIn1, MEM_Blob);
@@ -61073,28 +61648,30 @@
6107361648
**
6107461649
** A NULL value is not changed by this routine. It remains NULL.
6107561650
*/
6107661651
case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
6107761652
pIn1 = &aMem[pOp->p1];
61653
+ memAboutToChange(p, pIn1);
6107861654
if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
6107961655
sqlite3VdbeMemNumerify(pIn1);
6108061656
}
6108161657
break;
6108261658
}
6108361659
#endif /* SQLITE_OMIT_CAST */
6108461660
6108561661
/* Opcode: ToInt P1 * * * *
6108661662
**
61087
-** Force the value in register P1 be an integer. If
61663
+** Force the value in register P1 to be an integer. If
6108861664
** The value is currently a real number, drop its fractional part.
6108961665
** If the value is text or blob, try to convert it to an integer using the
6109061666
** equivalent of atoi() and store 0 if no such conversion is possible.
6109161667
**
6109261668
** A NULL value is not changed by this routine. It remains NULL.
6109361669
*/
6109461670
case OP_ToInt: { /* same as TK_TO_INT, in1 */
6109561671
pIn1 = &aMem[pOp->p1];
61672
+ memAboutToChange(p, pIn1);
6109661673
if( (pIn1->flags & MEM_Null)==0 ){
6109761674
sqlite3VdbeMemIntegerify(pIn1);
6109861675
}
6109961676
break;
6110061677
}
@@ -61109,10 +61686,11 @@
6110961686
**
6111061687
** A NULL value is not changed by this routine. It remains NULL.
6111161688
*/
6111261689
case OP_ToReal: { /* same as TK_TO_REAL, in1 */
6111361690
pIn1 = &aMem[pOp->p1];
61691
+ memAboutToChange(p, pIn1);
6111461692
if( (pIn1->flags & MEM_Null)==0 ){
6111561693
sqlite3VdbeMemRealify(pIn1);
6111661694
}
6111761695
break;
6111861696
}
@@ -61123,11 +61701,11 @@
6112361701
** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
6112461702
** jump to address P2.
6112561703
**
6112661704
** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
6112761705
** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
61128
-** bit is clear then fall thru if either operand is NULL.
61706
+** bit is clear then fall through if either operand is NULL.
6112961707
**
6113061708
** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
6113161709
** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
6113261710
** to coerce both inputs according to this affinity before the
6113361711
** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
@@ -61203,10 +61781,12 @@
6120361781
u16 flags3; /* Copy of initial value of pIn3->flags */
6120461782
#endif /* local variables moved into u.ai */
6120561783
6120661784
pIn1 = &aMem[pOp->p1];
6120761785
pIn3 = &aMem[pOp->p3];
61786
+ memAboutToChange(p, pIn1);
61787
+ memAboutToChange(p, pIn3);
6120861788
u.ai.flags1 = pIn1->flags;
6120961789
u.ai.flags3 = pIn3->flags;
6121061790
if( (pIn1->flags | pIn3->flags)&MEM_Null ){
6121161791
/* One or both operands are NULL */
6121261792
if( pOp->p5 & SQLITE_NULLEQ ){
@@ -61253,10 +61833,11 @@
6125361833
default: u.ai.res = u.ai.res>=0; break;
6125461834
}
6125561835
6125661836
if( pOp->p5 & SQLITE_STOREP2 ){
6125761837
pOut = &aMem[pOp->p2];
61838
+ memAboutToChange(p, pOut);
6125861839
MemSetTypeFlag(pOut, MEM_Int);
6125961840
pOut->u.i = u.ai.res;
6126061841
REGISTER_TRACE(pOp->p2, pOut);
6126161842
}else if( u.ai.res ){
6126261843
pc = pOp->p2-1;
@@ -61284,12 +61865,12 @@
6128461865
break;
6128561866
}
6128661867
6128761868
/* Opcode: Compare P1 P2 P3 P4 *
6128861869
**
61289
-** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
61290
-** one "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
61870
+** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
61871
+** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
6129161872
** the comparison for use by the next OP_Jump instruct.
6129261873
**
6129361874
** P4 is a KeyInfo structure that defines collating sequences and sort
6129461875
** orders for the comparison. The permutation applies to registers
6129561876
** only. The KeyInfo elements are used sequentially.
@@ -61327,10 +61908,12 @@
6132761908
assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
6132861909
}
6132961910
#endif /* SQLITE_DEBUG */
6133061911
for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
6133161912
u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
61913
+ assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
61914
+ assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
6133261915
REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
6133361916
REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
6133461917
assert( u.aj.i<u.aj.pKeyInfo->nField );
6133561918
u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
6133661919
u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
@@ -61558,10 +62141,11 @@
6155862141
u.am.pC = 0;
6155962142
memset(&u.am.sMem, 0, sizeof(u.am.sMem));
6156062143
assert( u.am.p1<p->nCursor );
6156162144
assert( pOp->p3>0 && pOp->p3<=p->nMem );
6156262145
u.am.pDest = &aMem[pOp->p3];
62146
+ memAboutToChange(p, u.am.pDest);
6156362147
MemSetTypeFlag(u.am.pDest, MEM_Null);
6156462148
u.am.zRec = 0;
6156562149
6156662150
/* This block sets the variable u.am.payloadSize to be the total number of
6156762151
** bytes in the record.
@@ -61605,10 +62189,11 @@
6160562189
assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
6160662190
}
6160762191
}else if( u.am.pC->pseudoTableReg>0 ){
6160862192
u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
6160962193
assert( u.am.pReg->flags & MEM_Blob );
62194
+ assert( memIsValid(u.am.pReg) );
6161062195
u.am.payloadSize = u.am.pReg->n;
6161162196
u.am.zRec = u.am.pReg->z;
6161262197
u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
6161362198
assert( u.am.payloadSize==0 || u.am.zRec!=0 );
6161462199
}else{
@@ -61829,25 +62414,24 @@
6182962414
assert( u.an.zAffinity!=0 );
6183062415
assert( u.an.zAffinity[pOp->p2]==0 );
6183162416
pIn1 = &aMem[pOp->p1];
6183262417
while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
6183362418
assert( pIn1 <= &p->aMem[p->nMem] );
62419
+ assert( memIsValid(pIn1) );
62420
+ memAboutToChange(p, pIn1);
6183462421
ExpandBlob(pIn1);
6183562422
applyAffinity(pIn1, u.an.cAff, encoding);
6183662423
pIn1++;
6183762424
}
6183862425
break;
6183962426
}
6184062427
6184162428
/* Opcode: MakeRecord P1 P2 P3 P4 *
6184262429
**
61843
-** Convert P2 registers beginning with P1 into a single entry
61844
-** suitable for use as a data record in a database table or as a key
61845
-** in an index. The details of the format are irrelevant as long as
61846
-** the OP_Column opcode can decode the record later.
61847
-** Refer to source code comments for the details of the record
61848
-** format.
62430
+** Convert P2 registers beginning with P1 into the [record format]
62431
+** use as a data record in a database table or as a key
62432
+** in an index. The OP_Column opcode can decode the record later.
6184962433
**
6185062434
** P4 may be a string that is P2 characters long. The nth character of the
6185162435
** string indicates the column affinity that should be used for the nth
6185262436
** field of the index key.
6185362437
**
@@ -61899,16 +62483,23 @@
6189962483
assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
6190062484
u.ao.pData0 = &aMem[u.ao.nField];
6190162485
u.ao.nField = pOp->p2;
6190262486
u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
6190362487
u.ao.file_format = p->minWriteFileFormat;
62488
+
62489
+ /* Identify the output register */
62490
+ assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
62491
+ pOut = &aMem[pOp->p3];
62492
+ memAboutToChange(p, pOut);
6190462493
6190562494
/* Loop through the elements that will make up the record to figure
6190662495
** out how much space is required for the new record.
6190762496
*/
6190862497
for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62498
+ assert( memIsValid(u.ao.pRec) );
6190962499
if( u.ao.zAffinity ){
62500
+ memAboutToChange(p, u.ao.pRec);
6191062501
applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
6191162502
}
6191262503
if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
6191362504
sqlite3VdbeMemExpandBlob(u.ao.pRec);
6191462505
}
@@ -61938,12 +62529,10 @@
6193862529
/* Make sure the output register has a buffer large enough to store
6193962530
** the new record. The output register (pOp->p3) is not allowed to
6194062531
** be one of the input registers (because the following call to
6194162532
** sqlite3VdbeMemGrow() could clobber the value before it is used).
6194262533
*/
61943
- assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
61944
- pOut = &aMem[pOp->p3];
6194562534
if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
6194662535
goto no_mem;
6194762536
}
6194862537
u.ao.zNewRecord = (u8 *)pOut->z;
6194962538
@@ -62112,10 +62701,11 @@
6211262701
}
6211362702
}
6211462703
if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
6211562704
sqlite3ExpirePreparedStatements(db);
6211662705
sqlite3ResetInternalSchema(db, 0);
62706
+ db->flags = (db->flags | SQLITE_InternChanges);
6211762707
}
6211862708
}
6211962709
6212062710
/* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
6212162711
** savepoints nested inside of the savepoint being operated on. */
@@ -62502,10 +63092,12 @@
6250263092
}
6250363093
if( pOp->p5 ){
6250463094
assert( u.aw.p2>0 );
6250563095
assert( u.aw.p2<=p->nMem );
6250663096
pIn2 = &aMem[u.aw.p2];
63097
+ assert( memIsValid(pIn2) );
63098
+ assert( (pIn2->flags & MEM_Int)!=0 );
6250763099
sqlite3VdbeMemIntegerify(pIn2);
6250863100
u.aw.p2 = (int)pIn2->u.i;
6250963101
/* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
6251063102
** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
6251163103
** If there were a failure, the prepared statement would have halted
@@ -62524,10 +63116,11 @@
6252463116
}
6252563117
assert( pOp->p1>=0 );
6252663118
u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
6252763119
if( u.aw.pCur==0 ) goto no_mem;
6252863120
u.aw.pCur->nullRow = 1;
63121
+ u.aw.pCur->isOrdered = 1;
6252963122
rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
6253063123
u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
6253163124
6253263125
/* Since it performs no memory allocation or IO, the only values that
6253363126
** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
@@ -62576,11 +63169,11 @@
6257663169
case OP_OpenAutoindex:
6257763170
case OP_OpenEphemeral: {
6257863171
#if 0 /* local variables moved into u.ax */
6257963172
VdbeCursor *pCx;
6258063173
#endif /* local variables moved into u.ax */
62581
- static const int openFlags =
63174
+ static const int vfsFlags =
6258263175
SQLITE_OPEN_READWRITE |
6258363176
SQLITE_OPEN_CREATE |
6258463177
SQLITE_OPEN_EXCLUSIVE |
6258563178
SQLITE_OPEN_DELETEONCLOSE |
6258663179
SQLITE_OPEN_TRANSIENT_DB;
@@ -62587,25 +63180,25 @@
6258763180
6258863181
assert( pOp->p1>=0 );
6258963182
u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
6259063183
if( u.ax.pCx==0 ) goto no_mem;
6259163184
u.ax.pCx->nullRow = 1;
62592
- rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
62593
- &u.ax.pCx->pBt);
63185
+ rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
63186
+ BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
6259463187
if( rc==SQLITE_OK ){
6259563188
rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
6259663189
}
6259763190
if( rc==SQLITE_OK ){
6259863191
/* If a transient index is required, create it by calling
62599
- ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
63192
+ ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
6260063193
** opening it. If a transient table is required, just use the
62601
- ** automatically created table with root-page 1 (an INTKEY table).
63194
+ ** automatically created table with root-page 1 (an BLOB_INTKEY table).
6260263195
*/
6260363196
if( pOp->p4.pKeyInfo ){
6260463197
int pgno;
6260563198
assert( pOp->p4type==P4_KEYINFO );
62606
- rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
63199
+ rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
6260763200
if( rc==SQLITE_OK ){
6260863201
assert( pgno==MASTER_ROOT+1 );
6260963202
rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
6261063203
(KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
6261163204
u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
@@ -62615,10 +63208,11 @@
6261563208
}else{
6261663209
rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
6261763210
u.ax.pCx->isTable = 1;
6261863211
}
6261963212
}
63213
+ u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
6262063214
u.ax.pCx->isIndex = !u.ax.pCx->isTable;
6262163215
break;
6262263216
}
6262363217
6262463218
/* Opcode: OpenPseudo P1 P2 P3 * *
@@ -62734,10 +63328,11 @@
6273463328
assert( u.az.pC!=0 );
6273563329
assert( u.az.pC->pseudoTableReg==0 );
6273663330
assert( OP_SeekLe == OP_SeekLt+1 );
6273763331
assert( OP_SeekGe == OP_SeekLt+2 );
6273863332
assert( OP_SeekGt == OP_SeekLt+3 );
63333
+ assert( u.az.pC->isOrdered );
6273963334
if( u.az.pC->pCursor!=0 ){
6274063335
u.az.oc = pOp->opcode;
6274163336
u.az.pC->nullRow = 0;
6274263337
if( u.az.pC->isTable ){
6274363338
/* The input value in P3 might be of any type: integer, real, string,
@@ -62816,10 +63411,13 @@
6281663411
assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
6281763412
assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
6281863413
assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
6281963414
6282063415
u.az.r.aMem = &aMem[pOp->p3];
63416
+#ifdef SQLITE_DEBUG
63417
+ { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
63418
+#endif
6282163419
ExpandBlob(u.az.r.aMem);
6282263420
rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
6282363421
if( rc!=SQLITE_OK ){
6282463422
goto abort_due_to_error;
6282563423
}
@@ -62944,15 +63542,18 @@
6294463542
assert( u.bb.pC->isTable==0 );
6294563543
if( pOp->p4.i>0 ){
6294663544
u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
6294763545
u.bb.r.nField = (u16)pOp->p4.i;
6294863546
u.bb.r.aMem = pIn3;
63547
+#ifdef SQLITE_DEBUG
63548
+ { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
63549
+#endif
6294963550
u.bb.r.flags = UNPACKED_PREFIX_MATCH;
6295063551
u.bb.pIdxKey = &u.bb.r;
6295163552
}else{
6295263553
assert( pIn3->flags & MEM_Blob );
62953
- ExpandBlob(pIn3);
63554
+ assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
6295463555
u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
6295563556
u.bb.aTempRec, sizeof(u.bb.aTempRec));
6295663557
if( u.bb.pIdxKey==0 ){
6295763558
goto no_mem;
6295863559
}
@@ -63043,10 +63644,13 @@
6304363644
/* Populate the index search key. */
6304463645
u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
6304563646
u.bc.r.nField = u.bc.nField + 1;
6304663647
u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
6304763648
u.bc.r.aMem = u.bc.aMx;
63649
+#ifdef SQLITE_DEBUG
63650
+ { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
63651
+#endif
6304863652
6304963653
/* Extract the value of u.bc.R from register P3. */
6305063654
sqlite3VdbeMemIntegerify(pIn3);
6305163655
u.bc.R = pIn3->u.i;
6305263656
@@ -63065,11 +63669,11 @@
6306563669
6306663670
/* Opcode: NotExists P1 P2 P3 * *
6306763671
**
6306863672
** Use the content of register P3 as a integer key. If a record
6306963673
** with that key does not exist in table of P1, then jump to P2.
63070
-** If the record does exist, then fall thru. The cursor is left
63674
+** If the record does exist, then fall through. The cursor is left
6307163675
** pointing to the record if it exists.
6307263676
**
6307363677
** The difference between this operation and NotFound is that this
6307463678
** operation assumes the key is an integer and that P1 is a table whereas
6307563679
** NotFound assumes key is a blob constructed from MakeRecord and
@@ -63223,11 +63827,13 @@
6322363827
u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
6322463828
}else{
6322563829
/* Assert that P3 is a valid memory cell. */
6322663830
assert( pOp->p3<=p->nMem );
6322763831
u.be.pMem = &aMem[pOp->p3];
63832
+ memAboutToChange(p, u.be.pMem);
6322863833
}
63834
+ assert( memIsValid(u.be.pMem) );
6322963835
6323063836
REGISTER_TRACE(pOp->p3, u.be.pMem);
6323163837
sqlite3VdbeMemIntegerify(u.be.pMem);
6323263838
assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
6323363839
if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
@@ -63242,33 +63848,40 @@
6324263848
#endif
6324363849
6324463850
sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
6324563851
}
6324663852
if( u.be.pC->useRandomRowid ){
63247
- /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
63853
+ /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
6324863854
** largest possible integer (9223372036854775807) then the database
63249
- ** engine starts picking candidate ROWIDs at random until it finds one
63250
- ** that is not previously used.
63251
- */
63855
+ ** engine starts picking positive candidate ROWIDs at random until
63856
+ ** it finds one that is not previously used. */
6325263857
assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
6325363858
** an AUTOINCREMENT table. */
63859
+ /* on the first attempt, simply do one more than previous */
6325463860
u.be.v = db->lastRowid;
63861
+ u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
63862
+ u.be.v++; /* ensure non-zero */
6325563863
u.be.cnt = 0;
63256
- do{
63257
- if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
63258
- u.be.v++;
63864
+ while( ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
63865
+ 0, &u.be.res))==SQLITE_OK)
63866
+ && (u.be.res==0)
63867
+ && (++u.be.cnt<100)){
63868
+ /* collision - try another random rowid */
63869
+ sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63870
+ if( u.be.cnt<5 ){
63871
+ /* try "small" random rowids for the initial attempts */
63872
+ u.be.v &= 0xffffff;
6325963873
}else{
63260
- sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63261
- if( u.be.cnt<5 ) u.be.v &= 0xffffff;
63874
+ u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
6326263875
}
63263
- rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
63264
- u.be.cnt++;
63265
- }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
63876
+ u.be.v++; /* ensure non-zero */
63877
+ }
6326663878
if( rc==SQLITE_OK && u.be.res==0 ){
6326763879
rc = SQLITE_FULL; /* IMP: R-38219-53002 */
6326863880
goto abort_due_to_error;
6326963881
}
63882
+ assert( u.be.v>0 ); /* EV: R-40812-03570 */
6327063883
}
6327163884
u.be.pC->rowidIsValid = 0;
6327263885
u.be.pC->deferredMoveto = 0;
6327363886
u.be.pC->cacheStatus = CACHE_STALE;
6327463887
}
@@ -63334,10 +63947,11 @@
6333463947
int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
6333563948
#endif /* local variables moved into u.bf */
6333663949
6333763950
u.bf.pData = &aMem[pOp->p2];
6333863951
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63952
+ assert( memIsValid(u.bf.pData) );
6333963953
u.bf.pC = p->apCsr[pOp->p1];
6334063954
assert( u.bf.pC!=0 );
6334163955
assert( u.bf.pC->pCursor!=0 );
6334263956
assert( u.bf.pC->pseudoTableReg==0 );
6334363957
assert( u.bf.pC->isTable );
@@ -63344,10 +63958,11 @@
6334463958
REGISTER_TRACE(pOp->p2, u.bf.pData);
6334563959
6334663960
if( pOp->opcode==OP_Insert ){
6334763961
u.bf.pKey = &aMem[pOp->p3];
6334863962
assert( u.bf.pKey->flags & MEM_Int );
63963
+ assert( memIsValid(u.bf.pKey) );
6334963964
REGISTER_TRACE(pOp->p3, u.bf.pKey);
6335063965
u.bf.iKey = u.bf.pKey->u.i;
6335163966
}else{
6335263967
assert( pOp->opcode==OP_InsertInt );
6335363968
u.bf.iKey = pOp->p3;
@@ -63495,10 +64110,11 @@
6349564110
u32 n;
6349664111
i64 n64;
6349764112
#endif /* local variables moved into u.bh */
6349864113
6349964114
pOut = &aMem[pOp->p2];
64115
+ memAboutToChange(p, pOut);
6350064116
6350164117
/* Note that RowKey and RowData are really exactly the same instruction */
6350264118
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6350364119
u.bh.pC = p->apCsr[pOp->p1];
6350464120
assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
@@ -63837,10 +64453,13 @@
6383764453
if( ALWAYS(u.bo.pCrsr!=0) ){
6383864454
u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
6383964455
u.bo.r.nField = (u16)pOp->p3;
6384064456
u.bo.r.flags = 0;
6384164457
u.bo.r.aMem = &aMem[pOp->p2];
64458
+#ifdef SQLITE_DEBUG
64459
+ { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
64460
+#endif
6384264461
rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
6384364462
if( rc==SQLITE_OK && u.bo.res==0 ){
6384464463
rc = sqlite3BtreeDelete(u.bo.pCrsr);
6384564464
}
6384664465
assert( u.bo.pC->deferredMoveto==0 );
@@ -63921,10 +64540,11 @@
6392164540
#endif /* local variables moved into u.bq */
6392264541
6392364542
assert( pOp->p1>=0 && pOp->p1<p->nCursor );
6392464543
u.bq.pC = p->apCsr[pOp->p1];
6392564544
assert( u.bq.pC!=0 );
64545
+ assert( u.bq.pC->isOrdered );
6392664546
if( ALWAYS(u.bq.pC->pCursor!=0) ){
6392764547
assert( u.bq.pC->deferredMoveto==0 );
6392864548
assert( pOp->p5==0 || pOp->p5==1 );
6392964549
assert( pOp->p4type==P4_INT32 );
6393064550
u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
@@ -63933,10 +64553,13 @@
6393364553
u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
6393464554
}else{
6393564555
u.bq.r.flags = UNPACKED_IGNORE_ROWID;
6393664556
}
6393764557
u.bq.r.aMem = &aMem[pOp->p3];
64558
+#ifdef SQLITE_DEBUG
64559
+ { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
64560
+#endif
6393864561
rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
6393964562
if( pOp->opcode==OP_IdxLT ){
6394064563
u.bq.res = -u.bq.res;
6394164564
}else{
6394264565
assert( pOp->opcode==OP_IdxGE );
@@ -64036,10 +64659,12 @@
6403664659
db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
6403764660
);
6403864661
if( pOp->p3 ){
6403964662
p->nChange += u.bs.nChange;
6404064663
if( pOp->p3>0 ){
64664
+ assert( memIsValid(&aMem[pOp->p3]) );
64665
+ memAboutToChange(p, &aMem[pOp->p3]);
6404164666
aMem[pOp->p3].u.i += u.bs.nChange;
6404264667
}
6404364668
}
6404464669
break;
6404564670
}
@@ -64079,13 +64704,13 @@
6407964704
assert( (p->btreeMask & (1<<pOp->p1))!=0 );
6408064705
u.bt.pDb = &db->aDb[pOp->p1];
6408164706
assert( u.bt.pDb->pBt!=0 );
6408264707
if( pOp->opcode==OP_CreateTable ){
6408364708
/* u.bt.flags = BTREE_INTKEY; */
64084
- u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
64709
+ u.bt.flags = BTREE_INTKEY;
6408564710
}else{
64086
- u.bt.flags = BTREE_ZERODATA;
64711
+ u.bt.flags = BTREE_BLOBKEY;
6408764712
}
6408864713
rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
6408964714
pOut->u.i = u.bt.pgno;
6409064715
break;
6409164716
}
@@ -64410,10 +65035,11 @@
6441065035
void *t; /* Token identifying trigger */
6441165036
#endif /* local variables moved into u.by */
6441265037
6441365038
u.by.pProgram = pOp->p4.pProgram;
6441465039
u.by.pRt = &aMem[pOp->p3];
65040
+ assert( memIsValid(u.by.pRt) );
6441565041
assert( u.by.pProgram->nOp>0 );
6441665042
6441765043
/* If the p5 flag is clear, then recursive invocation of triggers is
6441865044
** disabled for backwards compatibility (p5 is set if this sub-program
6441965045
** is really a trigger, not a foreign key action, and the flag set
@@ -64583,10 +65209,11 @@
6458365209
for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
6458465210
u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
6458565211
}else{
6458665212
u.ca.pIn1 = &aMem[pOp->p1];
6458765213
}
65214
+ assert( memIsValid(u.ca.pIn1) );
6458865215
sqlite3VdbeMemIntegerify(u.ca.pIn1);
6458965216
pIn2 = &aMem[pOp->p2];
6459065217
sqlite3VdbeMemIntegerify(pIn2);
6459165218
if( u.ca.pIn1->u.i<pIn2->u.i){
6459265219
u.ca.pIn1->u.i = pIn2->u.i;
@@ -64669,11 +65296,13 @@
6466965296
assert( u.cb.n>=0 );
6467065297
u.cb.pRec = &aMem[pOp->p2];
6467165298
u.cb.apVal = p->apArg;
6467265299
assert( u.cb.apVal || u.cb.n==0 );
6467365300
for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
65301
+ assert( memIsValid(u.cb.pRec) );
6467465302
u.cb.apVal[u.cb.i] = u.cb.pRec;
65303
+ memAboutToChange(p, u.cb.pRec);
6467565304
sqlite3VdbeMemStoreType(u.cb.pRec);
6467665305
}
6467765306
u.cb.ctx.pFunc = pOp->p4.pFunc;
6467865307
assert( pOp->p3>0 && pOp->p3<=p->nMem );
6467965308
u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
@@ -64689,11 +65318,11 @@
6468965318
assert( pOp>p->aOp );
6469065319
assert( pOp[-1].p4type==P4_COLLSEQ );
6469165320
assert( pOp[-1].opcode==OP_CollSeq );
6469265321
u.cb.ctx.pColl = pOp[-1].p4.pColl;
6469365322
}
64694
- (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
65323
+ (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
6469565324
if( u.cb.ctx.isError ){
6469665325
sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
6469765326
rc = u.cb.ctx.isError;
6469865327
}
6469965328
sqlite3VdbeMemRelease(&u.cb.ctx.s);
@@ -65076,10 +65705,11 @@
6507665705
#endif /* local variables moved into u.ch */
6507765706
6507865707
u.ch.pQuery = &aMem[pOp->p3];
6507965708
u.ch.pArgc = &u.ch.pQuery[1];
6508065709
u.ch.pCur = p->apCsr[pOp->p1];
65710
+ assert( memIsValid(u.ch.pQuery) );
6508165711
REGISTER_TRACE(pOp->p3, u.ch.pQuery);
6508265712
assert( u.ch.pCur->pVtabCursor );
6508365713
u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
6508465714
u.ch.pVtab = u.ch.pVtabCursor->pVtab;
6508565715
u.ch.pModule = u.ch.pVtab->pModule;
@@ -65133,10 +65763,11 @@
6513365763
6513465764
VdbeCursor *pCur = p->apCsr[pOp->p1];
6513565765
assert( pCur->pVtabCursor );
6513665766
assert( pOp->p3>0 && pOp->p3<=p->nMem );
6513765767
u.ci.pDest = &aMem[pOp->p3];
65768
+ memAboutToChange(p, u.ci.pDest);
6513865769
if( pCur->nullRow ){
6513965770
sqlite3VdbeMemSetNull(u.ci.pDest);
6514065771
break;
6514165772
}
6514265773
u.ci.pVtab = pCur->pVtabCursor->pVtab;
@@ -65235,14 +65866,16 @@
6523565866
#endif /* local variables moved into u.ck */
6523665867
6523765868
u.ck.pVtab = pOp->p4.pVtab->pVtab;
6523865869
u.ck.pName = &aMem[pOp->p1];
6523965870
assert( u.ck.pVtab->pModule->xRename );
65871
+ assert( memIsValid(u.ck.pName) );
6524065872
REGISTER_TRACE(pOp->p1, u.ck.pName);
6524165873
assert( u.ck.pName->flags & MEM_Str );
6524265874
rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
6524365875
importVtabErrMsg(p, u.ck.pVtab);
65876
+ p->expired = 0;
6524465877
6524565878
break;
6524665879
}
6524765880
#endif
6524865881
@@ -65287,10 +65920,12 @@
6528765920
assert( pOp->p4type==P4_VTAB );
6528865921
if( ALWAYS(u.cl.pModule->xUpdate) ){
6528965922
u.cl.apArg = p->apArg;
6529065923
u.cl.pX = &aMem[pOp->p3];
6529165924
for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
65925
+ assert( memIsValid(u.cl.pX) );
65926
+ memAboutToChange(p, u.cl.pX);
6529265927
sqlite3VdbeMemStoreType(u.cl.pX);
6529365928
u.cl.apArg[u.cl.i] = u.cl.pX;
6529465929
u.cl.pX++;
6529565930
}
6529665931
rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
@@ -66341,12 +66976,11 @@
6634166976
SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
6634266977
return pJfd->pMethods==&MemJournalMethods;
6634366978
}
6634466979
6634566980
/*
66346
-** Return the number of bytes required to store a MemJournal that uses vfs
66347
-** pVfs to create the underlying on-disk files.
66981
+** Return the number of bytes required to store a MemJournal file descriptor.
6634866982
*/
6634966983
SQLITE_PRIVATE int sqlite3MemJournalSize(void){
6635066984
return sizeof(MemJournal);
6635166985
}
6635266986
@@ -69226,12 +69860,12 @@
6922669860
return eType;
6922769861
}
6922869862
#endif
6922969863
6923069864
/*
69231
-** Generate code for scalar subqueries used as an expression
69232
-** and IN operators. Examples:
69865
+** Generate code for scalar subqueries used as a subquery expression, EXISTS,
69866
+** or IN operators. Examples:
6923369867
**
6923469868
** (SELECT a FROM b) -- subquery
6923569869
** EXISTS (SELECT a FROM b) -- EXISTS subquery
6923669870
** x IN (4,5,11) -- IN operator with list on right-hand side
6923769871
** x IN (SELECT a FROM b) -- IN operator with subquery on the right
@@ -69290,14 +69924,14 @@
6929069924
assert( testAddr>0 || pParse->db->mallocFailed );
6929169925
}
6929269926
6929369927
switch( pExpr->op ){
6929469928
case TK_IN: {
69295
- char affinity;
69296
- KeyInfo keyInfo;
69297
- int addr; /* Address of OP_OpenEphemeral instruction */
69298
- Expr *pLeft = pExpr->pLeft;
69929
+ char affinity; /* Affinity of the LHS of the IN */
69930
+ KeyInfo keyInfo; /* Keyinfo for the generated table */
69931
+ int addr; /* Address of OP_OpenEphemeral instruction */
69932
+ Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
6929969933
6930069934
if( rMayHaveNull ){
6930169935
sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
6930269936
}
6930369937
@@ -69316,10 +69950,11 @@
6931669950
** 'x' nor the SELECT... statement are columns, then numeric affinity
6931769951
** is used.
6931869952
*/
6931969953
pExpr->iTable = pParse->nTab++;
6932069954
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
69955
+ if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
6932169956
memset(&keyInfo, 0, sizeof(keyInfo));
6932269957
keyInfo.nField = 1;
6932369958
6932469959
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
6932569960
/* Case 1: expr IN (SELECT ...)
@@ -69924,77 +70559,10 @@
6992470559
}
6992570560
return 0;
6992670561
}
6992770562
#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
6992870563
69929
-/*
69930
-** If the last instruction coded is an ephemeral copy of any of
69931
-** the registers in the nReg registers beginning with iReg, then
69932
-** convert the last instruction from OP_SCopy to OP_Copy.
69933
-*/
69934
-SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
69935
- VdbeOp *pOp;
69936
- Vdbe *v;
69937
-
69938
- assert( pParse->db->mallocFailed==0 );
69939
- v = pParse->pVdbe;
69940
- assert( v!=0 );
69941
- pOp = sqlite3VdbeGetOp(v, -1);
69942
- assert( pOp!=0 );
69943
- if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
69944
- pOp->opcode = OP_Copy;
69945
- }
69946
-}
69947
-
69948
-/*
69949
-** Generate code to store the value of the iAlias-th alias in register
69950
-** target. The first time this is called, pExpr is evaluated to compute
69951
-** the value of the alias. The value is stored in an auxiliary register
69952
-** and the number of that register is returned. On subsequent calls,
69953
-** the register number is returned without generating any code.
69954
-**
69955
-** Note that in order for this to work, code must be generated in the
69956
-** same order that it is executed.
69957
-**
69958
-** Aliases are numbered starting with 1. So iAlias is in the range
69959
-** of 1 to pParse->nAlias inclusive.
69960
-**
69961
-** pParse->aAlias[iAlias-1] records the register number where the value
69962
-** of the iAlias-th alias is stored. If zero, that means that the
69963
-** alias has not yet been computed.
69964
-*/
69965
-static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
69966
-#if 0
69967
- sqlite3 *db = pParse->db;
69968
- int iReg;
69969
- if( pParse->nAliasAlloc<pParse->nAlias ){
69970
- pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
69971
- sizeof(pParse->aAlias[0])*pParse->nAlias );
69972
- testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
69973
- if( db->mallocFailed ) return 0;
69974
- memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
69975
- (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
69976
- pParse->nAliasAlloc = pParse->nAlias;
69977
- }
69978
- assert( iAlias>0 && iAlias<=pParse->nAlias );
69979
- iReg = pParse->aAlias[iAlias-1];
69980
- if( iReg==0 ){
69981
- if( pParse->iCacheLevel>0 ){
69982
- iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69983
- }else{
69984
- iReg = ++pParse->nMem;
69985
- sqlite3ExprCode(pParse, pExpr, iReg);
69986
- pParse->aAlias[iAlias-1] = iReg;
69987
- }
69988
- }
69989
- return iReg;
69990
-#else
69991
- UNUSED_PARAMETER(iAlias);
69992
- return sqlite3ExprCodeTarget(pParse, pExpr, target);
69993
-#endif
69994
-}
69995
-
6999670564
/*
6999770565
** Generate code into the current Vdbe to evaluate the given
6999870566
** expression. Attempt to store the results in register "target".
6999970567
** Return the register where results are stored.
7000070568
**
@@ -70099,11 +70667,11 @@
7009970667
case TK_REGISTER: {
7010070668
inReg = pExpr->iTable;
7010170669
break;
7010270670
}
7010370671
case TK_AS: {
70104
- inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
70672
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
7010570673
break;
7010670674
}
7010770675
#ifndef SQLITE_OMIT_CAST
7010870676
case TK_CAST: {
7010970677
/* Expressions of the form: CAST(pLeft AS token) */
@@ -70531,10 +71099,15 @@
7053171099
testcase( regFree1==0 );
7053271100
cacheX.op = TK_REGISTER;
7053371101
opCompare.op = TK_EQ;
7053471102
opCompare.pLeft = &cacheX;
7053571103
pTest = &opCompare;
71104
+ /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
71105
+ ** The value in regFree1 might get SCopy-ed into the file result.
71106
+ ** So make sure that the regFree1 register is not reused for other
71107
+ ** purposes and possibly overwritten. */
71108
+ regFree1 = 0;
7053671109
}
7053771110
for(i=0; i<nExpr; i=i+2){
7053871111
sqlite3ExprCachePush(pParse);
7053971112
if( pX ){
7054071113
assert( pTest!=0 );
@@ -70624,14 +71197,18 @@
7062471197
*/
7062571198
SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
7062671199
int inReg;
7062771200
7062871201
assert( target>0 && target<=pParse->nMem );
70629
- inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
70630
- assert( pParse->pVdbe || pParse->db->mallocFailed );
70631
- if( inReg!=target && pParse->pVdbe ){
70632
- sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71202
+ if( pExpr && pExpr->op==TK_REGISTER ){
71203
+ sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
71204
+ }else{
71205
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
71206
+ assert( pParse->pVdbe || pParse->db->mallocFailed );
71207
+ if( inReg!=target && pParse->pVdbe ){
71208
+ sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71209
+ }
7063371210
}
7063471211
return target;
7063571212
}
7063671213
7063771214
/*
@@ -70800,23 +71377,18 @@
7080071377
){
7080171378
struct ExprList_item *pItem;
7080271379
int i, n;
7080371380
assert( pList!=0 );
7080471381
assert( target>0 );
71382
+ assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
7080571383
n = pList->nExpr;
7080671384
for(pItem=pList->a, i=0; i<n; i++, pItem++){
70807
- if( pItem->iAlias ){
70808
- int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
70809
- Vdbe *v = sqlite3GetVdbe(pParse);
70810
- if( iReg!=target+i ){
70811
- sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
70812
- }
70813
- }else{
70814
- sqlite3ExprCode(pParse, pItem->pExpr, target+i);
70815
- }
70816
- if( doHardCopy && !pParse->db->mallocFailed ){
70817
- sqlite3ExprHardCopy(pParse, target, n);
71385
+ Expr *pExpr = pItem->pExpr;
71386
+ int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
71387
+ if( inReg!=target+i ){
71388
+ sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
71389
+ inReg, target+i);
7081871390
}
7081971391
}
7082071392
return n;
7082171393
}
7082271394
@@ -71794,10 +72366,15 @@
7179472366
if( pTrig->pSchema==pTempSchema ){
7179572367
zWhere = whereOrName(db, zWhere, pTrig->zName);
7179672368
}
7179772369
}
7179872370
}
72371
+ if( zWhere ){
72372
+ char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
72373
+ sqlite3DbFree(pParse->db, zWhere);
72374
+ zWhere = zNew;
72375
+ }
7179972376
return zWhere;
7180072377
}
7180172378
7180272379
/*
7180372380
** Generate code to drop and reload the internal representation of table
@@ -72401,11 +72978,12 @@
7240172978
int iIdxCur; /* Cursor open on index being analyzed */
7240272979
Vdbe *v; /* The virtual machine being built up */
7240372980
int i; /* Loop counter */
7240472981
int topOfLoop; /* The top of the loop */
7240572982
int endOfLoop; /* The end of the loop */
72406
- int addr; /* The address of an instruction */
72983
+ int addr = 0; /* The address of an instruction */
72984
+ int jZeroRows = 0; /* Jump from here if number of rows is zero */
7240772985
int iDb; /* Index of database containing pTab */
7240872986
int regTabname = iMem++; /* Register containing table name */
7240972987
int regIdxname = iMem++; /* Register containing index name */
7241072988
int regSampleno = iMem++; /* Register containing next sample number */
7241172989
int regCol = iMem++; /* Content of a column analyzed table */
@@ -72420,12 +72998,19 @@
7242072998
int regLast = iMem++; /* Index of last sample to record */
7242172999
int regFirst = iMem++; /* Index of first sample to record */
7242273000
#endif
7242373001
7242473002
v = sqlite3GetVdbe(pParse);
72425
- if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
72426
- /* Do no analysis for tables that have no indices */
73003
+ if( v==0 || NEVER(pTab==0) ){
73004
+ return;
73005
+ }
73006
+ if( pTab->tnum==0 ){
73007
+ /* Do not gather statistics on views or virtual tables */
73008
+ return;
73009
+ }
73010
+ if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
73011
+ /* Do not gather statistics on system tables */
7242773012
return;
7242873013
}
7242973014
assert( sqlite3BtreeHoldsAllMutexes(db) );
7243073015
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
7243173016
assert( iDb>=0 );
@@ -72438,10 +73023,11 @@
7243873023
7243973024
/* Establish a read-lock on the table at the shared-cache level. */
7244073025
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
7244173026
7244273027
iIdxCur = pParse->nTab++;
73028
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
7244373029
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
7244473030
int nCol = pIdx->nColumn;
7244573031
KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
7244673032
7244773033
if( iMem+1+(nCol*2)>pParse->nMem ){
@@ -72452,14 +73038,11 @@
7245273038
assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
7245373039
sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
7245473040
(char *)pKey, P4_KEYINFO_HANDOFF);
7245573041
VdbeComment((v, "%s", pIdx->zName));
7245673042
72457
- /* Populate the registers containing the table and index names. */
72458
- if( pTab->pIndex==pIdx ){
72459
- sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
72460
- }
73043
+ /* Populate the register containing the index name. */
7246173044
sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
7246273045
7246373046
#ifdef SQLITE_ENABLE_STAT2
7246473047
7246573048
/* If this iteration of the loop is generating code to analyze the
@@ -72590,12 +73173,14 @@
7259073173
**
7259173174
** If K==0 then no entry is made into the sqlite_stat1 table.
7259273175
** If K>0 then it is always the case the D>0 so division by zero
7259373176
** is never possible.
7259473177
*/
72595
- addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
7259673178
sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
73179
+ if( jZeroRows==0 ){
73180
+ jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
73181
+ }
7259773182
for(i=0; i<nCol; i++){
7259873183
sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
7259973184
sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
7260073185
sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
7260173186
sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
@@ -72605,17 +73190,39 @@
7260573190
}
7260673191
sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
7260773192
sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
7260873193
sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
7260973194
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73195
+ }
73196
+
73197
+ /* If the table has no indices, create a single sqlite_stat1 entry
73198
+ ** containing NULL as the index name and the row count as the content.
73199
+ */
73200
+ if( pTab->pIndex==0 ){
73201
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
73202
+ VdbeComment((v, "%s", pTab->zName));
73203
+ sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
73204
+ sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73205
+ }else{
73206
+ assert( jZeroRows>0 );
73207
+ addr = sqlite3VdbeAddOp0(v, OP_Goto);
73208
+ sqlite3VdbeJumpHere(v, jZeroRows);
73209
+ }
73210
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
73211
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73212
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73213
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73214
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73215
+ if( pParse->nMem<regRec ) pParse->nMem = regRec;
73216
+ if( jZeroRows ){
7261073217
sqlite3VdbeJumpHere(v, addr);
7261173218
}
7261273219
}
7261373220
7261473221
/*
7261573222
** Generate code that will cause the most recent index analysis to
72616
-** be laoded into internal hash tables where is can be used.
73223
+** be loaded into internal hash tables where is can be used.
7261773224
*/
7261873225
static void loadAnalysis(Parse *pParse, int iDb){
7261973226
Vdbe *v = sqlite3GetVdbe(pParse);
7262073227
if( v ){
7262173228
sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
@@ -72741,37 +73348,50 @@
7274173348
7274273349
/*
7274373350
** This callback is invoked once for each index when reading the
7274473351
** sqlite_stat1 table.
7274573352
**
72746
-** argv[0] = name of the index
72747
-** argv[1] = results of analysis - on integer for each column
73353
+** argv[0] = name of the table
73354
+** argv[1] = name of the index (might be NULL)
73355
+** argv[2] = results of analysis - on integer for each column
73356
+**
73357
+** Entries for which argv[1]==NULL simply record the number of rows in
73358
+** the table.
7274873359
*/
7274973360
static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
7275073361
analysisInfo *pInfo = (analysisInfo*)pData;
7275173362
Index *pIndex;
72752
- int i, c;
73363
+ Table *pTable;
73364
+ int i, c, n;
7275373365
unsigned int v;
7275473366
const char *z;
7275573367
72756
- assert( argc==2 );
73368
+ assert( argc==3 );
7275773369
UNUSED_PARAMETER2(NotUsed, argc);
7275873370
72759
- if( argv==0 || argv[0]==0 || argv[1]==0 ){
73371
+ if( argv==0 || argv[0]==0 || argv[2]==0 ){
7276073372
return 0;
7276173373
}
72762
- pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
72763
- if( pIndex==0 ){
73374
+ pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
73375
+ if( pTable==0 ){
7276473376
return 0;
7276573377
}
72766
- z = argv[1];
72767
- for(i=0; *z && i<=pIndex->nColumn; i++){
73378
+ if( argv[1] ){
73379
+ pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
73380
+ }else{
73381
+ pIndex = 0;
73382
+ }
73383
+ n = pIndex ? pIndex->nColumn : 0;
73384
+ z = argv[2];
73385
+ for(i=0; *z && i<=n; i++){
7276873386
v = 0;
7276973387
while( (c=z[0])>='0' && c<='9' ){
7277073388
v = v*10 + c - '0';
7277173389
z++;
7277273390
}
73391
+ if( i==0 ) pTable->nRowEst = v;
73392
+ if( pIndex==0 ) break;
7277373393
pIndex->aiRowEst[i] = v;
7277473394
if( *z==' ' ) z++;
7277573395
}
7277673396
return 0;
7277773397
}
@@ -72843,11 +73463,11 @@
7284373463
return SQLITE_ERROR;
7284473464
}
7284573465
7284673466
/* Load new statistics out of the sqlite_stat1 table */
7284773467
zSql = sqlite3MPrintf(db,
72848
- "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
73468
+ "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
7284973469
if( zSql==0 ){
7285073470
rc = SQLITE_NOMEM;
7285173471
}else{
7285273472
rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
7285373473
sqlite3DbFree(db, zSql);
@@ -73060,13 +73680,12 @@
7306073680
7306173681
/* Open the database file. If the btree is successfully opened, use
7306273682
** it to obtain the database schema. At this point the schema may
7306373683
** or may not be initialised.
7306473684
*/
73065
- rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
73066
- db->openFlags | SQLITE_OPEN_MAIN_DB,
73067
- &aNew->pBt);
73685
+ rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
73686
+ db->openFlags | SQLITE_OPEN_MAIN_DB);
7306873687
db->nDb++;
7306973688
if( rc==SQLITE_CONSTRAINT ){
7307073689
rc = SQLITE_ERROR;
7307173690
zErrDyn = sqlite3MPrintf(db, "database is already attached");
7307273691
}else if( rc==SQLITE_OK ){
@@ -73303,11 +73922,12 @@
7330373922
0, /* pNext */
7330473923
detachFunc, /* xFunc */
7330573924
0, /* xStep */
7330673925
0, /* xFinalize */
7330773926
"sqlite_detach", /* zName */
73308
- 0 /* pHash */
73927
+ 0, /* pHash */
73928
+ 0 /* pDestructor */
7330973929
};
7331073930
codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
7331173931
}
7331273932
7331373933
/*
@@ -73324,11 +73944,12 @@
7332473944
0, /* pNext */
7332573945
attachFunc, /* xFunc */
7332673946
0, /* xStep */
7332773947
0, /* xFinalize */
7332873948
"sqlite_attach", /* zName */
73329
- 0 /* pHash */
73949
+ 0, /* pHash */
73950
+ 0 /* pDestructor */
7333073951
};
7333173952
codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
7333273953
}
7333373954
#endif /* SQLITE_OMIT_ATTACH */
7333473955
@@ -74453,12 +75074,13 @@
7445375074
** set to the index of the database that the table or view is to be
7445475075
** created in.
7445575076
*/
7445675077
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
7445775078
if( iDb<0 ) return;
74458
- if( !OMIT_TEMPDB && isTemp && iDb>1 ){
74459
- /* If creating a temp table, the name may not be qualified */
75079
+ if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
75080
+ /* If creating a temp table, the name may not be qualified. Unless
75081
+ ** the database name is "temp" anyway. */
7446075082
sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
7446175083
return;
7446275084
}
7446375085
if( !OMIT_TEMPDB && isTemp ) iDb = 1;
7446475086
@@ -74502,21 +75124,22 @@
7450275124
** to an sqlite3_declare_vtab() call. In that case only the column names
7450375125
** and types will be used, so there is no need to test for namespace
7450475126
** collisions.
7450575127
*/
7450675128
if( !IN_DECLARE_VTAB ){
75129
+ char *zDb = db->aDb[iDb].zName;
7450775130
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
7450875131
goto begin_table_error;
7450975132
}
74510
- pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
75133
+ pTable = sqlite3FindTable(db, zName, zDb);
7451175134
if( pTable ){
7451275135
if( !noErr ){
7451375136
sqlite3ErrorMsg(pParse, "table %T already exists", pName);
7451475137
}
7451575138
goto begin_table_error;
7451675139
}
74517
- if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
75140
+ if( sqlite3FindIndex(db, zName, zDb)!=0 ){
7451875141
sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
7451975142
goto begin_table_error;
7452075143
}
7452175144
}
7452275145
@@ -74529,10 +75152,11 @@
7452975152
}
7453075153
pTable->zName = zName;
7453175154
pTable->iPKey = -1;
7453275155
pTable->pSchema = db->aDb[iDb].pSchema;
7453375156
pTable->nRef = 1;
75157
+ pTable->nRowEst = 1000000;
7453475158
assert( pParse->pNewTable==0 );
7453575159
pParse->pNewTable = pTable;
7453675160
7453775161
/* If this is the magic sqlite_sequence table used by autoincrement,
7453875162
** then record a pointer to this table in the main database structure
@@ -75375,16 +75999,14 @@
7537575999
sqlite3SelectDelete(db, pSelect);
7537676000
return;
7537776001
}
7537876002
sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
7537976003
p = pParse->pNewTable;
75380
- if( p==0 ){
76004
+ if( p==0 || pParse->nErr ){
7538176005
sqlite3SelectDelete(db, pSelect);
7538276006
return;
7538376007
}
75384
- assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
75385
- ** there could not have been an error */
7538676008
sqlite3TwoPartName(pParse, pName1, pName2, &pName);
7538776009
iDb = sqlite3SchemaToIndex(db, p->pSchema);
7538876010
if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
7538976011
&& sqlite3FixSelect(&sFix, pSelect)
7539076012
){
@@ -76498,11 +77120,12 @@
7649877120
*/
7649977121
if( pTblName ){
7650077122
sqlite3RefillIndex(pParse, pIndex, iMem);
7650177123
sqlite3ChangeCookie(pParse, iDb);
7650277124
sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
76503
- sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
77125
+ sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
77126
+ P4_DYNAMIC);
7650477127
sqlite3VdbeAddOp1(v, OP_Expire, 0);
7650577128
}
7650677129
}
7650777130
7650877131
/* When adding an index to the list of indices for a table, make
@@ -76559,18 +77182,18 @@
7655977182
** are based on typical values found in actual indices.
7656077183
*/
7656177184
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
7656277185
unsigned *a = pIdx->aiRowEst;
7656377186
int i;
77187
+ unsigned n;
7656477188
assert( a!=0 );
76565
- a[0] = 1000000;
76566
- for(i=pIdx->nColumn; i>=5; i--){
76567
- a[i] = 5;
76568
- }
76569
- while( i>=1 ){
76570
- a[i] = 11 - i;
76571
- i--;
77189
+ a[0] = pIdx->pTable->nRowEst;
77190
+ if( a[0]<10 ) a[0] = 10;
77191
+ n = 10;
77192
+ for(i=1; i<=pIdx->nColumn; i++){
77193
+ a[i] = n;
77194
+ if( n>5 ) n--;
7657277195
}
7657377196
if( pIdx->onError!=OE_None ){
7657477197
a[pIdx->nColumn] = 1;
7657577198
}
7657677199
}
@@ -76626,11 +77249,11 @@
7662677249
/* Generate code to remove the index and from the master table */
7662777250
v = sqlite3GetVdbe(pParse);
7662877251
if( v ){
7662977252
sqlite3BeginWriteOperation(pParse, 1, iDb);
7663077253
sqlite3NestedParse(pParse,
76631
- "DELETE FROM %Q.%s WHERE name=%Q",
77254
+ "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
7663277255
db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
7663377256
pIndex->zName
7663477257
);
7663577258
if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
7663677259
sqlite3NestedParse(pParse,
@@ -77118,11 +77741,11 @@
7711877741
SQLITE_OPEN_CREATE |
7711977742
SQLITE_OPEN_EXCLUSIVE |
7712077743
SQLITE_OPEN_DELETEONCLOSE |
7712177744
SQLITE_OPEN_TEMP_DB;
7712277745
77123
- rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
77746
+ rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
7712477747
if( rc!=SQLITE_OK ){
7712577748
sqlite3ErrorMsg(pParse, "unable to open a temporary database "
7712677749
"file for storing temporary tables");
7712777750
pParse->rc = rc;
7712877751
return 1;
@@ -77775,11 +78398,11 @@
7777578398
** If the SQLITE_PreferBuiltin flag is set, then search the built-in
7777678399
** functions even if a prior app-defined function was found. And give
7777778400
** priority to built-in functions.
7777878401
**
7777978402
** Except, if createFlag is true, that means that we are trying to
77780
- ** install a new function. Whatever FuncDef structure is returned will
78403
+ ** install a new function. Whatever FuncDef structure is returned it will
7778178404
** have fields overwritten with new information appropriate for the
7778278405
** new function. But the FuncDefs for built-in functions are read-only.
7778378406
** So we must not search for built-ins when creating a new function.
7778478407
*/
7778578408
if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
@@ -79956,14 +80579,14 @@
7995680579
if( caseSensitive ){
7995780580
pInfo = (struct compareInfo*)&likeInfoAlt;
7995880581
}else{
7995980582
pInfo = (struct compareInfo*)&likeInfoNorm;
7996080583
}
79961
- sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79962
- sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
80584
+ sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80585
+ sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
7996380586
sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
79964
- (struct compareInfo*)&globInfo, likeFunc, 0,0);
80587
+ (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
7996580588
setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
7996680589
setLikeOptFlag(db, "like",
7996780590
caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
7996880591
}
7996980592
@@ -80043,14 +80666,14 @@
8004380666
FUNCTION(upper, 1, 0, 0, upperFunc ),
8004480667
FUNCTION(lower, 1, 0, 0, lowerFunc ),
8004580668
FUNCTION(coalesce, 1, 0, 0, 0 ),
8004680669
FUNCTION(coalesce, 0, 0, 0, 0 ),
8004780670
/* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
80048
- {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
80671
+ {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
8004980672
FUNCTION(hex, 1, 0, 0, hexFunc ),
8005080673
/* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
80051
- {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
80674
+ {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
8005280675
FUNCTION(random, 0, 0, 0, randomFunc ),
8005380676
FUNCTION(randomblob, 1, 0, 0, randomBlob ),
8005480677
FUNCTION(nullif, 2, 0, 1, nullifFunc ),
8005580678
FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
8005680679
FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
@@ -80073,11 +80696,11 @@
8007380696
#endif
8007480697
AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
8007580698
AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
8007680699
AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
8007780700
/* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
80078
- {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
80701
+ {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
8007980702
AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
8008080703
AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
8008180704
AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
8008280705
8008380706
LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
@@ -80484,11 +81107,11 @@
8048481107
KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
8048581108
8048681109
sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
8048781110
sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
8048881111
for(i=0; i<nCol; i++){
80489
- sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
81112
+ sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
8049081113
}
8049181114
8049281115
/* If the parent table is the same as the child table, and we are about
8049381116
** to increment the constraint-counter (i.e. this is an INSERT operation),
8049481117
** then check if the row being inserted matches itself. If so, do not
@@ -87131,15 +87754,17 @@
8713187754
sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
8713287755
sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
8713387756
sqlite3ReleaseTempReg(pParse, r1);
8713487757
}
8713587758
87759
+#ifndef SQLITE_OMIT_SUBQUERY
8713687760
/*
8713787761
** Generate an error message when a SELECT is used within a subexpression
8713887762
** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
87139
-** column. We do this in a subroutine because the error occurs in multiple
87140
-** places.
87763
+** column. We do this in a subroutine because the error used to occur
87764
+** in multiple places. (The error only occurs in one place now, but we
87765
+** retain the subroutine to minimize code disruption.)
8714187766
*/
8714287767
static int checkForMultiColumnSelectError(
8714387768
Parse *pParse, /* Parse context. */
8714487769
SelectDest *pDest, /* Destination of SELECT results */
8714587770
int nExpr /* Number of result columns returned by SELECT */
@@ -87151,10 +87776,11 @@
8715187776
return 1;
8715287777
}else{
8715387778
return 0;
8715487779
}
8715587780
}
87781
+#endif
8715687782
8715787783
/*
8715887784
** This routine generates the code for the inside of the inner loop
8715987785
** of a SELECT.
8716087786
**
@@ -87230,14 +87856,10 @@
8723087856
if( pOrderBy==0 ){
8723187857
codeOffset(v, p, iContinue);
8723287858
}
8723387859
}
8723487860
87235
- if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
87236
- return;
87237
- }
87238
-
8723987861
switch( eDest ){
8724087862
/* In this mode, write each query result to the key of the temporary
8724187863
** table iParm.
8724287864
*/
8724387865
#ifndef SQLITE_OMIT_COMPOUND_SELECT
@@ -88143,10 +88765,11 @@
8814388765
/* Create the destination temporary table if necessary
8814488766
*/
8814588767
if( dest.eDest==SRT_EphemTab ){
8814688768
assert( p->pEList );
8814788769
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
88770
+ sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
8814888771
dest.eDest = SRT_Table;
8814988772
}
8815088773
8815188774
/* Make sure all SELECTs in the statement have the same number of elements
8815288775
** in their result sets.
@@ -90105,11 +90728,11 @@
9010590728
ExprList *pList = pF->pExpr->x.pList;
9010690729
assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
9010790730
if( pList ){
9010890731
nArg = pList->nExpr;
9010990732
regAgg = sqlite3GetTempRange(pParse, nArg);
90110
- sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
90733
+ sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
9011190734
}else{
9011290735
nArg = 0;
9011390736
regAgg = 0;
9011490737
}
9011590738
if( pF->iDistinct>=0 ){
@@ -90264,10 +90887,19 @@
9026490887
9026590888
/* Begin generating code.
9026690889
*/
9026790890
v = sqlite3GetVdbe(pParse);
9026890891
if( v==0 ) goto select_end;
90892
+
90893
+ /* If writing to memory or generating a set
90894
+ ** only a single column may be output.
90895
+ */
90896
+#ifndef SQLITE_OMIT_SUBQUERY
90897
+ if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90898
+ goto select_end;
90899
+ }
90900
+#endif
9026990901
9027090902
/* Generate code for all sub-queries in the FROM clause
9027190903
*/
9027290904
#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
9027390905
for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
@@ -90338,19 +90970,10 @@
9033890970
}
9033990971
return multiSelect(pParse, p, pDest);
9034090972
}
9034190973
#endif
9034290974
90343
- /* If writing to memory or generating a set
90344
- ** only a single column may be output.
90345
- */
90346
-#ifndef SQLITE_OMIT_SUBQUERY
90347
- if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90348
- goto select_end;
90349
- }
90350
-#endif
90351
-
9035290975
/* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
9035390976
** GROUP BY might use an index, DISTINCT never does.
9035490977
*/
9035590978
assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
9035690979
if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
@@ -90409,10 +91032,11 @@
9040991032
assert( isAgg || pGroupBy );
9041091033
distinct = pParse->nTab++;
9041191034
pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
9041291035
sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
9041391036
(char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91037
+ sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
9041491038
}else{
9041591039
distinct = -1;
9041691040
}
9041791041
9041891042
/* Aggregate and non-aggregate queries are handled differently */
@@ -92884,10 +93508,11 @@
9288493508
** be stored.
9288593509
*/
9288693510
assert( v );
9288793511
ephemTab = pParse->nTab++;
9288893512
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
93513
+ sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
9288993514
9289093515
/* fill the ephemeral table
9289193516
*/
9289293517
sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
9289393518
sqlite3Select(pParse, pSelect, &dest);
@@ -93022,10 +93647,14 @@
9302293647
int nDb; /* Number of attached databases */
9302393648
9302493649
if( !db->autoCommit ){
9302593650
sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
9302693651
return SQLITE_ERROR;
93652
+ }
93653
+ if( db->activeVdbeCnt>1 ){
93654
+ sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
93655
+ return SQLITE_ERROR;
9302793656
}
9302893657
9302993658
/* Save the current value of the database flags so that it can be
9303093659
** restored before returning. Then set the writable-schema flag, and
9303193660
** disable CHECK and foreign key constraints. */
@@ -93624,11 +94253,11 @@
9362494253
sqlite3DbFree(db, zStmt);
9362594254
v = sqlite3GetVdbe(pParse);
9362694255
sqlite3ChangeCookie(pParse, iDb);
9362794256
9362894257
sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93629
- zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
94258
+ zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
9363094259
sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
9363194260
sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
9363294261
pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
9363394262
}
9363494263
@@ -94864,15 +95493,16 @@
9486495493
if( op==TK_REGISTER ){
9486595494
op = pRight->op2;
9486695495
}
9486795496
if( op==TK_VARIABLE ){
9486895497
Vdbe *pReprepare = pParse->pReprepare;
94869
- pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
95498
+ int iCol = pRight->iColumn;
95499
+ pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
9487095500
if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
9487195501
z = (char *)sqlite3_value_text(pVal);
9487295502
}
94873
- sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
95503
+ sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
9487495504
assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
9487595505
}else if( op==TK_STRING ){
9487695506
z = pRight->u.zToken;
9487795507
}
9487895508
if( z ){
@@ -94886,11 +95516,11 @@
9488695516
pPrefix = sqlite3Expr(db, TK_STRING, z);
9488795517
if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
9488895518
*ppPrefix = pPrefix;
9488995519
if( op==TK_VARIABLE ){
9489095520
Vdbe *v = pParse->pVdbe;
94891
- sqlite3VdbeSetVarmask(v, pRight->iColumn);
95521
+ sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
9489295522
if( *pisComplete && pRight->u.zToken[1] ){
9489395523
/* If the rhs of the LIKE expression is a variable, and the current
9489495524
** value of the variable means there is no need to invoke the LIKE
9489595525
** function, then no OP_Variable will be added to the program.
9489695526
** This causes problems for the sqlite3_bind_parameter_name()
@@ -95900,11 +96530,11 @@
9590096530
return;
9590196531
}
9590296532
9590396533
assert( pParse->nQueryLoop >= (double)1 );
9590496534
pTable = pSrc->pTab;
95905
- nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
96535
+ nTableRow = pTable->nRowEst;
9590696536
logN = estLog(nTableRow);
9590796537
costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
9590896538
if( costTempIdx>=pCost->rCost ){
9590996539
/* The cost of creating the transient table would be greater than
9591096540
** doing the full table scan */
@@ -96510,11 +97140,11 @@
9651097140
/* The evalConstExpr() function will have already converted any TK_VARIABLE
9651197141
** expression involved in an comparison into a TK_REGISTER. */
9651297142
assert( pExpr->op!=TK_VARIABLE );
9651397143
if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
9651497144
int iVar = pExpr->iColumn;
96515
- sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
97145
+ sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
9651697146
*pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
9651797147
return SQLITE_OK;
9651897148
}
9651997149
return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
9652097150
}
@@ -96707,27 +97337,18 @@
9670797337
Index *pFirst; /* Any other index on the table */
9670897338
memset(&sPk, 0, sizeof(Index));
9670997339
sPk.nColumn = 1;
9671097340
sPk.aiColumn = &aiColumnPk;
9671197341
sPk.aiRowEst = aiRowEstPk;
96712
- aiRowEstPk[1] = 1;
9671397342
sPk.onError = OE_Replace;
9671497343
sPk.pTable = pSrc->pTab;
97344
+ aiRowEstPk[0] = pSrc->pTab->nRowEst;
97345
+ aiRowEstPk[1] = 1;
9671597346
pFirst = pSrc->pTab->pIndex;
9671697347
if( pSrc->notIndexed==0 ){
9671797348
sPk.pNext = pFirst;
9671897349
}
96719
- /* The aiRowEstPk[0] is an estimate of the total number of rows in the
96720
- ** table. Get this information from the ANALYZE information if it is
96721
- ** available. If not available, assume the table 1 million rows in size.
96722
- */
96723
- if( pFirst ){
96724
- assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
96725
- aiRowEstPk[0] = pFirst->aiRowEst[0];
96726
- }else{
96727
- aiRowEstPk[0] = 1000000;
96728
- }
9672997350
pProbe = &sPk;
9673097351
wsFlagMask = ~(
9673197352
WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
9673297353
);
9673397354
eqTermMask = WO_EQ|WO_IN;
@@ -98297,11 +98918,11 @@
9829798918
** CREATE TABLE t2(c, d);
9829898919
** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
9829998920
**
9830098921
** The best strategy is to iterate through table t1 first. However it
9830198922
** is not possible to determine this with a simple greedy algorithm.
98302
- ** However, since the cost of a linear scan through table t2 is the same
98923
+ ** Since the cost of a linear scan through table t2 is the same
9830398924
** as the cost of a linear scan through table t1, a simple greedy
9830498925
** algorithm may choose to use t2 for the outer loop, which is a much
9830598926
** costlier approach.
9830698927
*/
9830798928
nUnconstrained = 0;
@@ -103366,19 +103987,37 @@
103366103987
103367103988
/************** End of sqliteicu.h *******************************************/
103368103989
/************** Continuing where we left off in main.c ***********************/
103369103990
#endif
103370103991
103371
-/*
103372
-** The version of the library
103373
-*/
103374103992
#ifndef SQLITE_AMALGAMATION
103993
+/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
103994
+** contains the text of SQLITE_VERSION macro.
103995
+*/
103375103996
SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
103376103997
#endif
103998
+
103999
+/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
104000
+** a pointer to the to the sqlite3_version[] string constant.
104001
+*/
103377104002
SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
104003
+
104004
+/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
104005
+** pointer to a string constant whose value is the same as the
104006
+** SQLITE_SOURCE_ID C preprocessor macro.
104007
+*/
103378104008
SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
104009
+
104010
+/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
104011
+** returns an integer equal to SQLITE_VERSION_NUMBER.
104012
+*/
103379104013
SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
104014
+
104015
+/* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
104016
+** zero if and only if SQLite was compiled mutexing code omitted due to
104017
+** the SQLITE_THREADSAFE compile-time option being set to 0.
104018
+*/
103380104019
SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
103381104020
103382104021
#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
103383104022
/*
103384104023
** If the following function pointer is not NULL and if
@@ -103495,10 +104134,17 @@
103495104134
/* Do the rest of the initialization under the recursive mutex so
103496104135
** that we will be able to handle recursive calls into
103497104136
** sqlite3_initialize(). The recursive calls normally come through
103498104137
** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
103499104138
** recursive calls might also be possible.
104139
+ **
104140
+ ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
104141
+ ** to the xInit method, so the xInit method need not be threadsafe.
104142
+ **
104143
+ ** The following mutex is what serializes access to the appdef pcache xInit
104144
+ ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
104145
+ ** call to sqlite3PcacheInitialize().
103500104146
*/
103501104147
sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
103502104148
if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
103503104149
FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
103504104150
sqlite3GlobalConfig.inProgress = 1;
@@ -103775,16 +104421,16 @@
103775104421
if( cnt<0 ) cnt = 0;
103776104422
if( sz==0 || cnt==0 ){
103777104423
sz = 0;
103778104424
pStart = 0;
103779104425
}else if( pBuf==0 ){
103780
- sz = ROUND8(sz);
104426
+ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
103781104427
sqlite3BeginBenignMalloc();
103782
- pStart = sqlite3Malloc( sz*cnt );
104428
+ pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
103783104429
sqlite3EndBenignMalloc();
103784104430
}else{
103785
- sz = ROUNDDOWN8(sz);
104431
+ sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
103786104432
pStart = pBuf;
103787104433
}
103788104434
db->lookaside.pStart = pStart;
103789104435
db->lookaside.pFree = 0;
103790104436
db->lookaside.sz = (u16)sz;
@@ -103823,18 +104469,18 @@
103823104469
va_list ap;
103824104470
int rc;
103825104471
va_start(ap, op);
103826104472
switch( op ){
103827104473
case SQLITE_DBCONFIG_LOOKASIDE: {
103828
- void *pBuf = va_arg(ap, void*);
103829
- int sz = va_arg(ap, int);
103830
- int cnt = va_arg(ap, int);
104474
+ void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
104475
+ int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
104476
+ int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
103831104477
rc = setupLookaside(db, pBuf, sz, cnt);
103832104478
break;
103833104479
}
103834104480
default: {
103835
- rc = SQLITE_ERROR;
104481
+ rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
103836104482
break;
103837104483
}
103838104484
}
103839104485
va_end(ap);
103840104486
return rc;
@@ -103934,16 +104580,33 @@
103934104580
}
103935104581
db->nSavepoint = 0;
103936104582
db->nStatement = 0;
103937104583
db->isTransactionSavepoint = 0;
103938104584
}
104585
+
104586
+/*
104587
+** Invoke the destructor function associated with FuncDef p, if any. Except,
104588
+** if this is not the last copy of the function, do not invoke it. Multiple
104589
+** copies of a single function are created when create_function() is called
104590
+** with SQLITE_ANY as the encoding.
104591
+*/
104592
+static void functionDestroy(sqlite3 *db, FuncDef *p){
104593
+ FuncDestructor *pDestructor = p->pDestructor;
104594
+ if( pDestructor ){
104595
+ pDestructor->nRef--;
104596
+ if( pDestructor->nRef==0 ){
104597
+ pDestructor->xDestroy(pDestructor->pUserData);
104598
+ sqlite3DbFree(db, pDestructor);
104599
+ }
104600
+ }
104601
+}
103939104602
103940104603
/*
103941104604
** Close an existing SQLite database
103942104605
*/
103943104606
SQLITE_API int sqlite3_close(sqlite3 *db){
103944
- HashElem *i;
104607
+ HashElem *i; /* Hash table iterator */
103945104608
int j;
103946104609
103947104610
if( !db ){
103948104611
return SQLITE_OK;
103949104612
}
@@ -104007,10 +104670,11 @@
104007104670
for(j=0; j<ArraySize(db->aFunc.a); j++){
104008104671
FuncDef *pNext, *pHash, *p;
104009104672
for(p=db->aFunc.a[j]; p; p=pHash){
104010104673
pHash = p->pHash;
104011104674
while( p ){
104675
+ functionDestroy(db, p);
104012104676
pNext = p->pNext;
104013104677
sqlite3DbFree(db, p);
104014104678
p = pNext;
104015104679
}
104016104680
}
@@ -104281,11 +104945,12 @@
104281104945
int nArg,
104282104946
int enc,
104283104947
void *pUserData,
104284104948
void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104285104949
void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104286
- void (*xFinal)(sqlite3_context*)
104950
+ void (*xFinal)(sqlite3_context*),
104951
+ FuncDestructor *pDestructor
104287104952
){
104288104953
FuncDef *p;
104289104954
int nName;
104290104955
104291104956
assert( sqlite3_mutex_held(db->mutex) );
@@ -104309,14 +104974,14 @@
104309104974
if( enc==SQLITE_UTF16 ){
104310104975
enc = SQLITE_UTF16NATIVE;
104311104976
}else if( enc==SQLITE_ANY ){
104312104977
int rc;
104313104978
rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
104314
- pUserData, xFunc, xStep, xFinal);
104979
+ pUserData, xFunc, xStep, xFinal, pDestructor);
104315104980
if( rc==SQLITE_OK ){
104316104981
rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
104317
- pUserData, xFunc, xStep, xFinal);
104982
+ pUserData, xFunc, xStep, xFinal, pDestructor);
104318104983
}
104319104984
if( rc!=SQLITE_OK ){
104320104985
return rc;
104321104986
}
104322104987
enc = SQLITE_UTF16BE;
@@ -104345,10 +105010,19 @@
104345105010
p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
104346105011
assert(p || db->mallocFailed);
104347105012
if( !p ){
104348105013
return SQLITE_NOMEM;
104349105014
}
105015
+
105016
+ /* If an older version of the function with a configured destructor is
105017
+ ** being replaced invoke the destructor function here. */
105018
+ functionDestroy(db, p);
105019
+
105020
+ if( pDestructor ){
105021
+ pDestructor->nRef++;
105022
+ }
105023
+ p->pDestructor = pDestructor;
104350105024
p->flags = 0;
104351105025
p->xFunc = xFunc;
104352105026
p->xStep = xStep;
104353105027
p->xFinalize = xFinal;
104354105028
p->pUserData = pUserData;
@@ -104359,21 +105033,53 @@
104359105033
/*
104360105034
** Create new user functions.
104361105035
*/
104362105036
SQLITE_API int sqlite3_create_function(
104363105037
sqlite3 *db,
104364
- const char *zFunctionName,
105038
+ const char *zFunc,
104365105039
int nArg,
104366105040
int enc,
104367105041
void *p,
104368105042
void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104369105043
void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104370105044
void (*xFinal)(sqlite3_context*)
104371105045
){
104372
- int rc;
105046
+ return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
105047
+ xFinal, 0);
105048
+}
105049
+
105050
+SQLITE_API int sqlite3_create_function_v2(
105051
+ sqlite3 *db,
105052
+ const char *zFunc,
105053
+ int nArg,
105054
+ int enc,
105055
+ void *p,
105056
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105057
+ void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105058
+ void (*xFinal)(sqlite3_context*),
105059
+ void (*xDestroy)(void *)
105060
+){
105061
+ int rc = SQLITE_ERROR;
105062
+ FuncDestructor *pArg = 0;
104373105063
sqlite3_mutex_enter(db->mutex);
104374
- rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
105064
+ if( xDestroy ){
105065
+ pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
105066
+ if( !pArg ){
105067
+ xDestroy(p);
105068
+ goto out;
105069
+ }
105070
+ pArg->xDestroy = xDestroy;
105071
+ pArg->pUserData = p;
105072
+ }
105073
+ rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
105074
+ if( pArg && pArg->nRef==0 ){
105075
+ assert( rc!=SQLITE_OK );
105076
+ xDestroy(p);
105077
+ sqlite3DbFree(db, pArg);
105078
+ }
105079
+
105080
+ out:
104375105081
rc = sqlite3ApiExit(db, rc);
104376105082
sqlite3_mutex_leave(db->mutex);
104377105083
return rc;
104378105084
}
104379105085
@@ -104391,11 +105097,11 @@
104391105097
int rc;
104392105098
char *zFunc8;
104393105099
sqlite3_mutex_enter(db->mutex);
104394105100
assert( !db->mallocFailed );
104395105101
zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
104396
- rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
105102
+ rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
104397105103
sqlite3DbFree(db, zFunc8);
104398105104
rc = sqlite3ApiExit(db, rc);
104399105105
sqlite3_mutex_leave(db->mutex);
104400105106
return rc;
104401105107
}
@@ -104422,11 +105128,11 @@
104422105128
int nName = sqlite3Strlen30(zName);
104423105129
int rc;
104424105130
sqlite3_mutex_enter(db->mutex);
104425105131
if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
104426105132
sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
104427
- 0, sqlite3InvalidFunction, 0, 0);
105133
+ 0, sqlite3InvalidFunction, 0, 0, 0);
104428105134
}
104429105135
rc = sqlite3ApiExit(db, SQLITE_OK);
104430105136
sqlite3_mutex_leave(db->mutex);
104431105137
return rc;
104432105138
}
@@ -104560,11 +105266,14 @@
104560105266
** registered using sqlite3_wal_hook(). Likewise, registering a callback
104561105267
** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
104562105268
** configured by this function.
104563105269
*/
104564105270
SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
104565
-#ifndef SQLITE_OMIT_WAL
105271
+#ifdef SQLITE_OMIT_WAL
105272
+ UNUSED_PARAMETER(db);
105273
+ UNUSED_PARAMETER(nFrame);
105274
+#else
104566105275
if( nFrame>0 ){
104567105276
sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
104568105277
}else{
104569105278
sqlite3_wal_hook(db, 0, 0);
104570105279
}
@@ -104690,64 +105399,10 @@
104690105399
#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
104691105400
return 0;
104692105401
#endif
104693105402
}
104694105403
104695
-/*
104696
-** This routine is called to create a connection to a database BTree
104697
-** driver. If zFilename is the name of a file, then that file is
104698
-** opened and used. If zFilename is the magic name ":memory:" then
104699
-** the database is stored in memory (and is thus forgotten as soon as
104700
-** the connection is closed.) If zFilename is NULL then the database
104701
-** is a "virtual" database for transient use only and is deleted as
104702
-** soon as the connection is closed.
104703
-**
104704
-** A virtual database can be either a disk file (that is automatically
104705
-** deleted when the file is closed) or it an be held entirely in memory.
104706
-** The sqlite3TempInMemory() function is used to determine which.
104707
-*/
104708
-SQLITE_PRIVATE int sqlite3BtreeFactory(
104709
- sqlite3 *db, /* Main database when opening aux otherwise 0 */
104710
- const char *zFilename, /* Name of the file containing the BTree database */
104711
- int omitJournal, /* if TRUE then do not journal this file */
104712
- int nCache, /* How many pages in the page cache */
104713
- int vfsFlags, /* Flags passed through to vfsOpen */
104714
- Btree **ppBtree /* Pointer to new Btree object written here */
104715
-){
104716
- int btFlags = 0;
104717
- int rc;
104718
-
104719
- assert( sqlite3_mutex_held(db->mutex) );
104720
- assert( ppBtree != 0);
104721
- if( omitJournal ){
104722
- btFlags |= BTREE_OMIT_JOURNAL;
104723
- }
104724
- if( db->flags & SQLITE_NoReadlock ){
104725
- btFlags |= BTREE_NO_READLOCK;
104726
- }
104727
-#ifndef SQLITE_OMIT_MEMORYDB
104728
- if( zFilename==0 && sqlite3TempInMemory(db) ){
104729
- zFilename = ":memory:";
104730
- }
104731
-#endif
104732
-
104733
- if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
104734
- vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
104735
- }
104736
- rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
104737
-
104738
- /* If the B-Tree was successfully opened, set the pager-cache size to the
104739
- ** default value. Except, if the call to BtreeOpen() returned a handle
104740
- ** open on an existing shared pager-cache, do not change the pager-cache
104741
- ** size.
104742
- */
104743
- if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
104744
- sqlite3BtreeSetCacheSize(*ppBtree, nCache);
104745
- }
104746
- return rc;
104747
-}
104748
-
104749105404
/*
104750105405
** Return UTF-8 encoded English language explanation of the most recent
104751105406
** error.
104752105407
*/
104753105408
SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
@@ -104986,21 +105641,43 @@
104986105641
** It merely prevents new constructs that exceed the limit
104987105642
** from forming.
104988105643
*/
104989105644
SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
104990105645
int oldLimit;
105646
+
105647
+
105648
+ /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
105649
+ ** there is a hard upper bound set at compile-time by a C preprocessor
105650
+ ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
105651
+ ** "_MAX_".)
105652
+ */
105653
+ assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
105654
+ assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
105655
+ assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
105656
+ assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
105657
+ assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
105658
+ assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
105659
+ assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
105660
+ assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
105661
+ assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
105662
+ SQLITE_MAX_LIKE_PATTERN_LENGTH );
105663
+ assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
105664
+ assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
105665
+ assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
105666
+
105667
+
104991105668
if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
104992105669
return -1;
104993105670
}
104994105671
oldLimit = db->aLimit[limitId];
104995
- if( newLimit>=0 ){
105672
+ if( newLimit>=0 ){ /* IMP: R-52476-28732 */
104996105673
if( newLimit>aHardLimit[limitId] ){
104997
- newLimit = aHardLimit[limitId];
105674
+ newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
104998105675
}
104999105676
db->aLimit[limitId] = newLimit;
105000105677
}
105001
- return oldLimit;
105678
+ return oldLimit; /* IMP: R-53341-35419 */
105002105679
}
105003105680
105004105681
/*
105005105682
** This routine does the work of opening a database on behalf of
105006105683
** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
@@ -105019,10 +105696,28 @@
105019105696
*ppDb = 0;
105020105697
#ifndef SQLITE_OMIT_AUTOINIT
105021105698
rc = sqlite3_initialize();
105022105699
if( rc ) return rc;
105023105700
#endif
105701
+
105702
+ /* Only allow sensible combinations of bits in the flags argument.
105703
+ ** Throw an error if any non-sense combination is used. If we
105704
+ ** do not block illegal combinations here, it could trigger
105705
+ ** assert() statements in deeper layers. Sensible combinations
105706
+ ** are:
105707
+ **
105708
+ ** 1: SQLITE_OPEN_READONLY
105709
+ ** 2: SQLITE_OPEN_READWRITE
105710
+ ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
105711
+ */
105712
+ assert( SQLITE_OPEN_READONLY == 0x01 );
105713
+ assert( SQLITE_OPEN_READWRITE == 0x02 );
105714
+ assert( SQLITE_OPEN_CREATE == 0x04 );
105715
+ testcase( (1<<(flags&7))==0x02 ); /* READONLY */
105716
+ testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
105717
+ testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
105718
+ if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
105024105719
105025105720
if( sqlite3GlobalConfig.bCoreMutex==0 ){
105026105721
isThreadsafe = 0;
105027105722
}else if( flags & SQLITE_OPEN_NOMUTEX ){
105028105723
isThreadsafe = 0;
@@ -105053,11 +105748,12 @@
105053105748
SQLITE_OPEN_MAIN_JOURNAL |
105054105749
SQLITE_OPEN_TEMP_JOURNAL |
105055105750
SQLITE_OPEN_SUBJOURNAL |
105056105751
SQLITE_OPEN_MASTER_JOURNAL |
105057105752
SQLITE_OPEN_NOMUTEX |
105058
- SQLITE_OPEN_FULLMUTEX
105753
+ SQLITE_OPEN_FULLMUTEX |
105754
+ SQLITE_OPEN_WAL
105059105755
);
105060105756
105061105757
/* Allocate the sqlite data structure */
105062105758
db = sqlite3MallocZero( sizeof(sqlite3) );
105063105759
if( db==0 ) goto opendb_out;
@@ -105125,13 +105821,12 @@
105125105821
createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
105126105822
nocaseCollatingFunc, 0);
105127105823
105128105824
/* Open the backend database driver */
105129105825
db->openFlags = flags;
105130
- rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
105131
- flags | SQLITE_OPEN_MAIN_DB,
105132
- &db->aDb[0].pBt);
105826
+ rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
105827
+ flags | SQLITE_OPEN_MAIN_DB);
105133105828
if( rc!=SQLITE_OK ){
105134105829
if( rc==SQLITE_IOERR_NOMEM ){
105135105830
rc = SQLITE_NOMEM;
105136105831
}
105137105832
sqlite3Error(db, rc, 0);
@@ -105833,10 +106528,26 @@
105833106528
*/
105834106529
case SQLITE_TESTCTRL_PGHDRSZ: {
105835106530
rc = sizeof(PgHdr);
105836106531
break;
105837106532
}
106533
+
106534
+ /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
106535
+ **
106536
+ ** Pass pFree into sqlite3ScratchFree().
106537
+ ** If sz>0 then allocate a scratch buffer into pNew.
106538
+ */
106539
+ case SQLITE_TESTCTRL_SCRATCHMALLOC: {
106540
+ void *pFree, **ppNew;
106541
+ int sz;
106542
+ sz = va_arg(ap, int);
106543
+ ppNew = va_arg(ap, void**);
106544
+ pFree = va_arg(ap, void*);
106545
+ if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
106546
+ sqlite3ScratchFree(pFree);
106547
+ break;
106548
+ }
105838106549
105839106550
}
105840106551
va_end(ap);
105841106552
#endif /* SQLITE_OMIT_BUILTIN_TEST */
105842106553
return rc;
@@ -107022,10 +107733,11 @@
107022107733
);
107023107734
SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
107024107735
SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
107025107736
SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
107026107737
SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
107738
+SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
107027107739
107028107740
/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
107029107741
#define FTS3_SEGMENT_REQUIRE_POS 0x00000001
107030107742
#define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
107031107743
#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
@@ -108971,10 +109683,13 @@
108971109683
zQuery);
108972109684
}
108973109685
return rc;
108974109686
}
108975109687
109688
+ rc = sqlite3Fts3ReadLock(p);
109689
+ if( rc!=SQLITE_OK ) return rc;
109690
+
108976109691
rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
108977109692
pCsr->pNextId = pCsr->aDoclist;
108978109693
pCsr->iPrevId = 0;
108979109694
}
108980109695
@@ -109349,15 +110064,18 @@
109349110064
static int fts3RenameMethod(
109350110065
sqlite3_vtab *pVtab, /* Virtual table handle */
109351110066
const char *zName /* New name of table */
109352110067
){
109353110068
Fts3Table *p = (Fts3Table *)pVtab;
109354
- sqlite3 *db; /* Database connection */
110069
+ sqlite3 *db = p->db; /* Database connection */
109355110070
int rc; /* Return Code */
109356
-
109357
- db = p->db;
109358
- rc = SQLITE_OK;
110071
+
110072
+ rc = sqlite3Fts3PendingTermsFlush(p);
110073
+ if( rc!=SQLITE_OK ){
110074
+ return rc;
110075
+ }
110076
+
109359110077
fts3DbExec(&rc, db,
109360110078
"ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
109361110079
p->zDb, p->zName, zName
109362110080
);
109363110081
if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
@@ -112512,10 +113230,40 @@
112512113230
return SQLITE_CORRUPT;
112513113231
}
112514113232
}
112515113233
return SQLITE_OK;
112516113234
}
113235
+
113236
+/*
113237
+** This function ensures that the caller has obtained a shared-cache
113238
+** table-lock on the %_content table. This is required before reading
113239
+** data from the fts3 table. If this lock is not acquired first, then
113240
+** the caller may end up holding read-locks on the %_segments and %_segdir
113241
+** tables, but no read-lock on the %_content table. If this happens
113242
+** a second connection will be able to write to the fts3 table, but
113243
+** attempting to commit those writes might return SQLITE_LOCKED or
113244
+** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
113245
+** write-locks on the %_segments and %_segdir ** tables).
113246
+**
113247
+** We try to avoid this because if FTS3 returns any error when committing
113248
+** a transaction, the whole transaction will be rolled back. And this is
113249
+** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
113250
+** still happen if the user reads data directly from the %_segments or
113251
+** %_segdir tables instead of going through FTS3 though.
113252
+*/
113253
+SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
113254
+ int rc; /* Return code */
113255
+ sqlite3_stmt *pStmt; /* Statement used to obtain lock */
113256
+
113257
+ rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
113258
+ if( rc==SQLITE_OK ){
113259
+ sqlite3_bind_null(pStmt, 1);
113260
+ sqlite3_step(pStmt);
113261
+ rc = sqlite3_reset(pStmt);
113262
+ }
113263
+ return rc;
113264
+}
112517113265
112518113266
/*
112519113267
** Set *ppStmt to a statement handle that may be used to iterate through
112520113268
** all rows in the %_segdir table, from oldest to newest. If successful,
112521113269
** return SQLITE_OK. If an error occurs while preparing the statement,
@@ -116003,10 +116751,49 @@
116003116751
**
116004116752
*************************************************************************
116005116753
** This file contains code for implementations of the r-tree and r*-tree
116006116754
** algorithms packaged as an SQLite virtual table module.
116007116755
*/
116756
+
116757
+/*
116758
+** Database Format of R-Tree Tables
116759
+** --------------------------------
116760
+**
116761
+** The data structure for a single virtual r-tree table is stored in three
116762
+** native SQLite tables declared as follows. In each case, the '%' character
116763
+** in the table name is replaced with the user-supplied name of the r-tree
116764
+** table.
116765
+**
116766
+** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
116767
+** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
116768
+** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
116769
+**
116770
+** The data for each node of the r-tree structure is stored in the %_node
116771
+** table. For each node that is not the root node of the r-tree, there is
116772
+** an entry in the %_parent table associating the node with its parent.
116773
+** And for each row of data in the table, there is an entry in the %_rowid
116774
+** table that maps from the entries rowid to the id of the node that it
116775
+** is stored on.
116776
+**
116777
+** The root node of an r-tree always exists, even if the r-tree table is
116778
+** empty. The nodeno of the root node is always 1. All other nodes in the
116779
+** table must be the same size as the root node. The content of each node
116780
+** is formatted as follows:
116781
+**
116782
+** 1. If the node is the root node (node 1), then the first 2 bytes
116783
+** of the node contain the tree depth as a big-endian integer.
116784
+** For non-root nodes, the first 2 bytes are left unused.
116785
+**
116786
+** 2. The next 2 bytes contain the number of entries currently
116787
+** stored in the node.
116788
+**
116789
+** 3. The remainder of the node contains the node entries. Each entry
116790
+** consists of a single 8-byte integer followed by an even number
116791
+** of 4-byte coordinates. For leaf nodes the integer is the rowid
116792
+** of a record. For internal nodes it is the node number of a
116793
+** child page.
116794
+*/
116008116795
116009116796
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
116010116797
116011116798
/*
116012116799
** This file contains an implementation of a couple of different variants
@@ -116044,18 +116831,22 @@
116044116831
#endif
116045116832
#if VARIANT_RSTARTREE_SPLIT
116046116833
#define AssignCells splitNodeStartree
116047116834
#endif
116048116835
116836
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116837
+# define NDEBUG 1
116838
+#endif
116049116839
116050116840
#ifndef SQLITE_CORE
116051116841
SQLITE_EXTENSION_INIT1
116052116842
#else
116053116843
#endif
116054116844
116055116845
116056116846
#ifndef SQLITE_AMALGAMATION
116847
+#include "sqlite3rtree.h"
116057116848
typedef sqlite3_int64 i64;
116058116849
typedef unsigned char u8;
116059116850
typedef unsigned int u32;
116060116851
#endif
116061116852
@@ -116062,10 +116853,12 @@
116062116853
typedef struct Rtree Rtree;
116063116854
typedef struct RtreeCursor RtreeCursor;
116064116855
typedef struct RtreeNode RtreeNode;
116065116856
typedef struct RtreeCell RtreeCell;
116066116857
typedef struct RtreeConstraint RtreeConstraint;
116858
+typedef struct RtreeMatchArg RtreeMatchArg;
116859
+typedef struct RtreeGeomCallback RtreeGeomCallback;
116067116860
typedef union RtreeCoord RtreeCoord;
116068116861
116069116862
/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
116070116863
#define RTREE_MAX_DIMENSIONS 5
116071116864
@@ -116131,10 +116924,19 @@
116131116924
*/
116132116925
#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
116133116926
#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
116134116927
#define RTREE_MAXCELLS 51
116135116928
116929
+/*
116930
+** The smallest possible node-size is (512-64)==448 bytes. And the largest
116931
+** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
116932
+** Therefore all non-root nodes must contain at least 3 entries. Since
116933
+** 2^40 is greater than 2^64, an r-tree structure always has a depth of
116934
+** 40 or less.
116935
+*/
116936
+#define RTREE_MAX_DEPTH 40
116937
+
116136116938
/*
116137116939
** An rtree cursor object.
116138116940
*/
116139116941
struct RtreeCursor {
116140116942
sqlite3_vtab_cursor base;
@@ -116163,39 +116965,27 @@
116163116965
116164116966
/*
116165116967
** A search constraint.
116166116968
*/
116167116969
struct RtreeConstraint {
116168
- int iCoord; /* Index of constrained coordinate */
116169
- int op; /* Constraining operation */
116170
- double rValue; /* Constraint value. */
116970
+ int iCoord; /* Index of constrained coordinate */
116971
+ int op; /* Constraining operation */
116972
+ double rValue; /* Constraint value. */
116973
+ int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
116974
+ sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
116171116975
};
116172116976
116173116977
/* Possible values for RtreeConstraint.op */
116174
-#define RTREE_EQ 0x41
116175
-#define RTREE_LE 0x42
116176
-#define RTREE_LT 0x43
116177
-#define RTREE_GE 0x44
116178
-#define RTREE_GT 0x45
116978
+#define RTREE_EQ 0x41
116979
+#define RTREE_LE 0x42
116980
+#define RTREE_LT 0x43
116981
+#define RTREE_GE 0x44
116982
+#define RTREE_GT 0x45
116983
+#define RTREE_MATCH 0x46
116179116984
116180116985
/*
116181116986
** An rtree structure node.
116182
-**
116183
-** Data format (RtreeNode.zData):
116184
-**
116185
-** 1. If the node is the root node (node 1), then the first 2 bytes
116186
-** of the node contain the tree depth as a big-endian integer.
116187
-** For non-root nodes, the first 2 bytes are left unused.
116188
-**
116189
-** 2. The next 2 bytes contain the number of entries currently
116190
-** stored in the node.
116191
-**
116192
-** 3. The remainder of the node contains the node entries. Each entry
116193
-** consists of a single 8-byte integer followed by an even number
116194
-** of 4-byte coordinates. For leaf nodes the integer is the rowid
116195
-** of a record. For internal nodes it is the node number of a
116196
-** child page.
116197116987
*/
116198116988
struct RtreeNode {
116199116989
RtreeNode *pParent; /* Parent node */
116200116990
i64 iNode;
116201116991
int nRef;
@@ -116211,10 +117001,44 @@
116211117001
struct RtreeCell {
116212117002
i64 iRowid;
116213117003
RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
116214117004
};
116215117005
117006
+
117007
+/*
117008
+** Value for the first field of every RtreeMatchArg object. The MATCH
117009
+** operator tests that the first field of a blob operand matches this
117010
+** value to avoid operating on invalid blobs (which could cause a segfault).
117011
+*/
117012
+#define RTREE_GEOMETRY_MAGIC 0x891245AB
117013
+
117014
+/*
117015
+** An instance of this structure must be supplied as a blob argument to
117016
+** the right-hand-side of an SQL MATCH operator used to constrain an
117017
+** r-tree query.
117018
+*/
117019
+struct RtreeMatchArg {
117020
+ u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
117021
+ int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
117022
+ void *pContext;
117023
+ int nParam;
117024
+ double aParam[1];
117025
+};
117026
+
117027
+/*
117028
+** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
117029
+** a single instance of the following structure is allocated. It is used
117030
+** as the context for the user-function created by by s_r_g_c(). The object
117031
+** is eventually deleted by the destructor mechanism provided by
117032
+** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
117033
+** the geometry callback function).
117034
+*/
117035
+struct RtreeGeomCallback {
117036
+ int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
117037
+ void *pContext;
117038
+};
117039
+
116216117040
#ifndef MAX
116217117041
# define MAX(x,y) ((x) < (y) ? (y) : (x))
116218117042
#endif
116219117043
#ifndef MIN
116220117044
# define MIN(x,y) ((x) > (y) ? (y) : (x))
@@ -116293,14 +117117,12 @@
116293117117
116294117118
/*
116295117119
** Clear the content of node p (set all bytes to 0x00).
116296117120
*/
116297117121
static void nodeZero(Rtree *pRtree, RtreeNode *p){
116298
- if( p ){
116299
- memset(&p->zData[2], 0, pRtree->iNodeSize-2);
116300
- p->isDirty = 1;
116301
- }
117122
+ memset(&p->zData[2], 0, pRtree->iNodeSize-2);
117123
+ p->isDirty = 1;
116302117124
}
116303117125
116304117126
/*
116305117127
** Given a node number iNode, return the corresponding key to use
116306117128
** in the Rtree.aHash table.
@@ -116316,26 +117138,23 @@
116316117138
** Search the node hash table for node iNode. If found, return a pointer
116317117139
** to it. Otherwise, return 0.
116318117140
*/
116319117141
static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
116320117142
RtreeNode *p;
116321
- assert( iNode!=0 );
116322117143
for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
116323117144
return p;
116324117145
}
116325117146
116326117147
/*
116327117148
** Add node pNode to the node hash table.
116328117149
*/
116329117150
static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
116330
- if( pNode ){
116331
- int iHash;
116332
- assert( pNode->pNext==0 );
116333
- iHash = nodeHash(pNode->iNode);
116334
- pNode->pNext = pRtree->aHash[iHash];
116335
- pRtree->aHash[iHash] = pNode;
116336
- }
117151
+ int iHash;
117152
+ assert( pNode->pNext==0 );
117153
+ iHash = nodeHash(pNode->iNode);
117154
+ pNode->pNext = pRtree->aHash[iHash];
117155
+ pRtree->aHash[iHash] = pNode;
116337117156
}
116338117157
116339117158
/*
116340117159
** Remove node pNode from the node hash table.
116341117160
*/
@@ -116353,15 +117172,15 @@
116353117172
** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
116354117173
** indicating that node has not yet been assigned a node number. It is
116355117174
** assigned a node number when nodeWrite() is called to write the
116356117175
** node contents out to the database.
116357117176
*/
116358
-static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
117177
+static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
116359117178
RtreeNode *pNode;
116360117179
pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116361117180
if( pNode ){
116362
- memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
117181
+ memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
116363117182
pNode->zData = (u8 *)&pNode[1];
116364117183
pNode->nRef = 1;
116365117184
pNode->pParent = pParent;
116366117185
pNode->isDirty = 1;
116367117186
nodeReference(pParent);
@@ -116378,10 +117197,11 @@
116378117197
i64 iNode, /* Node number to load */
116379117198
RtreeNode *pParent, /* Either the parent node or NULL */
116380117199
RtreeNode **ppNode /* OUT: Acquired node */
116381117200
){
116382117201
int rc;
117202
+ int rc2 = SQLITE_OK;
116383117203
RtreeNode *pNode;
116384117204
116385117205
/* Check if the requested node is already in the hash table. If so,
116386117206
** increase its reference count and return it.
116387117207
*/
@@ -116394,43 +117214,67 @@
116394117214
pNode->nRef++;
116395117215
*ppNode = pNode;
116396117216
return SQLITE_OK;
116397117217
}
116398117218
116399
- pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116400
- if( !pNode ){
116401
- *ppNode = 0;
116402
- return SQLITE_NOMEM;
116403
- }
116404
- pNode->pParent = pParent;
116405
- pNode->zData = (u8 *)&pNode[1];
116406
- pNode->nRef = 1;
116407
- pNode->iNode = iNode;
116408
- pNode->isDirty = 0;
116409
- pNode->pNext = 0;
116410
-
116411117219
sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
116412117220
rc = sqlite3_step(pRtree->pReadNode);
116413117221
if( rc==SQLITE_ROW ){
116414117222
const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
116415
- assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
116416
- memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
116417
- nodeReference(pParent);
117223
+ if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
117224
+ pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
117225
+ if( !pNode ){
117226
+ rc2 = SQLITE_NOMEM;
117227
+ }else{
117228
+ pNode->pParent = pParent;
117229
+ pNode->zData = (u8 *)&pNode[1];
117230
+ pNode->nRef = 1;
117231
+ pNode->iNode = iNode;
117232
+ pNode->isDirty = 0;
117233
+ pNode->pNext = 0;
117234
+ memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
117235
+ nodeReference(pParent);
117236
+ }
117237
+ }
117238
+ }
117239
+ rc = sqlite3_reset(pRtree->pReadNode);
117240
+ if( rc==SQLITE_OK ) rc = rc2;
117241
+
117242
+ /* If the root node was just loaded, set pRtree->iDepth to the height
117243
+ ** of the r-tree structure. A height of zero means all data is stored on
117244
+ ** the root node. A height of one means the children of the root node
117245
+ ** are the leaves, and so on. If the depth as specified on the root node
117246
+ ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
117247
+ */
117248
+ if( pNode && iNode==1 ){
117249
+ pRtree->iDepth = readInt16(pNode->zData);
117250
+ if( pRtree->iDepth>RTREE_MAX_DEPTH ){
117251
+ rc = SQLITE_CORRUPT;
117252
+ }
117253
+ }
117254
+
117255
+ /* If no error has occurred so far, check if the "number of entries"
117256
+ ** field on the node is too large. If so, set the return code to
117257
+ ** SQLITE_CORRUPT.
117258
+ */
117259
+ if( pNode && rc==SQLITE_OK ){
117260
+ if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
117261
+ rc = SQLITE_CORRUPT;
117262
+ }
117263
+ }
117264
+
117265
+ if( rc==SQLITE_OK ){
117266
+ if( pNode!=0 ){
117267
+ nodeHashInsert(pRtree, pNode);
117268
+ }else{
117269
+ rc = SQLITE_CORRUPT;
117270
+ }
117271
+ *ppNode = pNode;
116418117272
}else{
116419117273
sqlite3_free(pNode);
116420
- pNode = 0;
116421
- }
116422
-
116423
- *ppNode = pNode;
116424
- rc = sqlite3_reset(pRtree->pReadNode);
116425
-
116426
- if( rc==SQLITE_OK && iNode==1 ){
116427
- pRtree->iDepth = readInt16(pNode->zData);
116428
- }
116429
-
116430
- assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
116431
- nodeHashInsert(pRtree, pNode);
117274
+ *ppNode = 0;
117275
+ }
116432117276
116433117277
return rc;
116434117278
}
116435117279
116436117280
/*
@@ -116479,12 +117323,11 @@
116479117323
int nMaxCell; /* Maximum number of cells for pNode */
116480117324
116481117325
nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
116482117326
nCell = NCELL(pNode);
116483117327
116484
- assert(nCell<=nMaxCell);
116485
-
117328
+ assert( nCell<=nMaxCell );
116486117329
if( nCell<nMaxCell ){
116487117330
nodeOverwriteCell(pRtree, pNode, pCell, nCell);
116488117331
writeInt16(&pNode->zData[2], nCell+1);
116489117332
pNode->isDirty = 1;
116490117333
}
@@ -116700,18 +117543,37 @@
116700117543
*ppCursor = (sqlite3_vtab_cursor *)pCsr;
116701117544
116702117545
return rc;
116703117546
}
116704117547
117548
+
117549
+/*
117550
+** Free the RtreeCursor.aConstraint[] array and its contents.
117551
+*/
117552
+static void freeCursorConstraints(RtreeCursor *pCsr){
117553
+ if( pCsr->aConstraint ){
117554
+ int i; /* Used to iterate through constraint array */
117555
+ for(i=0; i<pCsr->nConstraint; i++){
117556
+ sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
117557
+ if( pGeom ){
117558
+ if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
117559
+ sqlite3_free(pGeom);
117560
+ }
117561
+ }
117562
+ sqlite3_free(pCsr->aConstraint);
117563
+ pCsr->aConstraint = 0;
117564
+ }
117565
+}
117566
+
116705117567
/*
116706117568
** Rtree virtual table module xClose method.
116707117569
*/
116708117570
static int rtreeClose(sqlite3_vtab_cursor *cur){
116709117571
Rtree *pRtree = (Rtree *)(cur->pVtab);
116710117572
int rc;
116711117573
RtreeCursor *pCsr = (RtreeCursor *)cur;
116712
- sqlite3_free(pCsr->aConstraint);
117574
+ freeCursorConstraints(pCsr);
116713117575
rc = nodeRelease(pRtree, pCsr->pNode);
116714117576
sqlite3_free(pCsr);
116715117577
return rc;
116716117578
}
116717117579
@@ -116723,18 +117585,44 @@
116723117585
*/
116724117586
static int rtreeEof(sqlite3_vtab_cursor *cur){
116725117587
RtreeCursor *pCsr = (RtreeCursor *)cur;
116726117588
return (pCsr->pNode==0);
116727117589
}
117590
+
117591
+/*
117592
+** The r-tree constraint passed as the second argument to this function is
117593
+** guaranteed to be a MATCH constraint.
117594
+*/
117595
+static int testRtreeGeom(
117596
+ Rtree *pRtree, /* R-Tree object */
117597
+ RtreeConstraint *pConstraint, /* MATCH constraint to test */
117598
+ RtreeCell *pCell, /* Cell to test */
117599
+ int *pbRes /* OUT: Test result */
117600
+){
117601
+ int i;
117602
+ double aCoord[RTREE_MAX_DIMENSIONS*2];
117603
+ int nCoord = pRtree->nDim*2;
117604
+
117605
+ assert( pConstraint->op==RTREE_MATCH );
117606
+ assert( pConstraint->pGeom );
117607
+
117608
+ for(i=0; i<nCoord; i++){
117609
+ aCoord[i] = DCOORD(pCell->aCoord[i]);
117610
+ }
117611
+ return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
117612
+}
116728117613
116729117614
/*
116730117615
** Cursor pCursor currently points to a cell in a non-leaf page.
116731
-** Return true if the sub-tree headed by the cell is filtered
117616
+** Set *pbEof to true if the sub-tree headed by the cell is filtered
116732117617
** (excluded) by the constraints in the pCursor->aConstraint[]
116733117618
** array, or false otherwise.
117619
+**
117620
+** Return SQLITE_OK if successful or an SQLite error code if an error
117621
+** occurs within a geometry callback.
116734117622
*/
116735
-static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
117623
+static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
116736117624
RtreeCell cell;
116737117625
int ii;
116738117626
int bRes = 0;
116739117627
116740117628
nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
@@ -116742,56 +117630,92 @@
116742117630
RtreeConstraint *p = &pCursor->aConstraint[ii];
116743117631
double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
116744117632
double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
116745117633
116746117634
assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116747
- || p->op==RTREE_GT || p->op==RTREE_EQ
117635
+ || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
116748117636
);
116749117637
116750117638
switch( p->op ){
116751
- case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
116752
- case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
116753
- case RTREE_EQ:
117639
+ case RTREE_LE: case RTREE_LT:
117640
+ bRes = p->rValue<cell_min;
117641
+ break;
117642
+
117643
+ case RTREE_GE: case RTREE_GT:
117644
+ bRes = p->rValue>cell_max;
117645
+ break;
117646
+
117647
+ case RTREE_EQ:
116754117648
bRes = (p->rValue>cell_max || p->rValue<cell_min);
116755117649
break;
117650
+
117651
+ default: {
117652
+ int rc;
117653
+ assert( p->op==RTREE_MATCH );
117654
+ rc = testRtreeGeom(pRtree, p, &cell, &bRes);
117655
+ if( rc!=SQLITE_OK ){
117656
+ return rc;
117657
+ }
117658
+ bRes = !bRes;
117659
+ break;
117660
+ }
116756117661
}
116757117662
}
116758117663
116759
- return bRes;
117664
+ *pbEof = bRes;
117665
+ return SQLITE_OK;
116760117666
}
116761117667
116762117668
/*
116763
-** Return true if the cell that cursor pCursor currently points to
117669
+** Test if the cell that cursor pCursor currently points to
116764117670
** would be filtered (excluded) by the constraints in the
116765
-** pCursor->aConstraint[] array, or false otherwise.
117671
+** pCursor->aConstraint[] array. If so, set *pbEof to true before
117672
+** returning. If the cell is not filtered (excluded) by the constraints,
117673
+** set pbEof to zero.
117674
+**
117675
+** Return SQLITE_OK if successful or an SQLite error code if an error
117676
+** occurs within a geometry callback.
116766117677
**
116767117678
** This function assumes that the cell is part of a leaf node.
116768117679
*/
116769
-static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
117680
+static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
116770117681
RtreeCell cell;
116771117682
int ii;
117683
+ *pbEof = 0;
116772117684
116773117685
nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
116774117686
for(ii=0; ii<pCursor->nConstraint; ii++){
116775117687
RtreeConstraint *p = &pCursor->aConstraint[ii];
116776117688
double coord = DCOORD(cell.aCoord[p->iCoord]);
116777117689
int res;
116778117690
assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116779
- || p->op==RTREE_GT || p->op==RTREE_EQ
117691
+ || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
116780117692
);
116781117693
switch( p->op ){
116782117694
case RTREE_LE: res = (coord<=p->rValue); break;
116783117695
case RTREE_LT: res = (coord<p->rValue); break;
116784117696
case RTREE_GE: res = (coord>=p->rValue); break;
116785117697
case RTREE_GT: res = (coord>p->rValue); break;
116786117698
case RTREE_EQ: res = (coord==p->rValue); break;
117699
+ default: {
117700
+ int rc;
117701
+ assert( p->op==RTREE_MATCH );
117702
+ rc = testRtreeGeom(pRtree, p, &cell, &res);
117703
+ if( rc!=SQLITE_OK ){
117704
+ return rc;
117705
+ }
117706
+ break;
117707
+ }
116787117708
}
116788117709
116789
- if( !res ) return 1;
117710
+ if( !res ){
117711
+ *pbEof = 1;
117712
+ return SQLITE_OK;
117713
+ }
116790117714
}
116791117715
116792
- return 0;
117716
+ return SQLITE_OK;
116793117717
}
116794117718
116795117719
/*
116796117720
** Cursor pCursor currently points at a node that heads a sub-tree of
116797117721
** height iHeight (if iHeight==0, then the node is a leaf). Descend
@@ -116814,17 +117738,17 @@
116814117738
int iSavedCell = pCursor->iCell;
116815117739
116816117740
assert( iHeight>=0 );
116817117741
116818117742
if( iHeight==0 ){
116819
- isEof = testRtreeEntry(pRtree, pCursor);
117743
+ rc = testRtreeEntry(pRtree, pCursor, &isEof);
116820117744
}else{
116821
- isEof = testRtreeCell(pRtree, pCursor);
117745
+ rc = testRtreeCell(pRtree, pCursor, &isEof);
116822117746
}
116823
- if( isEof || iHeight==0 ){
117747
+ if( rc!=SQLITE_OK || isEof || iHeight==0 ){
116824117748
*pEof = isEof;
116825
- return SQLITE_OK;
117749
+ return rc;
116826117750
}
116827117751
116828117752
iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
116829117753
rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
116830117754
if( rc!=SQLITE_OK ){
@@ -116856,45 +117780,59 @@
116856117780
116857117781
/*
116858117782
** One of the cells in node pNode is guaranteed to have a 64-bit
116859117783
** integer value equal to iRowid. Return the index of this cell.
116860117784
*/
116861
-static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
117785
+static int nodeRowidIndex(
117786
+ Rtree *pRtree,
117787
+ RtreeNode *pNode,
117788
+ i64 iRowid,
117789
+ int *piIndex
117790
+){
116862117791
int ii;
116863
- for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
116864
- assert( ii<(NCELL(pNode)-1) );
117792
+ int nCell = NCELL(pNode);
117793
+ for(ii=0; ii<nCell; ii++){
117794
+ if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
117795
+ *piIndex = ii;
117796
+ return SQLITE_OK;
117797
+ }
116865117798
}
116866
- return ii;
117799
+ return SQLITE_CORRUPT;
116867117800
}
116868117801
116869117802
/*
116870117803
** Return the index of the cell containing a pointer to node pNode
116871117804
** in its parent. If pNode is the root node, return -1.
116872117805
*/
116873
-static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
117806
+static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
116874117807
RtreeNode *pParent = pNode->pParent;
116875117808
if( pParent ){
116876
- return nodeRowidIndex(pRtree, pParent, pNode->iNode);
117809
+ return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
116877117810
}
116878
- return -1;
117811
+ *piIndex = -1;
117812
+ return SQLITE_OK;
116879117813
}
116880117814
116881117815
/*
116882117816
** Rtree virtual table module xNext method.
116883117817
*/
116884117818
static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
116885117819
Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
116886117820
RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116887117821
int rc = SQLITE_OK;
117822
+
117823
+ /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
117824
+ ** already at EOF. It is against the rules to call the xNext() method of
117825
+ ** a cursor that has already reached EOF.
117826
+ */
117827
+ assert( pCsr->pNode );
116888117828
116889117829
if( pCsr->iStrategy==1 ){
116890117830
/* This "scan" is a direct lookup by rowid. There is no next entry. */
116891117831
nodeRelease(pRtree, pCsr->pNode);
116892117832
pCsr->pNode = 0;
116893
- }
116894
-
116895
- else if( pCsr->pNode ){
117833
+ }else{
116896117834
/* Move to the next entry that matches the configured constraints. */
116897117835
int iHeight = 0;
116898117836
while( pCsr->pNode ){
116899117837
RtreeNode *pNode = pCsr->pNode;
116900117838
int nCell = NCELL(pNode);
@@ -116904,11 +117842,14 @@
116904117842
if( rc!=SQLITE_OK || !isEof ){
116905117843
return rc;
116906117844
}
116907117845
}
116908117846
pCsr->pNode = pNode->pParent;
116909
- pCsr->iCell = nodeParentIndex(pRtree, pNode);
117847
+ rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
117848
+ if( rc!=SQLITE_OK ){
117849
+ return rc;
117850
+ }
116910117851
nodeReference(pCsr->pNode);
116911117852
nodeRelease(pRtree, pNode);
116912117853
iHeight++;
116913117854
}
116914117855
}
@@ -116972,10 +117913,55 @@
116972117913
rc = sqlite3_reset(pRtree->pReadRowid);
116973117914
}
116974117915
return rc;
116975117916
}
116976117917
117918
+/*
117919
+** This function is called to configure the RtreeConstraint object passed
117920
+** as the second argument for a MATCH constraint. The value passed as the
117921
+** first argument to this function is the right-hand operand to the MATCH
117922
+** operator.
117923
+*/
117924
+static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
117925
+ RtreeMatchArg *p;
117926
+ sqlite3_rtree_geometry *pGeom;
117927
+ int nBlob;
117928
+
117929
+ /* Check that value is actually a blob. */
117930
+ if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
117931
+
117932
+ /* Check that the blob is roughly the right size. */
117933
+ nBlob = sqlite3_value_bytes(pValue);
117934
+ if( nBlob<sizeof(RtreeMatchArg)
117935
+ || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
117936
+ ){
117937
+ return SQLITE_ERROR;
117938
+ }
117939
+
117940
+ pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
117941
+ sizeof(sqlite3_rtree_geometry) + nBlob
117942
+ );
117943
+ if( !pGeom ) return SQLITE_NOMEM;
117944
+ memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
117945
+ p = (RtreeMatchArg *)&pGeom[1];
117946
+
117947
+ memcpy(p, sqlite3_value_blob(pValue), nBlob);
117948
+ if( p->magic!=RTREE_GEOMETRY_MAGIC
117949
+ || nBlob!=(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
117950
+ ){
117951
+ sqlite3_free(pGeom);
117952
+ return SQLITE_ERROR;
117953
+ }
117954
+
117955
+ pGeom->pContext = p->pContext;
117956
+ pGeom->nParam = p->nParam;
117957
+ pGeom->aParam = p->aParam;
117958
+
117959
+ pCons->xGeom = p->xGeom;
117960
+ pCons->pGeom = pGeom;
117961
+ return SQLITE_OK;
117962
+}
116977117963
116978117964
/*
116979117965
** Rtree virtual table module xFilter method.
116980117966
*/
116981117967
static int rtreeFilter(
@@ -116990,22 +117976,22 @@
116990117976
int ii;
116991117977
int rc = SQLITE_OK;
116992117978
116993117979
rtreeReference(pRtree);
116994117980
116995
- sqlite3_free(pCsr->aConstraint);
116996
- pCsr->aConstraint = 0;
117981
+ freeCursorConstraints(pCsr);
116997117982
pCsr->iStrategy = idxNum;
116998117983
116999117984
if( idxNum==1 ){
117000117985
/* Special case - lookup by rowid. */
117001117986
RtreeNode *pLeaf; /* Leaf on which the required cell resides */
117002117987
i64 iRowid = sqlite3_value_int64(argv[0]);
117003117988
rc = findLeafNode(pRtree, iRowid, &pLeaf);
117004117989
pCsr->pNode = pLeaf;
117005
- if( pLeaf && rc==SQLITE_OK ){
117006
- pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
117990
+ if( pLeaf ){
117991
+ assert( rc==SQLITE_OK );
117992
+ rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
117007117993
}
117008117994
}else{
117009117995
/* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
117010117996
** with the configured constraints.
117011117997
*/
@@ -117013,16 +117999,28 @@
117013117999
pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
117014118000
pCsr->nConstraint = argc;
117015118001
if( !pCsr->aConstraint ){
117016118002
rc = SQLITE_NOMEM;
117017118003
}else{
118004
+ memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
117018118005
assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
117019118006
for(ii=0; ii<argc; ii++){
117020118007
RtreeConstraint *p = &pCsr->aConstraint[ii];
117021118008
p->op = idxStr[ii*2];
117022118009
p->iCoord = idxStr[ii*2+1]-'a';
117023
- p->rValue = sqlite3_value_double(argv[ii]);
118010
+ if( p->op==RTREE_MATCH ){
118011
+ /* A MATCH operator. The right-hand-side must be a blob that
118012
+ ** can be cast into an RtreeMatchArg object. One created using
118013
+ ** an sqlite3_rtree_geometry_callback() SQL user function.
118014
+ */
118015
+ rc = deserializeGeometry(argv[ii], p);
118016
+ if( rc!=SQLITE_OK ){
118017
+ break;
118018
+ }
118019
+ }else{
118020
+ p->rValue = sqlite3_value_double(argv[ii]);
118021
+ }
117024118022
}
117025118023
}
117026118024
}
117027118025
117028118026
if( rc==SQLITE_OK ){
@@ -117078,10 +118076,11 @@
117078118076
** = 0x41 ('A')
117079118077
** <= 0x42 ('B')
117080118078
** < 0x43 ('C')
117081118079
** >= 0x44 ('D')
117082118080
** > 0x45 ('E')
118081
+** MATCH 0x46 ('F')
117083118082
** ----------------------
117084118083
**
117085118084
** The second of each pair of bytes identifies the coordinate column
117086118085
** to which the constraint applies. The leftmost coordinate column
117087118086
** is 'a', the second from the left 'b' etc.
@@ -117116,43 +118115,47 @@
117116118115
*/
117117118116
pIdxInfo->estimatedCost = 10.0;
117118118117
return SQLITE_OK;
117119118118
}
117120118119
117121
- if( p->usable && p->iColumn>0 ){
118120
+ if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
118121
+ int j, opmsk;
118122
+ static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
117122118123
u8 op = 0;
117123118124
switch( p->op ){
117124118125
case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
117125118126
case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
117126118127
case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
117127118128
case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
117128118129
case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
117129
- }
117130
- if( op ){
117131
- /* Make sure this particular constraint has not been used before.
117132
- ** If it has been used before, ignore it.
117133
- **
117134
- ** A <= or < can be used if there is a prior >= or >.
117135
- ** A >= or > can be used if there is a prior < or <=.
117136
- ** A <= or < is disqualified if there is a prior <=, <, or ==.
117137
- ** A >= or > is disqualified if there is a prior >=, >, or ==.
117138
- ** A == is disqualifed if there is any prior constraint.
117139
- */
117140
- int j, opmsk;
117141
- static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
117142
- assert( compatible[RTREE_EQ & 7]==0 );
117143
- assert( compatible[RTREE_LT & 7]==1 );
117144
- assert( compatible[RTREE_LE & 7]==1 );
117145
- assert( compatible[RTREE_GT & 7]==2 );
117146
- assert( compatible[RTREE_GE & 7]==2 );
117147
- cCol = p->iColumn - 1 + 'a';
117148
- opmsk = compatible[op & 7];
117149
- for(j=0; j<iIdx; j+=2){
117150
- if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
117151
- op = 0;
117152
- break;
117153
- }
118130
+ default:
118131
+ assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
118132
+ op = RTREE_MATCH;
118133
+ break;
118134
+ }
118135
+ assert( op!=0 );
118136
+
118137
+ /* Make sure this particular constraint has not been used before.
118138
+ ** If it has been used before, ignore it.
118139
+ **
118140
+ ** A <= or < can be used if there is a prior >= or >.
118141
+ ** A >= or > can be used if there is a prior < or <=.
118142
+ ** A <= or < is disqualified if there is a prior <=, <, or ==.
118143
+ ** A >= or > is disqualified if there is a prior >=, >, or ==.
118144
+ ** A == is disqualifed if there is any prior constraint.
118145
+ */
118146
+ assert( compatible[RTREE_EQ & 7]==0 );
118147
+ assert( compatible[RTREE_LT & 7]==1 );
118148
+ assert( compatible[RTREE_LE & 7]==1 );
118149
+ assert( compatible[RTREE_GT & 7]==2 );
118150
+ assert( compatible[RTREE_GE & 7]==2 );
118151
+ cCol = p->iColumn - 1 + 'a';
118152
+ opmsk = compatible[op & 7];
118153
+ for(j=0; j<iIdx; j+=2){
118154
+ if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
118155
+ op = 0;
118156
+ break;
117154118157
}
117155118158
}
117156118159
if( op ){
117157118160
assert( iIdx<sizeof(zIdxStr)-1 );
117158118161
zIdxStr[iIdx++] = op;
@@ -117256,11 +118259,16 @@
117256118259
int iExclude
117257118260
){
117258118261
int ii;
117259118262
float overlap = 0.0;
117260118263
for(ii=0; ii<nCell; ii++){
117261
- if( ii!=iExclude ){
118264
+#if VARIANT_RSTARTREE_CHOOSESUBTREE
118265
+ if( ii!=iExclude )
118266
+#else
118267
+ assert( iExclude==-1 );
118268
+#endif
118269
+ {
117262118270
int jj;
117263118271
float o = 1.0;
117264118272
for(jj=0; jj<(pRtree->nDim*2); jj+=2){
117265118273
double x1;
117266118274
double x2;
@@ -117349,26 +118357,35 @@
117349118357
/* Select the child node which will be enlarged the least if pCell
117350118358
** is inserted into it. Resolve ties by choosing the entry with
117351118359
** the smallest area.
117352118360
*/
117353118361
for(iCell=0; iCell<nCell; iCell++){
118362
+ int bBest = 0;
117354118363
float growth;
117355118364
float area;
117356118365
float overlap = 0.0;
117357118366
nodeGetCell(pRtree, pNode, iCell, &cell);
117358118367
growth = cellGrowth(pRtree, &cell, pCell);
117359118368
area = cellArea(pRtree, &cell);
118369
+
117360118370
#if VARIANT_RSTARTREE_CHOOSESUBTREE
117361118371
if( ii==(pRtree->iDepth-1) ){
117362118372
overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
117363118373
}
117364
-#endif
117365118374
if( (iCell==0)
117366118375
|| (overlap<fMinOverlap)
117367118376
|| (overlap==fMinOverlap && growth<fMinGrowth)
117368118377
|| (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
117369118378
){
118379
+ bBest = 1;
118380
+ }
118381
+#else
118382
+ if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
118383
+ bBest = 1;
118384
+ }
118385
+#endif
118386
+ if( bBest ){
117370118387
fMinOverlap = overlap;
117371118388
fMinGrowth = growth;
117372118389
fMinArea = area;
117373118390
iBest = cell.iRowid;
117374118391
}
@@ -117387,29 +118404,34 @@
117387118404
/*
117388118405
** A cell with the same content as pCell has just been inserted into
117389118406
** the node pNode. This function updates the bounding box cells in
117390118407
** all ancestor elements.
117391118408
*/
117392
-static void AdjustTree(
118409
+static int AdjustTree(
117393118410
Rtree *pRtree, /* Rtree table */
117394118411
RtreeNode *pNode, /* Adjust ancestry of this node. */
117395118412
RtreeCell *pCell /* This cell was just inserted */
117396118413
){
117397118414
RtreeNode *p = pNode;
117398118415
while( p->pParent ){
117399
- RtreeCell cell;
117400118416
RtreeNode *pParent = p->pParent;
117401
- int iCell = nodeParentIndex(pRtree, p);
118417
+ RtreeCell cell;
118418
+ int iCell;
118419
+
118420
+ if( nodeParentIndex(pRtree, p, &iCell) ){
118421
+ return SQLITE_CORRUPT;
118422
+ }
117402118423
117403118424
nodeGetCell(pRtree, pParent, iCell, &cell);
117404118425
if( !cellContains(pRtree, &cell, pCell) ){
117405118426
cellUnion(pRtree, &cell, pCell);
117406118427
nodeOverwriteCell(pRtree, pParent, &cell, iCell);
117407118428
}
117408118429
117409118430
p = pParent;
117410118431
}
118432
+ return SQLITE_OK;
117411118433
}
117412118434
117413118435
/*
117414118436
** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
117415118437
*/
@@ -117934,18 +118956,18 @@
117934118956
nodeZero(pRtree, pNode);
117935118957
memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
117936118958
nCell++;
117937118959
117938118960
if( pNode->iNode==1 ){
117939
- pRight = nodeNew(pRtree, pNode, 1);
117940
- pLeft = nodeNew(pRtree, pNode, 1);
118961
+ pRight = nodeNew(pRtree, pNode);
118962
+ pLeft = nodeNew(pRtree, pNode);
117941118963
pRtree->iDepth++;
117942118964
pNode->isDirty = 1;
117943118965
writeInt16(pNode->zData, pRtree->iDepth);
117944118966
}else{
117945118967
pLeft = pNode;
117946
- pRight = nodeNew(pRtree, pLeft->pParent, 1);
118968
+ pRight = nodeNew(pRtree, pLeft->pParent);
117947118969
nodeReference(pLeft);
117948118970
}
117949118971
117950118972
if( !pLeft || !pRight ){
117951118973
rc = SQLITE_NOMEM;
@@ -117958,12 +118980,16 @@
117958118980
rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
117959118981
if( rc!=SQLITE_OK ){
117960118982
goto splitnode_out;
117961118983
}
117962118984
117963
- /* Ensure both child nodes have node numbers assigned to them. */
117964
- if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
118985
+ /* Ensure both child nodes have node numbers assigned to them by calling
118986
+ ** nodeWrite(). Node pRight always needs a node number, as it was created
118987
+ ** by nodeNew() above. But node pLeft sometimes already has a node number.
118988
+ ** In this case avoid the all to nodeWrite().
118989
+ */
118990
+ if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
117965118991
|| (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
117966118992
){
117967118993
goto splitnode_out;
117968118994
}
117969118995
@@ -117975,13 +119001,19 @@
117975119001
if( rc!=SQLITE_OK ){
117976119002
goto splitnode_out;
117977119003
}
117978119004
}else{
117979119005
RtreeNode *pParent = pLeft->pParent;
117980
- int iCell = nodeParentIndex(pRtree, pLeft);
117981
- nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
117982
- AdjustTree(pRtree, pParent, &leftbbox);
119006
+ int iCell;
119007
+ rc = nodeParentIndex(pRtree, pLeft, &iCell);
119008
+ if( rc==SQLITE_OK ){
119009
+ nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
119010
+ rc = AdjustTree(pRtree, pParent, &leftbbox);
119011
+ }
119012
+ if( rc!=SQLITE_OK ){
119013
+ goto splitnode_out;
119014
+ }
117983119015
}
117984119016
if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
117985119017
goto splitnode_out;
117986119018
}
117987119019
@@ -118021,44 +119053,73 @@
118021119053
nodeRelease(pRtree, pLeft);
118022119054
sqlite3_free(aCell);
118023119055
return rc;
118024119056
}
118025119057
119058
+/*
119059
+** If node pLeaf is not the root of the r-tree and its pParent pointer is
119060
+** still NULL, load all ancestor nodes of pLeaf into memory and populate
119061
+** the pLeaf->pParent chain all the way up to the root node.
119062
+**
119063
+** This operation is required when a row is deleted (or updated - an update
119064
+** is implemented as a delete followed by an insert). SQLite provides the
119065
+** rowid of the row to delete, which can be used to find the leaf on which
119066
+** the entry resides (argument pLeaf). Once the leaf is located, this
119067
+** function is called to determine its ancestry.
119068
+*/
118026119069
static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
118027119070
int rc = SQLITE_OK;
118028
- if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
118029
- sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
118030
- if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
118031
- i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
118032
- rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
118033
- }else{
118034
- rc = SQLITE_ERROR;
118035
- }
118036
- sqlite3_reset(pRtree->pReadParent);
118037
- if( rc==SQLITE_OK ){
118038
- rc = fixLeafParent(pRtree, pLeaf->pParent);
118039
- }
119071
+ RtreeNode *pChild = pLeaf;
119072
+ while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
119073
+ int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
119074
+ sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
119075
+ rc = sqlite3_step(pRtree->pReadParent);
119076
+ if( rc==SQLITE_ROW ){
119077
+ RtreeNode *pTest; /* Used to test for reference loops */
119078
+ i64 iNode; /* Node number of parent node */
119079
+
119080
+ /* Before setting pChild->pParent, test that we are not creating a
119081
+ ** loop of references (as we would if, say, pChild==pParent). We don't
119082
+ ** want to do this as it leads to a memory leak when trying to delete
119083
+ ** the referenced counted node structures.
119084
+ */
119085
+ iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
119086
+ for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
119087
+ if( !pTest ){
119088
+ rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
119089
+ }
119090
+ }
119091
+ rc = sqlite3_reset(pRtree->pReadParent);
119092
+ if( rc==SQLITE_OK ) rc = rc2;
119093
+ if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
119094
+ pChild = pChild->pParent;
118040119095
}
118041119096
return rc;
118042119097
}
118043119098
118044119099
static int deleteCell(Rtree *, RtreeNode *, int, int);
118045119100
118046119101
static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
118047119102
int rc;
119103
+ int rc2;
118048119104
RtreeNode *pParent;
118049119105
int iCell;
118050119106
118051119107
assert( pNode->nRef==1 );
118052119108
118053119109
/* Remove the entry in the parent cell. */
118054
- iCell = nodeParentIndex(pRtree, pNode);
118055
- pParent = pNode->pParent;
118056
- pNode->pParent = 0;
118057
- if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
118058
- || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
118059
- ){
119110
+ rc = nodeParentIndex(pRtree, pNode, &iCell);
119111
+ if( rc==SQLITE_OK ){
119112
+ pParent = pNode->pParent;
119113
+ pNode->pParent = 0;
119114
+ rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
119115
+ }
119116
+ rc2 = nodeRelease(pRtree, pParent);
119117
+ if( rc==SQLITE_OK ){
119118
+ rc = rc2;
119119
+ }
119120
+ if( rc!=SQLITE_OK ){
118060119121
return rc;
118061119122
}
118062119123
118063119124
/* Remove the xxx_node entry. */
118064119125
sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
@@ -118084,12 +119145,13 @@
118084119145
pRtree->pDeleted = pNode;
118085119146
118086119147
return SQLITE_OK;
118087119148
}
118088119149
118089
-static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
119150
+static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
118090119151
RtreeNode *pParent = pNode->pParent;
119152
+ int rc = SQLITE_OK;
118091119153
if( pParent ){
118092119154
int ii;
118093119155
int nCell = NCELL(pNode);
118094119156
RtreeCell box; /* Bounding box for pNode */
118095119157
nodeGetCell(pRtree, pNode, 0, &box);
@@ -118097,21 +119159,25 @@
118097119159
RtreeCell cell;
118098119160
nodeGetCell(pRtree, pNode, ii, &cell);
118099119161
cellUnion(pRtree, &box, &cell);
118100119162
}
118101119163
box.iRowid = pNode->iNode;
118102
- ii = nodeParentIndex(pRtree, pNode);
118103
- nodeOverwriteCell(pRtree, pParent, &box, ii);
118104
- fixBoundingBox(pRtree, pParent);
119164
+ rc = nodeParentIndex(pRtree, pNode, &ii);
119165
+ if( rc==SQLITE_OK ){
119166
+ nodeOverwriteCell(pRtree, pParent, &box, ii);
119167
+ rc = fixBoundingBox(pRtree, pParent);
119168
+ }
118105119169
}
119170
+ return rc;
118106119171
}
118107119172
118108119173
/*
118109119174
** Delete the cell at index iCell of node pNode. After removing the
118110119175
** cell, adjust the r-tree data structure if required.
118111119176
*/
118112119177
static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
119178
+ RtreeNode *pParent;
118113119179
int rc;
118114119180
118115119181
if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
118116119182
return rc;
118117119183
}
@@ -118124,18 +119190,17 @@
118124119190
/* If the node is not the tree root and now has less than the minimum
118125119191
** number of cells, remove it from the tree. Otherwise, update the
118126119192
** cell in the parent node so that it tightly contains the updated
118127119193
** node.
118128119194
*/
118129
- if( pNode->iNode!=1 ){
118130
- RtreeNode *pParent = pNode->pParent;
118131
- if( (pParent->iNode!=1 || NCELL(pParent)!=1)
118132
- && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
118133
- ){
119195
+ pParent = pNode->pParent;
119196
+ assert( pParent || pNode->iNode==1 );
119197
+ if( pParent ){
119198
+ if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
118134119199
rc = removeNode(pRtree, pNode, iHeight);
118135119200
}else{
118136
- fixBoundingBox(pRtree, pNode);
119201
+ rc = fixBoundingBox(pRtree, pNode);
118137119202
}
118138119203
}
118139119204
118140119205
return rc;
118141119206
}
@@ -118214,11 +119279,11 @@
118214119279
rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
118215119280
}
118216119281
}
118217119282
}
118218119283
if( rc==SQLITE_OK ){
118219
- fixBoundingBox(pRtree, pNode);
119284
+ rc = fixBoundingBox(pRtree, pNode);
118220119285
}
118221119286
for(; rc==SQLITE_OK && ii<nCell; ii++){
118222119287
/* Find a node to store this cell in. pNode->iNode currently contains
118223119288
** the height of the sub-tree headed by the cell.
118224119289
*/
@@ -118268,15 +119333,17 @@
118268119333
}
118269119334
#else
118270119335
rc = SplitNode(pRtree, pNode, pCell, iHeight);
118271119336
#endif
118272119337
}else{
118273
- AdjustTree(pRtree, pNode, pCell);
118274
- if( iHeight==0 ){
118275
- rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
118276
- }else{
118277
- rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
119338
+ rc = AdjustTree(pRtree, pNode, pCell);
119339
+ if( rc==SQLITE_OK ){
119340
+ if( iHeight==0 ){
119341
+ rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
119342
+ }else{
119343
+ rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
119344
+ }
118278119345
}
118279119346
}
118280119347
return rc;
118281119348
}
118282119349
@@ -118342,11 +119409,10 @@
118342119409
int rc = SQLITE_OK;
118343119410
118344119411
rtreeReference(pRtree);
118345119412
118346119413
assert(nData>=1);
118347
- assert(hashIsEmpty(pRtree));
118348119414
118349119415
/* If azData[0] is not an SQL NULL value, it is the rowid of a
118350119416
** record to delete from the r-tree table. The following block does
118351119417
** just that.
118352119418
*/
@@ -118368,12 +119434,14 @@
118368119434
}
118369119435
118370119436
/* Delete the cell in question from the leaf node. */
118371119437
if( rc==SQLITE_OK ){
118372119438
int rc2;
118373
- iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
118374
- rc = deleteCell(pRtree, pLeaf, iCell, 0);
119439
+ rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
119440
+ if( rc==SQLITE_OK ){
119441
+ rc = deleteCell(pRtree, pLeaf, iCell, 0);
119442
+ }
118375119443
rc2 = nodeRelease(pRtree, pLeaf);
118376119444
if( rc==SQLITE_OK ){
118377119445
rc = rc2;
118378119446
}
118379119447
}
@@ -118391,23 +119459,24 @@
118391119459
**
118392119460
** This is equivalent to copying the contents of the child into
118393119461
** the root node (the operation that Gutman's paper says to perform
118394119462
** in this scenario).
118395119463
*/
118396
- if( rc==SQLITE_OK && pRtree->iDepth>0 ){
118397
- if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
118398
- RtreeNode *pChild;
118399
- i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
118400
- rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
118401
- if( rc==SQLITE_OK ){
118402
- rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
118403
- }
118404
- if( rc==SQLITE_OK ){
118405
- pRtree->iDepth--;
118406
- writeInt16(pRoot->zData, pRtree->iDepth);
118407
- pRoot->isDirty = 1;
118408
- }
119464
+ if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
119465
+ int rc2;
119466
+ RtreeNode *pChild;
119467
+ i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
119468
+ rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
119469
+ if( rc==SQLITE_OK ){
119470
+ rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
119471
+ }
119472
+ rc2 = nodeRelease(pRtree, pChild);
119473
+ if( rc==SQLITE_OK ) rc = rc2;
119474
+ if( rc==SQLITE_OK ){
119475
+ pRtree->iDepth--;
119476
+ writeInt16(pRoot->zData, pRtree->iDepth);
119477
+ pRoot->isDirty = 1;
118409119478
}
118410119479
}
118411119480
118412119481
/* Re-insert the contents of any underfull nodes removed from the tree. */
118413119482
for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
@@ -118693,11 +119762,11 @@
118693119762
){
118694119763
int rc = SQLITE_OK;
118695119764
Rtree *pRtree;
118696119765
int nDb; /* Length of string argv[1] */
118697119766
int nName; /* Length of string argv[2] */
118698
- int eCoordType = (int)pAux;
119767
+ int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
118699119768
118700119769
const char *aErrMsg[] = {
118701119770
0, /* 0 */
118702119771
"Wrong number of columns for an rtree table", /* 1 */
118703119772
"Too few columns for an rtree table", /* 2 */
@@ -118839,16 +119908,14 @@
118839119908
** Register the r-tree module with database handle db. This creates the
118840119909
** virtual table module "rtree" and the debugging/analysis scalar
118841119910
** function "rtreenode".
118842119911
*/
118843119912
SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
118844
- int rc = SQLITE_OK;
119913
+ const int utf8 = SQLITE_UTF8;
119914
+ int rc;
118845119915
118846
- if( rc==SQLITE_OK ){
118847
- int utf8 = SQLITE_UTF8;
118848
- rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
118849
- }
119916
+ rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
118850119917
if( rc==SQLITE_OK ){
118851119918
int utf8 = SQLITE_UTF8;
118852119919
rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
118853119920
}
118854119921
if( rc==SQLITE_OK ){
@@ -118860,10 +119927,74 @@
118860119927
rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
118861119928
}
118862119929
118863119930
return rc;
118864119931
}
119932
+
119933
+/*
119934
+** A version of sqlite3_free() that can be used as a callback. This is used
119935
+** in two places - as the destructor for the blob value returned by the
119936
+** invocation of a geometry function, and as the destructor for the geometry
119937
+** functions themselves.
119938
+*/
119939
+static void doSqlite3Free(void *p){
119940
+ sqlite3_free(p);
119941
+}
119942
+
119943
+/*
119944
+** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
119945
+** scalar user function. This C function is the callback used for all such
119946
+** registered SQL functions.
119947
+**
119948
+** The scalar user functions return a blob that is interpreted by r-tree
119949
+** table MATCH operators.
119950
+*/
119951
+static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
119952
+ RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
119953
+ RtreeMatchArg *pBlob;
119954
+ int nBlob;
119955
+
119956
+ nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
119957
+ pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
119958
+ if( !pBlob ){
119959
+ sqlite3_result_error_nomem(ctx);
119960
+ }else{
119961
+ int i;
119962
+ pBlob->magic = RTREE_GEOMETRY_MAGIC;
119963
+ pBlob->xGeom = pGeomCtx->xGeom;
119964
+ pBlob->pContext = pGeomCtx->pContext;
119965
+ pBlob->nParam = nArg;
119966
+ for(i=0; i<nArg; i++){
119967
+ pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
119968
+ }
119969
+ sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
119970
+ }
119971
+}
119972
+
119973
+/*
119974
+** Register a new geometry function for use with the r-tree MATCH operator.
119975
+*/
119976
+SQLITE_API int sqlite3_rtree_geometry_callback(
119977
+ sqlite3 *db,
119978
+ const char *zGeom,
119979
+ int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
119980
+ void *pContext
119981
+){
119982
+ RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
119983
+
119984
+ /* Allocate and populate the context object. */
119985
+ pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
119986
+ if( !pGeomCtx ) return SQLITE_NOMEM;
119987
+ pGeomCtx->xGeom = xGeom;
119988
+ pGeomCtx->pContext = pContext;
119989
+
119990
+ /* Create the new user-function. Register a destructor function to delete
119991
+ ** the context object when it is no longer required. */
119992
+ return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
119993
+ (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
119994
+ );
119995
+}
118865119996
118866119997
#if !SQLITE_CORE
118867119998
SQLITE_API int sqlite3_extension_init(
118868119999
sqlite3 *db,
118869120000
char **pzErrMsg,
118870120001
--- 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.7.2. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a one 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% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
@@ -352,19 +352,25 @@
352 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X) ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
 
 
 
 
 
 
358 ** Older versions of SQLite used an optional THREADSAFE macro.
359 ** We support that for legacy
360 */
361 #if !defined(SQLITE_THREADSAFE)
362 #if defined(THREADSAFE)
363 # define SQLITE_THREADSAFE THREADSAFE
364 #else
365 # define SQLITE_THREADSAFE 1
366 #endif
367 #endif
368
369 /*
370 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
@@ -642,13 +648,13 @@
642 **
643 ** See also: [sqlite3_libversion()],
644 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
645 ** [sqlite_version()] and [sqlite_source_id()].
646 */
647 #define SQLITE_VERSION "3.7.2"
648 #define SQLITE_VERSION_NUMBER 3007002
649 #define SQLITE_SOURCE_ID "2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3"
650
651 /*
652 ** CAPI3REF: Run-Time Library Version Numbers
653 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
654 **
@@ -1292,19 +1298,23 @@
1292 ** object once the object has been registered.
1293 **
1294 ** The zName field holds the name of the VFS module. The name must
1295 ** be unique across all VFS modules.
1296 **
1297 ** SQLite will guarantee that the zFilename parameter to xOpen
1298 ** is either a NULL pointer or string obtained
1299 ** from xFullPathname(). SQLite further guarantees that
 
 
 
 
1300 ** the string will be valid and unchanged until xClose() is
1301 ** called. Because of the previous sentence,
1302 ** the [sqlite3_file] can safely store a pointer to the
1303 ** filename if it needs to remember the filename for some reason.
1304 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1305 ** must invent its own temporary name for the file. Whenever the
1306 ** xFilename parameter is NULL it will also be the case that the
1307 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1308 **
1309 ** The flags argument to xOpen() includes all bits set in
1310 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -1311,11 +1321,11 @@
1311 ** or [sqlite3_open16()] is used, then flags includes at least
1312 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1313 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1314 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1315 **
1316 ** SQLite will also add one of the following flags to the xOpen()
1317 ** call, depending on the object being opened:
1318 **
1319 ** <ul>
1320 ** <li> [SQLITE_OPEN_MAIN_DB]
1321 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -1322,11 +1332,12 @@
1322 ** <li> [SQLITE_OPEN_TEMP_DB]
1323 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1324 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1325 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1326 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1327 ** </ul>
 
1328 **
1329 ** The file I/O implementation can use the object type flags to
1330 ** change the way it deals with files. For example, an application
1331 ** that does not care about crash recovery or rollback might make
1332 ** the open of a journal file a no-op. Writes to this journal would
@@ -1341,39 +1352,40 @@
1341 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1342 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1343 ** </ul>
1344 **
1345 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1346 ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
1347 ** will be set for TEMP databases, journals and for subjournals.
 
1348 **
1349 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1350 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1351 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1352 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1353 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1354 ** be created, and that it is an error if it already exists.
1355 ** It is <i>not</i> used to indicate the file should be opened
1356 ** for exclusive access.
1357 **
1358 ** At least szOsFile bytes of memory are allocated by SQLite
1359 ** to hold the [sqlite3_file] structure passed as the third
1360 ** argument to xOpen. The xOpen method does not have to
1361 ** allocate the structure; it should just fill it in. Note that
1362 ** the xOpen method must set the sqlite3_file.pMethods to either
1363 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1364 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1365 ** element will be valid after xOpen returns regardless of the success
1366 ** or failure of the xOpen call.
1367 **
1368 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1369 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1370 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1371 ** to test whether a file is at least readable. The file can be a
1372 ** directory.
1373 **
1374 ** SQLite will always allocate at least mxPathname+1 bytes for the
1375 ** output buffer xFullPathname. The exact size of the output buffer
1376 ** is also passed as a parameter to both methods. If the output buffer
1377 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1378 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1379 ** to prevent this by setting mxPathname to a sufficiently large value.
@@ -1383,14 +1395,14 @@
1383 ** included in the VFS structure for completeness.
1384 ** The xRandomness() function attempts to return nBytes bytes
1385 ** of good-quality randomness into zOut. The return value is
1386 ** the actual number of bytes of randomness obtained.
1387 ** The xSleep() method causes the calling thread to sleep for at
1388 ** least the number of microseconds given. The xCurrentTime()
1389 ** method returns a Julian Day Number for the current date and time as
1390 ** a floating point value.
1391 ** The xCurrentTimeInt64() method returns, as an integer, the Julian
1392 ** Day Number multipled by 86400000 (the number of milliseconds in
1393 ** a 24-hour day).
1394 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1395 ** date and time if that method is available (if iVersion is 2 or
1396 ** greater and the function pointer is not NULL) and will fall back
@@ -1783,11 +1795,11 @@
1783 ** statistics. ^(When memory allocation statistics are disabled, the
1784 ** following SQLite interfaces become non-operational:
1785 ** <ul>
1786 ** <li> [sqlite3_memory_used()]
1787 ** <li> [sqlite3_memory_highwater()]
1788 ** <li> [sqlite3_soft_heap_limit()]
1789 ** <li> [sqlite3_status()]
1790 ** </ul>)^
1791 ** ^Memory allocation statistics are enabled by default unless SQLite is
1792 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1793 ** allocation statistics are disabled by default.
@@ -1797,19 +1809,18 @@
1797 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1798 ** scratch memory. There are three arguments: A pointer an 8-byte
1799 ** aligned memory buffer from which the scrach allocations will be
1800 ** drawn, the size of each scratch allocation (sz),
1801 ** and the maximum number of scratch allocations (N). The sz
1802 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1803 ** larger than the actual scratch space required due to internal overhead.
1804 ** The first argument must be a pointer to an 8-byte aligned buffer
1805 ** of at least sz*N bytes of memory.
1806 ** ^SQLite will use no more than one scratch buffer per thread. So
1807 ** N should be set to the expected maximum number of threads. ^SQLite will
1808 ** never require a scratch buffer that is more than 6 times the database
1809 ** page size. ^If SQLite needs needs additional scratch memory beyond
1810 ** what is provided by this configuration option, then
1811 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1812 **
1813 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1814 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1815 ** the database page cache with the default page cache implemenation.
@@ -1825,12 +1836,11 @@
1825 ** argument should point to an allocation of at least sz*N bytes of memory.
1826 ** ^SQLite will use the memory provided by the first argument to satisfy its
1827 ** memory needs for the first N pages that it adds to cache. ^If additional
1828 ** page cache memory is needed beyond what is provided by this option, then
1829 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1830 ** ^The implementation might use one or more of the N buffers to hold
1831 ** memory accounting information. The pointer in the first argument must
1832 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1833 ** will be undefined.</dd>
1834 **
1835 ** <dt>SQLITE_CONFIG_HEAP</dt>
1836 ** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1955,12 +1965,18 @@
1955 ** size of each lookaside buffer slot. ^The third argument is the number of
1956 ** slots. The size of the buffer in the first argument must be greater than
1957 ** or equal to the product of the second and third arguments. The buffer
1958 ** must be aligned to an 8-byte boundary. ^If the second argument to
1959 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1960 ** rounded down to the next smaller
1961 ** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
 
 
 
 
 
 
1962 **
1963 ** </dl>
1964 */
1965 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1966
@@ -2260,10 +2276,13 @@
2260 */
2261 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2262
2263 /*
2264 ** CAPI3REF: Convenience Routines For Running Queries
 
 
 
2265 **
2266 ** Definition: A <b>result table</b> is memory data structure created by the
2267 ** [sqlite3_get_table()] interface. A result table records the
2268 ** complete query results from one or more queries.
2269 **
@@ -2281,11 +2300,11 @@
2281 **
2282 ** A result table might consist of one or more memory allocations.
2283 ** It is not safe to pass a result table directly to [sqlite3_free()].
2284 ** A result table should be deallocated using [sqlite3_free_table()].
2285 **
2286 ** As an example of the result table format, suppose a query result
2287 ** is as follows:
2288 **
2289 ** <blockquote><pre>
2290 ** Name | Age
2291 ** -----------------------
@@ -2305,31 +2324,31 @@
2305 ** azResult&#91;3] = "43";
2306 ** azResult&#91;4] = "Bob";
2307 ** azResult&#91;5] = "28";
2308 ** azResult&#91;6] = "Cindy";
2309 ** azResult&#91;7] = "21";
2310 ** </pre></blockquote>
2311 **
2312 ** ^The sqlite3_get_table() function evaluates one or more
2313 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2314 ** string of its 2nd parameter and returns a result table to the
2315 ** pointer given in its 3rd parameter.
2316 **
2317 ** After the application has finished with the result from sqlite3_get_table(),
2318 ** it should pass the result table pointer to sqlite3_free_table() in order to
2319 ** release the memory that was malloced. Because of the way the
2320 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2321 ** function must not try to call [sqlite3_free()] directly. Only
2322 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2323 **
2324 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2325 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2326 ** to any internal data structures of SQLite. It uses only the public
2327 ** interface defined here. As a consequence, errors that occur in the
2328 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2329 ** reflected in subsequent calls to [sqlite3_errcode()] or
2330 ** [sqlite3_errmsg()].)^
2331 */
2332 SQLITE_API int sqlite3_get_table(
2333 sqlite3 *db, /* An open database */
2334 const char *zSql, /* SQL to be evaluated */
2335 char ***pazResult, /* Results of the query */
@@ -2477,11 +2496,13 @@
2477 ** by sqlite3_realloc() and the prior allocation is freed.
2478 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2479 ** is not freed.
2480 **
2481 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2482 ** is always aligned to at least an 8 byte boundary.
 
 
2483 **
2484 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2485 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2486 ** implementation of these routines to be omitted. That capability
2487 ** is no longer provided. Only built-in memory allocators can be used.
@@ -2735,21 +2756,32 @@
2735 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2736
2737 /*
2738 ** CAPI3REF: Query Progress Callbacks
2739 **
2740 ** ^This routine configures a callback function - the
2741 ** progress callback - that is invoked periodically during long
2742 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2743 ** [sqlite3_get_table()]. An example use for this
2744 ** interface is to keep a GUI updated during a large query.
 
 
 
 
 
 
 
 
 
 
 
2745 **
2746 ** ^If the progress callback returns non-zero, the operation is
2747 ** interrupted. This feature can be used to implement a
2748 ** "Cancel" button on a GUI progress dialog box.
2749 **
2750 ** The progress handler must not do anything that will modify
2751 ** the database connection that invoked the progress handler.
2752 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2753 ** database connections for the meaning of "modify" in this paragraph.
2754 **
2755 */
@@ -2804,11 +2836,11 @@
2804 ** </dl>
2805 **
2806 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2807 ** combinations shown above or one of the combinations shown above combined
2808 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2809 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2810 ** then the behavior is undefined.
2811 **
2812 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2813 ** opens in the multi-thread [threading mode] as long as the single-thread
2814 ** mode has not been set at compile-time or start-time. ^If the
@@ -2929,21 +2961,26 @@
2929 ** ^(This interface allows the size of various constructs to be limited
2930 ** on a connection by connection basis. The first parameter is the
2931 ** [database connection] whose limit is to be set or queried. The
2932 ** second parameter is one of the [limit categories] that define a
2933 ** class of constructs to be size limited. The third parameter is the
2934 ** new limit for that construct. The function returns the old limit.)^
2935 **
2936 ** ^If the new limit is a negative number, the limit is unchanged.
2937 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2938 ** [limits | hard upper bound]
2939 ** set by a compile-time C preprocessor macro named
2940 ** [limits | SQLITE_MAX_XYZ].
2941 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2942 ** ^Attempts to increase a limit above its hard upper bound are
2943 ** silently truncated to the hard upper bound.
2944 **
 
 
 
 
 
2945 ** Run-time limits are intended for use in applications that manage
2946 ** both their own internal database and also databases that are controlled
2947 ** by untrusted external sources. An example application might be a
2948 ** web browser that has its own databases for storing history and
2949 ** separate databases controlled by JavaScript applications downloaded
@@ -2968,11 +3005,11 @@
2968 ** The synopsis of the meanings of the various limits is shown below.
2969 ** Additional information is available at [limits | Limits in SQLite].
2970 **
2971 ** <dl>
2972 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2973 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2974 **
2975 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2976 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2977 **
2978 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2986,11 +3023,13 @@
2986 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2987 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2988 **
2989 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2990 ** <dd>The maximum number of instructions in a virtual machine program
2991 ** used to implement an SQL statement.</dd>)^
 
 
2992 **
2993 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2994 ** <dd>The maximum number of arguments on a function.</dd>)^
2995 **
2996 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2999,12 +3038,11 @@
2999 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3000 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3001 ** [GLOB] operators.</dd>)^
3002 **
3003 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3004 ** <dd>The maximum number of variables in an SQL statement that can
3005 ** be bound.</dd>)^
3006 **
3007 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3008 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3009 ** </dl>
3010 */
@@ -3072,16 +3110,11 @@
3072 **
3073 ** <ol>
3074 ** <li>
3075 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3076 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3077 ** statement and try to run it again. ^If the schema has changed in
3078 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
3079 ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
3080 ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
3081 ** error go away. Note: use [sqlite3_errmsg()] to find the text
3082 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
3083 ** </li>
3084 **
3085 ** <li>
3086 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3087 ** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -3090,15 +3123,20 @@
3090 ** in order to find the underlying cause of the problem. With the "v2" prepare
3091 ** interfaces, the underlying reason for the error is returned immediately.
3092 ** </li>
3093 **
3094 ** <li>
3095 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
3096 ** change the query plan for a statement, then the statement may be
3097 ** automatically recompiled (as if there had been a schema change) on the first
3098 ** [sqlite3_step()] call following any change to the
3099 ** [sqlite3_bind_text | bindings] of the [parameter].
 
 
 
 
 
3100 ** </li>
3101 ** </ol>
3102 */
3103 SQLITE_API int sqlite3_prepare(
3104 sqlite3 *db, /* Database handle */
@@ -3161,11 +3199,11 @@
3161 ** or if SQLite is run in one of reduced mutex modes
3162 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3163 ** then there is no distinction between protected and unprotected
3164 ** sqlite3_value objects and they can be used interchangeably. However,
3165 ** for maximum code portability it is recommended that applications
3166 ** still make the distinction between between protected and unprotected
3167 ** sqlite3_value objects even when not strictly required.
3168 **
3169 ** ^The sqlite3_value objects that are passed as parameters into the
3170 ** implementation of [application-defined SQL functions] are protected.
3171 ** ^The sqlite3_value object returned by
@@ -3356,10 +3394,12 @@
3356 ** CAPI3REF: Number Of Columns In A Result Set
3357 **
3358 ** ^Return the number of columns in the result set returned by the
3359 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3360 ** statement that does not return data (for example an [UPDATE]).
 
 
3361 */
3362 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3363
3364 /*
3365 ** CAPI3REF: Column Names In A Result Set
@@ -3546,12 +3586,18 @@
3546 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3547
3548 /*
3549 ** CAPI3REF: Number of columns in a result set
3550 **
3551 ** ^The sqlite3_data_count(P) the number of columns in the
3552 ** of the result set of [prepared statement] P.
 
 
 
 
 
 
3553 */
3554 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3555
3556 /*
3557 ** CAPI3REF: Fundamental Datatypes
@@ -3627,22 +3673,30 @@
3627 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3628 ** the string to UTF-8 and then returns the number of bytes.
3629 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3630 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3631 ** the number of bytes in that string.
3632 ** ^The value returned does not include the zero terminator at the end
3633 ** of the string. ^For clarity: the value returned is the number of
 
 
 
 
 
 
 
 
 
 
 
 
 
3634 ** bytes in the string, not the number of characters.
3635 **
3636 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3637 ** even empty strings, are always zero terminated. ^The return
3638 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3639 ** pointer, possibly even a NULL pointer.
3640 **
3641 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3642 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3643 ** ^The zero terminator is not included in this count.
3644 **
3645 ** ^The object returned by [sqlite3_column_value()] is an
3646 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3647 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3648 ** If the [unprotected sqlite3_value] object returned by
@@ -3683,14 +3737,14 @@
3683 ** and atof(). SQLite does not really use these functions. It has its
3684 ** own equivalent internal routines. The atoi() and atof() names are
3685 ** used in the table for brevity and because they are familiar to most
3686 ** C programmers.
3687 **
3688 ** ^Note that when type conversions occur, pointers returned by prior
3689 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3690 ** sqlite3_column_text16() may be invalidated.
3691 ** ^(Type conversions and pointer invalidations might occur
3692 ** in the following cases:
3693 **
3694 ** <ul>
3695 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3696 ** sqlite3_column_text16() is called. A zero-terminator might
@@ -3699,26 +3753,26 @@
3699 ** sqlite3_column_text16() is called. The content must be converted
3700 ** to UTF-16.</li>
3701 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3702 ** sqlite3_column_text() is called. The content must be converted
3703 ** to UTF-8.</li>
3704 ** </ul>)^
3705 **
3706 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3707 ** not invalidate a prior pointer, though of course the content of the buffer
3708 ** that the prior pointer points to will have been modified. Other kinds
3709 ** of conversion are done in place when it is possible, but sometimes they
3710 ** are not possible and in those cases prior pointers are invalidated.
3711 **
3712 ** ^(The safest and easiest to remember policy is to invoke these routines
3713 ** in one of the following ways:
3714 **
3715 ** <ul>
3716 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3717 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3718 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3719 ** </ul>)^
3720 **
3721 ** In other words, you should call sqlite3_column_text(),
3722 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3723 ** into the desired format, then invoke sqlite3_column_bytes() or
3724 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3752,21 +3806,30 @@
3752
3753 /*
3754 ** CAPI3REF: Destroy A Prepared Statement Object
3755 **
3756 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3757 ** ^If the statement was executed successfully or not executed at all, then
3758 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3759 ** [error code] or [extended error code] is returned.
 
 
3760 **
3761 ** ^This routine can be called at any point during the execution of the
3762 ** [prepared statement]. ^If the virtual machine has not
3763 ** completed execution when this routine is called, that is like
3764 ** encountering an error or an [sqlite3_interrupt | interrupt].
3765 ** ^Incomplete updates may be rolled back and transactions canceled,
3766 ** depending on the circumstances, and the
3767 ** [error code] returned will be [SQLITE_ABORT].
 
 
 
 
 
 
 
3768 */
3769 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3770
3771 /*
3772 ** CAPI3REF: Reset A Prepared Statement Object
@@ -3798,40 +3861,42 @@
3798 ** CAPI3REF: Create Or Redefine SQL Functions
3799 ** KEYWORDS: {function creation routines}
3800 ** KEYWORDS: {application-defined SQL function}
3801 ** KEYWORDS: {application-defined SQL functions}
3802 **
3803 ** ^These two functions (collectively known as "function creation routines")
3804 ** are used to add SQL functions or aggregates or to redefine the behavior
3805 ** of existing SQL functions or aggregates. The only difference between the
3806 ** two is that the second parameter, the name of the (scalar) function or
3807 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3808 ** for sqlite3_create_function16().
 
3809 **
3810 ** ^The first parameter is the [database connection] to which the SQL
3811 ** function is to be added. ^If an application uses more than one database
3812 ** connection then application-defined SQL functions must be added
3813 ** to each database connection separately.
3814 **
3815 ** The second parameter is the name of the SQL function to be created or
3816 ** redefined. ^The length of the name is limited to 255 bytes, exclusive of
3817 ** the zero-terminator. Note that the name length limit is in bytes, not
3818 ** characters. ^Any attempt to create a function with a longer name
3819 ** will result in [SQLITE_ERROR] being returned.
 
3820 **
3821 ** ^The third parameter (nArg)
3822 ** is the number of arguments that the SQL function or
3823 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3824 ** aggregate may take any number of arguments between 0 and the limit
3825 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
3826 ** parameter is less than -1 or greater than 127 then the behavior is
3827 ** undefined.
3828 **
3829 ** The fourth parameter, eTextRep, specifies what
3830 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3831 ** its parameters. Any SQL function implementation should be able to work
3832 ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3833 ** more efficient with one encoding than another. ^An application may
3834 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3835 ** times with the same function but with different values of eTextRep.
3836 ** ^When multiple implementations of the same function are available, SQLite
3837 ** will pick the one that involves the least amount of data conversion.
@@ -3839,17 +3904,25 @@
3839 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3840 **
3841 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
3842 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3843 **
3844 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3845 ** pointers to C-language functions that implement the SQL function or
3846 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3847 ** callback only; NULL pointers should be passed as the xStep and xFinal
3848 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3849 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3850 ** SQL function or aggregate, pass NULL for all three function callbacks.
 
 
 
 
 
 
 
 
3851 **
3852 ** ^It is permitted to register multiple implementations of the same
3853 ** functions with the same name but with either differing numbers of
3854 ** arguments or differing preferred text encodings. ^SQLite will use
3855 ** the implementation that most closely matches the way in which the
@@ -3861,15 +3934,10 @@
3861 ** ^A function where the encoding difference is between UTF16le and UTF16be
3862 ** is a closer match than a function where the encoding difference is
3863 ** between UTF8 and UTF16.
3864 **
3865 ** ^Built-in functions may be overloaded by new application-defined functions.
3866 ** ^The first application-defined function with a given name overrides all
3867 ** built-in functions in the same [database connection] with the same name.
3868 ** ^Subsequent application-defined functions of the same name only override
3869 ** prior application-defined functions that are an exact match for the
3870 ** number of parameters and preferred encoding.
3871 **
3872 ** ^An application-defined function is permitted to call other
3873 ** SQLite interfaces. However, such calls must not
3874 ** close the database connection nor finalize or reset the prepared
3875 ** statement in which the function is running.
@@ -3891,10 +3959,21 @@
3891 int eTextRep,
3892 void *pApp,
3893 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3894 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3895 void (*xFinal)(sqlite3_context*)
 
 
 
 
 
 
 
 
 
 
 
3896 );
3897
3898 /*
3899 ** CAPI3REF: Text Encodings
3900 **
@@ -4238,73 +4317,97 @@
4238 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4239
4240 /*
4241 ** CAPI3REF: Define New Collating Sequences
4242 **
4243 ** These functions are used to add new collation sequences to the
4244 ** [database connection] specified as the first argument.
4245 **
4246 ** ^The name of the new collation sequence is specified as a UTF-8 string
4247 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4248 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4249 ** the name is passed as the second function argument.
4250 **
4251 ** ^The third argument may be one of the constants [SQLITE_UTF8],
4252 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4253 ** routine expects to be passed pointers to strings encoded using UTF-8,
4254 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4255 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4256 ** expects pointers to be UTF-16 strings in the native byte order, or the
4257 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4258 ** the routine expects pointers to 16-bit word aligned strings
4259 ** of UTF-16 in the native byte order.
4260 **
4261 ** A pointer to the user supplied routine must be passed as the fifth
4262 ** argument. ^If it is NULL, this is the same as deleting the collation
4263 ** sequence (so that SQLite cannot call it any more).
4264 ** ^Each time the application supplied function is invoked, it is passed
4265 ** as its first parameter a copy of the void* passed as the fourth argument
4266 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4267 **
4268 ** ^The remaining arguments to the application-supplied routine are two strings,
4269 ** each represented by a (length, data) pair and encoded in the encoding
4270 ** that was passed as the third argument when the collation sequence was
4271 ** registered. The application defined collation routine should
4272 ** return negative, zero or positive if the first string is less than,
4273 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4274 **
4275 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4276 ** except that it takes an extra argument which is a destructor for
4277 ** the collation. ^The destructor is called when the collation is
4278 ** destroyed and is passed a copy of the fourth parameter void* pointer
4279 ** of the sqlite3_create_collation_v2().
4280 ** ^Collations are destroyed when they are overridden by later calls to the
4281 ** collation creation functions or when the [database connection] is closed
4282 ** using [sqlite3_close()].
4283 **
4284 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4285 */
4286 SQLITE_API int sqlite3_create_collation(
4287 sqlite3*,
4288 const char *zName,
4289 int eTextRep,
4290 void*,
4291 int(*xCompare)(void*,int,const void*,int,const void*)
4292 );
4293 SQLITE_API int sqlite3_create_collation_v2(
4294 sqlite3*,
4295 const char *zName,
4296 int eTextRep,
4297 void*,
4298 int(*xCompare)(void*,int,const void*,int,const void*),
4299 void(*xDestroy)(void*)
4300 );
4301 SQLITE_API int sqlite3_create_collation16(
4302 sqlite3*,
4303 const void *zName,
4304 int eTextRep,
4305 void*,
4306 int(*xCompare)(void*,int,const void*,int,const void*)
4307 );
4308
4309 /*
4310 ** CAPI3REF: Collation Needed Callbacks
@@ -4389,20 +4492,23 @@
4389 #endif
4390
4391 /*
4392 ** CAPI3REF: Suspend Execution For A Short Time
4393 **
4394 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
4395 ** for at least a number of milliseconds specified in its parameter.
4396 **
4397 ** ^If the operating system does not support sleep requests with
4398 ** millisecond time resolution, then the time will be rounded up to
4399 ** the nearest second. ^The number of milliseconds of sleep actually
4400 ** requested from the operating system is returned.
4401 **
4402 ** ^SQLite implements this interface by calling the xSleep()
4403 ** method of the default [sqlite3_vfs] object.
 
 
 
4404 */
4405 SQLITE_API int sqlite3_sleep(int);
4406
4407 /*
4408 ** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4620,44 +4726,77 @@
4620 ** of heap memory by deallocating non-essential memory allocations
4621 ** held by the database library. Memory used to cache database
4622 ** pages to improve performance is an example of non-essential memory.
4623 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4624 ** which might be more or less than the amount requested.
 
 
4625 */
4626 SQLITE_API int sqlite3_release_memory(int);
4627
4628 /*
4629 ** CAPI3REF: Impose A Limit On Heap Size
4630 **
4631 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4632 ** on the amount of heap memory that may be allocated by SQLite.
4633 ** ^If an internal allocation is requested that would exceed the
4634 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4635 ** more times to free up some space before the allocation is performed.
4636 **
4637 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4638 ** cannot free sufficient memory to prevent the limit from being exceeded,
4639 ** the memory is allocated anyway and the current operation proceeds.
4640 **
4641 ** ^A negative or zero value for N means that there is no soft heap limit and
4642 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4643 ** ^The default value for the soft heap limit is zero.
4644 **
4645 ** ^(SQLite makes a best effort to honor the soft heap limit.
4646 ** But if the soft heap limit cannot be honored, execution will
4647 ** continue without error or notification.)^ This is why the limit is
4648 ** called a "soft" limit. It is advisory only.
4649 **
4650 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4651 ** allocated by a single thread - the same thread in which this routine
4652 ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
4653 ** applied to all threads. The value specified for the soft heap limit
4654 ** is an upper bound on the total memory allocation for all threads. In
4655 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4656 ** individual threads.
4657 */
4658 SQLITE_API void sqlite3_soft_heap_limit(int);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4659
4660 /*
4661 ** CAPI3REF: Extract Metadata About A Column Of A Table
4662 **
4663 ** ^This routine returns metadata about a specific column of a specific
@@ -4777,38 +4916,51 @@
4777 ** it back off again.
4778 */
4779 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4780
4781 /*
4782 ** CAPI3REF: Automatically Load An Extensions
4783 **
4784 ** ^This API can be invoked at program startup in order to register
4785 ** one or more statically linked extensions that will be available
4786 ** to all new [database connections].
4787 **
4788 ** ^(This routine stores a pointer to the extension entry point
4789 ** in an array that is obtained from [sqlite3_malloc()]. That memory
4790 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4791 **
4792 ** ^This function registers an extension entry point that is
4793 ** automatically invoked whenever a new [database connection]
4794 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4795 ** or [sqlite3_open_v2()].
4796 ** ^Duplicate extensions are detected so calling this routine
4797 ** multiple times with the same extension is harmless.
4798 ** ^Automatic extensions apply across all threads.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4799 */
4800 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4801
4802 /*
4803 ** CAPI3REF: Reset Automatic Extension Loading
4804 **
4805 ** ^(This function disables all previously registered automatic
4806 ** extensions. It undoes the effect of all prior
4807 ** [sqlite3_auto_extension()] calls.)^
4808 **
4809 ** ^This function disables automatic extensions in all threads.
4810 */
4811 SQLITE_API void sqlite3_reset_auto_extension(void);
4812
4813 /*
4814 ** The interface to the virtual-table mechanism is currently considered
@@ -5443,11 +5595,11 @@
5443 ** output variable when querying the system for the current mutex
5444 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5445 **
5446 ** ^The xMutexInit method defined by this structure is invoked as
5447 ** part of system initialization by the sqlite3_initialize() function.
5448 ** ^The xMutexInit routine is calle by SQLite exactly once for each
5449 ** effective call to [sqlite3_initialize()].
5450 **
5451 ** ^The xMutexEnd method defined by this structure is invoked as
5452 ** part of system shutdown by the sqlite3_shutdown() function. The
5453 ** implementation of this method is expected to release all outstanding
@@ -5640,11 +5792,12 @@
5640 #define SQLITE_TESTCTRL_ALWAYS 13
5641 #define SQLITE_TESTCTRL_RESERVE 14
5642 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
5643 #define SQLITE_TESTCTRL_ISKEYWORD 16
5644 #define SQLITE_TESTCTRL_PGHDRSZ 17
5645 #define SQLITE_TESTCTRL_LAST 17
 
5646
5647 /*
5648 ** CAPI3REF: SQLite Runtime Status
5649 **
5650 ** ^This interface is used to retrieve runtime status information
@@ -5659,11 +5812,11 @@
5659 ** value. For those parameters
5660 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5661 ** ^(Other parameters record only the highwater mark and not the current
5662 ** value. For these latter parameters nothing is written into *pCurrent.)^
5663 **
5664 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5665 ** non-zero [error code] on failure.
5666 **
5667 ** This routine is threadsafe but is not atomic. This routine can be
5668 ** called while other threads are running the same or different SQLite
5669 ** interfaces. However the values returned in *pCurrent and
@@ -5709,11 +5862,11 @@
5709 ** [SQLITE_CONFIG_PAGECACHE]. The
5710 ** value returned is in pages, not in bytes.</dd>)^
5711 **
5712 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5713 ** <dd>This parameter returns the number of bytes of page cache
5714 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5715 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
5716 ** returned value includes allocations that overflowed because they
5717 ** where too large (they were larger than the "sz" parameter to
5718 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5719 ** no space was left in the page cache.</dd>)^
@@ -5732,11 +5885,11 @@
5732 ** outstanding at time, this parameter also reports the number of threads
5733 ** using scratch memory at the same time.</dd>)^
5734 **
5735 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5736 ** <dd>This parameter returns the number of bytes of scratch memory
5737 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5738 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
5739 ** returned include overflows because the requested allocation was too
5740 ** larger (that is, because the requested allocation was larger than the
5741 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5742 ** slots were available.
@@ -5780,10 +5933,13 @@
5780 **
5781 ** ^The current value of the requested parameter is written into *pCur
5782 ** and the highest instantaneous value is written into *pHiwtr. ^If
5783 ** the resetFlg is true, then the highest instantaneous value is
5784 ** reset back down to the current value.
 
 
 
5785 **
5786 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5787 */
5788 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5789
@@ -5907,122 +6063,134 @@
5907 ** CAPI3REF: Application Defined Page Cache.
5908 ** KEYWORDS: {page cache}
5909 **
5910 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5911 ** register an alternative page cache implementation by passing in an
5912 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5913 ** heap memory used by SQLite is used by the page cache to cache data read
5914 ** from, or ready to be written to, the database file. By implementing a
5915 ** custom page cache using this API, an application can control more
5916 ** precisely the amount of memory consumed by SQLite, the way in which
 
5917 ** that memory is allocated and released, and the policies used to
5918 ** determine exactly which parts of a database file are cached and for
5919 ** how long.
5920 **
 
 
 
 
5921 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5922 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
5923 ** the application may discard the parameter after the call to
5924 ** [sqlite3_config()] returns.)^
5925 **
5926 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
 
5927 ** (usually only once during the lifetime of the process). ^(The xInit()
5928 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5929 ** ^The xInit() method can set up up global structures and/or any mutexes
5930 ** required by the custom page cache implementation.
 
 
 
5931 **
5932 ** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5933 ** if the application invokes this API. It can be used to clean up
5934 ** any outstanding resources before process shutdown, if required.
 
5935 **
5936 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5937 ** the xInit method, so the xInit method need not be threadsafe. ^The
5938 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5939 ** not need to be threadsafe either. All other methods must be threadsafe
5940 ** in multithreaded applications.
5941 **
5942 ** ^SQLite will never invoke xInit() more than once without an intervening
5943 ** call to xShutdown().
5944 **
5945 ** ^The xCreate() method is used to construct a new cache instance. SQLite
5946 ** will typically create one cache instance for each open database file,
5947 ** though this is not guaranteed. ^The
5948 ** first parameter, szPage, is the size in bytes of the pages that must
5949 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
5950 ** will the page size of the database file that is to be cached plus an
5951 ** increment (here called "R") of about 100 or 200. ^SQLite will use the
5952 ** extra R bytes on each page to store metadata about the underlying
5953 ** database page on disk. The value of R depends
5954 ** on the SQLite version, the target platform, and how SQLite was compiled.
5955 ** ^R is constant for a particular build of SQLite. ^The second argument to
5956 ** xCreate(), bPurgeable, is true if the cache being created will
5957 ** be used to cache database pages of a file stored on disk, or
5958 ** false if it is used for an in-memory database. ^The cache implementation
5959 ** does not have to do anything special based with the value of bPurgeable;
5960 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
5961 ** never invoke xUnpin() except to deliberately delete a page.
5962 ** ^In other words, a cache created with bPurgeable set to false will
 
 
5963 ** never contain any unpinned pages.
5964 **
5965 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5966 ** suggested maximum cache-size (number of pages stored by) the cache
5967 ** instance passed as the first argument. This is the value configured using
5968 ** the SQLite "[PRAGMA cache_size]" command.)^ ^As with the bPurgeable
5969 ** parameter, the implementation is not required to do anything with this
5970 ** value; it is advisory only.
5971 **
5972 ** ^The xPagecount() method should return the number of pages currently
5973 ** stored in the cache.
5974 **
5975 ** ^The xFetch() method is used to fetch a page and return a pointer to it.
5976 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5977 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5978 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
 
5979 ** is considered to be "pinned".
5980 **
5981 ** ^If the requested page is already in the page cache, then the page cache
5982 ** implementation must return a pointer to the page buffer with its content
5983 ** intact. ^(If the requested page is not already in the cache, then the
5984 ** behavior of the cache implementation is determined by the value of the
5985 ** createFlag parameter passed to xFetch, according to the following table:
5986 **
5987 ** <table border=1 width=85% align=center>
5988 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5989 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
5990 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5991 ** Otherwise return NULL.
5992 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
5993 ** NULL if allocating a new page is effectively impossible.
5994 ** </table>)^
5995 **
5996 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If
5997 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
 
5998 ** attempt to unpin one or more cache pages by spilling the content of
5999 ** pinned pages to disk and synching the operating system disk cache. After
6000 ** attempting to unpin pages, the xFetch() method will be invoked again with
6001 ** a createFlag of 2.
6002 **
6003 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6004 ** as its second argument. ^(If the third parameter, discard, is non-zero,
6005 ** then the page should be evicted from the cache. In this case SQLite
6006 ** assumes that the next time the page is retrieved from the cache using
6007 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
6008 ** zero, then the page is considered to be unpinned. ^The cache implementation
6009 ** may choose to evict unpinned pages at any time.
6010 **
6011 ** ^(The cache is not required to perform any reference counting. A single
6012 ** call to xUnpin() unpins the page regardless of the number of prior calls
6013 ** to xFetch().)^
6014 **
6015 ** ^The xRekey() method is used to change the key value associated with the
6016 ** page passed as the second argument from oldKey to newKey. ^If the cache
6017 ** previously contains an entry associated with newKey, it should be
6018 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6019 ** to be pinned.
6020 **
6021 ** ^When SQLite calls the xTruncate() method, the cache must discard all
6022 ** existing cache entries with page numbers (keys) greater than or equal
6023 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
6024 ** of these pages are pinned, they are implicitly unpinned, meaning that
6025 ** they can be safely discarded.
6026 **
6027 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6028 ** All resources associated with the specified cache should be freed. ^After
@@ -6496,10 +6664,66 @@
6496 #if 0
6497 } /* End of the 'extern "C"' block */
6498 #endif
6499 #endif
6500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6501
6502 /************** End of sqlite3.h *********************************************/
6503 /************** Continuing where we left off in sqliteInt.h ******************/
6504 /************** Include hash.h in the middle of sqliteInt.h ******************/
6505 /************** Begin file hash.h ********************************************/
@@ -7066,10 +7290,11 @@
7066 typedef struct Schema Schema;
7067 typedef struct Expr Expr;
7068 typedef struct ExprList ExprList;
7069 typedef struct ExprSpan ExprSpan;
7070 typedef struct FKey FKey;
 
7071 typedef struct FuncDef FuncDef;
7072 typedef struct FuncDefHash FuncDefHash;
7073 typedef struct IdList IdList;
7074 typedef struct Index Index;
7075 typedef struct IndexSample IndexSample;
@@ -7172,16 +7397,15 @@
7172 ** following values.
7173 **
7174 ** NOTE: These values must match the corresponding PAGER_ values in
7175 ** pager.h.
7176 */
7177 #define BTREE_OMIT_JOURNAL 1 /* Do not use journal. No argument */
7178 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
7179 #define BTREE_MEMORY 4 /* In-memory DB. No argument */
7180 #define BTREE_READONLY 8 /* Open the database in read-only mode */
7181 #define BTREE_READWRITE 16 /* Open for both reading and writing */
7182 #define BTREE_CREATE 32 /* Create the database if it does not exist */
7183
7184 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7185 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7186 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7187 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
@@ -7213,15 +7437,21 @@
7213 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7214
7215 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7216
7217 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7218 ** of the following flags:
 
 
 
 
 
 
 
7219 */
7220 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
7221 #define BTREE_ZERODATA 2 /* Table has keys only - no data */
7222 #define BTREE_LEAFDATA 4 /* Data stored in leaves only. Implies INTKEY */
7223
7224 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7225 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7226 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7227
@@ -7838,10 +8068,11 @@
7838 **
7839 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7840 */
7841 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
7842 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
 
7843
7844 /*
7845 ** Valid values for the second argument to sqlite3PagerLockingMode().
7846 */
7847 #define PAGER_LOCKINGMODE_QUERY -1
@@ -8472,12 +8703,12 @@
8472 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
8473 #define sqlite3_mutex_free(X)
8474 #define sqlite3_mutex_enter(X)
8475 #define sqlite3_mutex_try(X) SQLITE_OK
8476 #define sqlite3_mutex_leave(X)
8477 #define sqlite3_mutex_held(X) 1
8478 #define sqlite3_mutex_notheld(X) 1
8479 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
8480 #define sqlite3MutexInit() SQLITE_OK
8481 #define sqlite3MutexEnd()
8482 #endif /* defined(SQLITE_MUTEX_OMIT) */
8483
@@ -8795,10 +9026,31 @@
8795 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8796 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8797 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
8798 char *zName; /* SQL name of the function. */
8799 FuncDef *pHash; /* Next with a different name but the same hash */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8800 };
8801
8802 /*
8803 ** Possible values for FuncDef.flags
8804 */
@@ -8835,19 +9087,19 @@
8835 ** FuncDef.flags variable is set to the value passed as the flags
8836 ** parameter.
8837 */
8838 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8839 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8840 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8841 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8842 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8843 pArg, 0, xFunc, 0, 0, #zName, 0}
8844 #define LIKEFUNC(zName, nArg, arg, flags) \
8845 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8846 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8847 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8848 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8849
8850 /*
8851 ** All current savepoints are stored in a linked list starting at
8852 ** sqlite3.pSavepoint. The first element in the list is the most recently
8853 ** opened savepoint. Savepoints are added to the list by the vdbe
@@ -9063,10 +9315,11 @@
9063 int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
9064 int nCol; /* Number of columns in this table */
9065 Column *aCol; /* Information about each column */
9066 Index *pIndex; /* List of SQL indexes on this table. */
9067 int tnum; /* Root BTree node for this table (see note above) */
 
9068 Select *pSelect; /* NULL for tables. Points to definition if a view. */
9069 u16 nRef; /* Number of pointers to this Table */
9070 u8 tabFlags; /* Mask of TF_* values */
9071 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
9072 FKey *pFKey; /* Linked list of all foreign keys in this table */
@@ -10341,11 +10594,11 @@
10341 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10342 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10343 SQLITE_PRIVATE void sqlite3PageFree(void*);
10344 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10345 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10346 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10347
10348 /*
10349 ** On systems with ample stack space and that support alloca(), make
10350 ** use of alloca() to obtain space for large automatic objects. By default,
10351 ** obtain space from malloc().
@@ -10512,11 +10765,10 @@
10512 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10513 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10514 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10515 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10516 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10517 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10518 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10519 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10520 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10521 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10522 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
@@ -10632,12 +10884,10 @@
10632 # define sqlite3AuthContextPush(a,b,c)
10633 # define sqlite3AuthContextPop(a) ((void)(a))
10634 #endif
10635 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10636 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10637 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10638 int omitJournal, int nCache, int flags, Btree **ppBtree);
10639 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10640 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10641 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10642 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10643 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
@@ -10759,11 +11009,13 @@
10759 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10760 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10761 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10762 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10763 void (*)(sqlite3_context*,int,sqlite3_value **),
10764 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
 
 
10765 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10766 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10767
10768 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10769 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
@@ -11679,10 +11931,11 @@
11679 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
11680 Bool nullRow; /* True if pointing to a row with no data */
11681 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
11682 Bool isTable; /* True if a table requiring integer keys */
11683 Bool isIndex; /* True if an index containing keys only - no data */
 
11684 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
11685 Btree *pBt; /* Separate file holding temporary table */
11686 int pseudoTableReg; /* Register holding pseudotable content. */
11687 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
11688 int nField; /* Number of fields in the header */
@@ -11773,10 +12026,14 @@
11773 char *z; /* String or BLOB value */
11774 int n; /* Number of characters in string value, excluding '\0' */
11775 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
11776 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
11777 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
 
 
 
 
11778 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
11779 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
11780 };
11781
11782 /* One or more of the following flags are set to indicate the validOK
@@ -11799,10 +12056,11 @@
11799 #define MEM_Int 0x0004 /* Value is an integer */
11800 #define MEM_Real 0x0008 /* Value is a real number */
11801 #define MEM_Blob 0x0010 /* Value is a BLOB */
11802 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
11803 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
 
11804 #define MEM_TypeMask 0x00ff /* Mask of type bits */
11805
11806 /* Whenever Mem contains a valid string or blob representation, one of
11807 ** the following flags must be set to determine the memory management
11808 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
@@ -11812,23 +12070,29 @@
11812 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
11813 #define MEM_Static 0x0800 /* Mem.z points to a static string */
11814 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
11815 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
11816 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
11817
11818 #ifdef SQLITE_OMIT_INCRBLOB
11819 #undef MEM_Zero
11820 #define MEM_Zero 0x0000
11821 #endif
11822
11823
11824 /*
11825 ** Clear any existing type flags from a Mem and replace them with f
11826 */
11827 #define MemSetTypeFlag(p, f) \
11828 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
11829
 
 
 
 
 
 
 
 
11830
11831 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
11832 ** additional information about auxiliary information bound to arguments
11833 ** of the function. This is used to implement the sqlite3_get_auxdata()
11834 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
@@ -12012,10 +12276,14 @@
12012 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12013 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12014 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12015 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12016 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
 
 
 
 
12017
12018 #ifndef SQLITE_OMIT_FOREIGN_KEY
12019 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12020 #else
12021 # define sqlite3VdbeCheckFk(p,i) 0
@@ -13518,10 +13786,16 @@
13518 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13519 return pVfs->xSleep(pVfs, nMicro);
13520 }
13521 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13522 int rc;
 
 
 
 
 
 
13523 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13524 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13525 }else{
13526 double r;
13527 rc = pVfs->xCurrentTime(pVfs, &r);
@@ -13901,11 +14175,11 @@
13901 ** routines and redirected to xFree.
13902 */
13903 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13904 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13905 assert( pPrior!=0 && nByte>0 );
13906 nByte = ROUND8(nByte);
13907 p--;
13908 p = realloc(p, nByte+8 );
13909 if( p ){
13910 p[0] = nByte;
13911 p++;
@@ -14307,10 +14581,11 @@
14307 */
14308 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14309 struct MemBlockHdr *pOldHdr;
14310 void *pNew;
14311 assert( mem.disallow==0 );
 
14312 pOldHdr = sqlite3MemsysGetHeader(pPrior);
14313 pNew = sqlite3MemMalloc(nByte);
14314 if( pNew ){
14315 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14316 if( nByte>pOldHdr->iSize ){
@@ -15576,11 +15851,11 @@
15576 */
15577 static void *memsys5Realloc(void *pPrior, int nBytes){
15578 int nOld;
15579 void *p;
15580 assert( pPrior!=0 );
15581 assert( (nBytes&(nBytes-1))==0 );
15582 assert( nBytes>=0 );
15583 if( nBytes==0 ){
15584 return 0;
15585 }
15586 nOld = memsys5Size(pPrior);
@@ -17100,10 +17375,70 @@
17100 *************************************************************************
17101 **
17102 ** Memory allocation functions used throughout sqlite.
17103 */
17104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17105 /*
17106 ** This routine runs when the memory allocator sees that the
17107 ** total memory allocation is about to exceed the soft heap
17108 ** limit.
17109 */
@@ -17114,82 +17449,70 @@
17114 ){
17115 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17116 sqlite3_release_memory(allocSize);
17117 }
17118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17119 /*
17120 ** Set the soft heap-size limit for the library. Passing a zero or
17121 ** negative value indicates no limit.
17122 */
17123 SQLITE_API void sqlite3_soft_heap_limit(int n){
17124 sqlite3_uint64 iLimit;
17125 int overage;
17126 if( n<0 ){
17127 iLimit = 0;
17128 }else{
17129 iLimit = n;
17130 }
17131 #ifndef SQLITE_OMIT_AUTOINIT
17132 sqlite3_initialize();
17133 #endif
17134 if( iLimit>0 ){
17135 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
 
 
 
 
17136 }else{
17137 sqlite3MemoryAlarm(0, 0, 0);
17138 }
17139 overage = (int)(sqlite3_memory_used() - (i64)n);
17140 if( overage>0 ){
17141 sqlite3_release_memory(overage);
17142 }
17143 }
17144
17145 /*
17146 ** Attempt to release up to n bytes of non-essential memory currently
17147 ** held by SQLite. An example of non-essential memory is memory used to
17148 ** cache database pages that are not currently in use.
17149 */
17150 SQLITE_API int sqlite3_release_memory(int n){
17151 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17152 int nRet = 0;
17153 nRet += sqlite3PcacheReleaseMemory(n-nRet);
17154 return nRet;
17155 #else
17156 UNUSED_PARAMETER(n);
17157 return SQLITE_OK;
17158 #endif
17159 }
17160
17161 /*
17162 ** State information local to the memory allocation subsystem.
17163 */
17164 static SQLITE_WSD struct Mem0Global {
17165 /* Number of free pages for scratch and page-cache memory */
17166 u32 nScratchFree;
17167 u32 nPageFree;
17168
17169 sqlite3_mutex *mutex; /* Mutex to serialize access */
17170
17171 /*
17172 ** The alarm callback and its arguments. The mem0.mutex lock will
17173 ** be held while the callback is running. Recursive calls into
17174 ** the memory subsystem are allowed, but no new callbacks will be
17175 ** issued.
17176 */
17177 sqlite3_int64 alarmThreshold;
17178 void (*alarmCallback)(void*, sqlite3_int64,int);
17179 void *alarmArg;
17180
17181 /*
17182 ** Pointers to the end of sqlite3GlobalConfig.pScratch and
17183 ** sqlite3GlobalConfig.pPage to a block of memory that records
17184 ** which pages are available.
17185 */
17186 u32 *aScratchFree;
17187 u32 *aPageFree;
17188 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17189
17190 #define mem0 GLOBAL(struct Mem0Global, mem0)
17191
17192 /*
17193 ** Initialize the memory allocation subsystem.
17194 */
17195 SQLITE_PRIVATE int sqlite3MallocInit(void){
@@ -17199,39 +17522,48 @@
17199 memset(&mem0, 0, sizeof(mem0));
17200 if( sqlite3GlobalConfig.bCoreMutex ){
17201 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17202 }
17203 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17204 && sqlite3GlobalConfig.nScratch>=0 ){
17205 int i;
17206 sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
17207 mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
17208 [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
17209 for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
17210 mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
 
 
 
 
 
 
 
 
17211 }else{
 
17212 sqlite3GlobalConfig.pScratch = 0;
17213 sqlite3GlobalConfig.szScratch = 0;
17214 }
17215 if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
17216 && sqlite3GlobalConfig.nPage>=1 ){
17217 int i;
17218 int overhead;
17219 int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
17220 int n = sqlite3GlobalConfig.nPage;
17221 overhead = (4*n + sz - 1)/sz;
17222 sqlite3GlobalConfig.nPage -= overhead;
17223 mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
17224 [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
17225 for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
17226 mem0.nPageFree = sqlite3GlobalConfig.nPage;
17227 }else{
17228 sqlite3GlobalConfig.pPage = 0;
17229 sqlite3GlobalConfig.szPage = 0;
 
17230 }
17231 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17232 }
 
 
 
 
 
 
 
 
 
17233
17234 /*
17235 ** Deinitialize the memory allocation subsystem.
17236 */
17237 SQLITE_PRIVATE void sqlite3MallocEnd(void){
@@ -17263,40 +17595,10 @@
17263 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17264 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
17265 return res;
17266 }
17267
17268 /*
17269 ** Change the alarm callback
17270 */
17271 SQLITE_PRIVATE int sqlite3MemoryAlarm(
17272 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17273 void *pArg,
17274 sqlite3_int64 iThreshold
17275 ){
17276 sqlite3_mutex_enter(mem0.mutex);
17277 mem0.alarmCallback = xCallback;
17278 mem0.alarmArg = pArg;
17279 mem0.alarmThreshold = iThreshold;
17280 sqlite3_mutex_leave(mem0.mutex);
17281 return SQLITE_OK;
17282 }
17283
17284 #ifndef SQLITE_OMIT_DEPRECATED
17285 /*
17286 ** Deprecated external interface. Internal/core SQLite code
17287 ** should call sqlite3MemoryAlarm.
17288 */
17289 SQLITE_API int sqlite3_memory_alarm(
17290 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17291 void *pArg,
17292 sqlite3_int64 iThreshold
17293 ){
17294 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17295 }
17296 #endif
17297
17298 /*
17299 ** Trigger the alarm
17300 */
17301 static void sqlite3MallocAlarm(int nByte){
17302 void (*xCallback)(void*,sqlite3_int64,int);
@@ -17325,18 +17627,23 @@
17325 nFull = sqlite3GlobalConfig.m.xRoundup(n);
17326 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17327 if( mem0.alarmCallback!=0 ){
17328 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17329 if( nUsed+nFull >= mem0.alarmThreshold ){
 
17330 sqlite3MallocAlarm(nFull);
 
 
17331 }
17332 }
17333 p = sqlite3GlobalConfig.m.xMalloc(nFull);
 
17334 if( p==0 && mem0.alarmCallback ){
17335 sqlite3MallocAlarm(nFull);
17336 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17337 }
 
17338 if( p ){
17339 nFull = sqlite3MallocSize(p);
17340 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17341 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17342 }
@@ -17348,11 +17655,13 @@
17348 ** Allocate memory. This routine is like sqlite3_malloc() except that it
17349 ** assumes the memory subsystem has already been initialized.
17350 */
17351 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17352 void *p;
17353 if( n<=0 || n>=0x7fffff00 ){
 
 
17354 /* A memory allocation of a number of bytes which is near the maximum
17355 ** signed integer value might cause an integer overflow inside of the
17356 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
17357 ** 255 bytes of overhead. SQLite itself will never use anything near
17358 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
@@ -17362,10 +17671,11 @@
17362 mallocWithAlarm(n, &p);
17363 sqlite3_mutex_leave(mem0.mutex);
17364 }else{
17365 p = sqlite3GlobalConfig.m.xMalloc(n);
17366 }
 
17367 return p;
17368 }
17369
17370 /*
17371 ** This version of the memory allocation is for use by the application.
@@ -17399,64 +17709,70 @@
17399 ** embedded processor.
17400 */
17401 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17402 void *p;
17403 assert( n>0 );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17404
17405 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17406 /* Verify that no more than two scratch allocation per thread
17407 ** is outstanding at one time. (This is only checked in the
17408 ** single-threaded case since checking in the multi-threaded case
17409 ** would be much more complicated.) */
17410 assert( scratchAllocOut<=1 );
17411 #endif
17412
17413 if( sqlite3GlobalConfig.szScratch<n ){
17414 goto scratch_overflow;
17415 }else{
17416 sqlite3_mutex_enter(mem0.mutex);
17417 if( mem0.nScratchFree==0 ){
17418 sqlite3_mutex_leave(mem0.mutex);
17419 goto scratch_overflow;
17420 }else{
17421 int i;
17422 i = mem0.aScratchFree[--mem0.nScratchFree];
17423 i *= sqlite3GlobalConfig.szScratch;
17424 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17425 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17426 sqlite3_mutex_leave(mem0.mutex);
17427 p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
17428 assert( (((u8*)p - (u8*)0) & 7)==0 );
17429 }
17430 }
17431 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17432 scratchAllocOut = p!=0;
17433 #endif
17434
17435 return p;
17436
17437 scratch_overflow:
17438 if( sqlite3GlobalConfig.bMemstat ){
17439 sqlite3_mutex_enter(mem0.mutex);
17440 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17441 n = mallocWithAlarm(n, &p);
17442 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17443 sqlite3_mutex_leave(mem0.mutex);
17444 }else{
17445 p = sqlite3GlobalConfig.m.xMalloc(n);
17446 }
17447 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17448 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17449 scratchAllocOut = p!=0;
17450 #endif
17451 return p;
17452 }
17453 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17454 if( p ){
17455 if( sqlite3GlobalConfig.pScratch==0
17456 || p<sqlite3GlobalConfig.pScratch
17457 || p>=(void*)mem0.aScratchFree ){
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17458 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17459 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17460 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17461 if( sqlite3GlobalConfig.bMemstat ){
17462 int iSize = sqlite3MallocSize(p);
@@ -17467,30 +17783,10 @@
17467 sqlite3GlobalConfig.m.xFree(p);
17468 sqlite3_mutex_leave(mem0.mutex);
17469 }else{
17470 sqlite3GlobalConfig.m.xFree(p);
17471 }
17472 }else{
17473 int i;
17474 i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
17475 i /= sqlite3GlobalConfig.szScratch;
17476 assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
17477 sqlite3_mutex_enter(mem0.mutex);
17478 assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
17479 mem0.aScratchFree[mem0.nScratchFree++] = i;
17480 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17481 sqlite3_mutex_leave(mem0.mutex);
17482
17483 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17484 /* Verify that no more than two scratch allocation per thread
17485 ** is outstanding at one time. (This is only checked in the
17486 ** single-threaded case since checking in the multi-threaded case
17487 ** would be much more complicated.) */
17488 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17489 scratchAllocOut = 0;
17490 #endif
17491
17492 }
17493 }
17494 }
17495
17496 /*
@@ -17527,11 +17823,11 @@
17527
17528 /*
17529 ** Free memory previously obtained from sqlite3Malloc().
17530 */
17531 SQLITE_API void sqlite3_free(void *p){
17532 if( p==0 ) return;
17533 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17534 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17535 if( sqlite3GlobalConfig.bMemstat ){
17536 sqlite3_mutex_enter(mem0.mutex);
17537 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
@@ -17574,21 +17870,24 @@
17574 */
17575 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17576 int nOld, nNew;
17577 void *pNew;
17578 if( pOld==0 ){
17579 return sqlite3Malloc(nBytes);
17580 }
17581 if( nBytes<=0 ){
17582 sqlite3_free(pOld);
17583 return 0;
17584 }
17585 if( nBytes>=0x7fffff00 ){
17586 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17587 return 0;
17588 }
17589 nOld = sqlite3MallocSize(pOld);
 
 
 
17590 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17591 if( nOld==nNew ){
17592 pNew = pOld;
17593 }else if( sqlite3GlobalConfig.bMemstat ){
17594 sqlite3_mutex_enter(mem0.mutex);
@@ -17610,10 +17909,11 @@
17610 }
17611 sqlite3_mutex_leave(mem0.mutex);
17612 }else{
17613 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17614 }
 
17615 return pNew;
17616 }
17617
17618 /*
17619 ** The public interface to sqlite3Realloc. Make sure that the memory
@@ -19773,10 +20073,16 @@
19773 #define UpperToLower sqlite3UpperToLower
19774
19775 /*
19776 ** Some systems have stricmp(). Others have strcasecmp(). Because
19777 ** there is no consistency, we will define our own.
 
 
 
 
 
 
19778 */
19779 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19780 register unsigned char *a, *b;
19781 a = (unsigned char *)zLeft;
19782 b = (unsigned char *)zRight;
@@ -26177,11 +26483,11 @@
26177 goto shmpage_out;
26178 }
26179 pShmNode->apRegion = apNew;
26180 while(pShmNode->nRegion<=iRegion){
26181 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
26182 MAP_SHARED, pShmNode->h, iRegion*szRegion
26183 );
26184 if( pMem==MAP_FAILED ){
26185 rc = SQLITE_IOERR;
26186 goto shmpage_out;
26187 }
@@ -28000,17 +28306,20 @@
28000 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28001 struct timespec timeout = {1, 0}; /* 1 sec timeout */
28002
28003 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28004 memset(pHostID, 0, PROXY_HOSTIDLEN);
 
 
28005 if( gethostuuid(pHostID, &timeout) ){
28006 int err = errno;
28007 if( pError ){
28008 *pError = err;
28009 }
28010 return SQLITE_IOERR;
28011 }
 
28012 #ifdef SQLITE_TEST
28013 /* simulate multiple hosts by creating unique hostid file paths */
28014 if( sqlite3_hostid_num != 0){
28015 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28016 }
@@ -30339,10 +30648,18 @@
30339 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30340 }
30341
30342 #ifndef SQLITE_OMIT_WAL
30343
 
 
 
 
 
 
 
 
30344 /*
30345 ** Helper functions to obtain and relinquish the global mutex. The
30346 ** global mutex is used to protect the winLockInfo objects used by
30347 ** this file, all of which may be shared by multiple threads.
30348 **
@@ -30507,19 +30824,26 @@
30507 ** by VFS shared-memory methods.
30508 */
30509 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30510 winShmNode **pp;
30511 winShmNode *p;
 
30512 assert( winShmMutexHeld() );
30513 pp = &winShmNodeList;
30514 while( (p = *pp)!=0 ){
30515 if( p->nRef==0 ){
30516 int i;
30517 if( p->mutex ) sqlite3_mutex_free(p->mutex);
30518 for(i=0; i<p->nRegion; i++){
30519 UnmapViewOfFile(p->aRegion[i].pMap);
30520 CloseHandle(p->aRegion[i].hMap);
 
 
 
 
 
 
30521 }
30522 if( p->hFile.h != INVALID_HANDLE_VALUE ){
30523 SimulateIOErrorBenign(1);
30524 winClose((sqlite3_file *)&p->hFile);
30525 SimulateIOErrorBenign(0);
@@ -30592,14 +30916,15 @@
30592 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30593 if( pShmNode->mutex==0 ){
30594 rc = SQLITE_NOMEM;
30595 goto shm_open_err;
30596 }
 
30597 rc = winOpen(pDbFd->pVfs,
30598 pShmNode->zFilename, /* Name of the file (UTF-8) */
30599 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
30600 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30601 0);
30602 if( SQLITE_OK!=rc ){
30603 rc = SQLITE_CANTOPEN_BKPT;
30604 goto shm_open_err;
30605 }
@@ -30903,14 +31228,22 @@
30903 void *pMap = 0; /* Mapped memory region */
30904
30905 hMap = CreateFileMapping(pShmNode->hFile.h,
30906 NULL, PAGE_READWRITE, 0, nByte, NULL
30907 );
 
 
 
30908 if( hMap ){
 
 
30909 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
30910 0, 0, nByte
30911 );
 
 
 
30912 }
30913 if( !pMap ){
30914 pShmNode->lastErrno = GetLastError();
30915 rc = SQLITE_IOERR;
30916 if( hMap ) CloseHandle(hMap);
@@ -30923,12 +31256,14 @@
30923 }
30924 }
30925
30926 shmpage_out:
30927 if( pShmNode->nRegion>iRegion ){
 
 
30928 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
30929 *pp = (void *)&p[iRegion*szRegion];
30930 }else{
30931 *pp = 0;
30932 }
30933 sqlite3_mutex_leave(pShmNode->mutex);
30934 return rc;
@@ -31151,13 +31486,64 @@
31151 DWORD dwFlagsAndAttributes = 0;
31152 #if SQLITE_OS_WINCE
31153 int isTemp = 0;
31154 #endif
31155 winFile *pFile = (winFile*)id;
31156 void *zConverted; /* Filename in OS encoding */
31157 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31158 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31159
31160 assert( id!=0 );
31161 UNUSED_PARAMETER(pVfs);
31162
31163 pFile->h = INVALID_HANDLE_VALUE;
@@ -31164,11 +31550,12 @@
31164
31165 /* If the second argument to this function is NULL, generate a
31166 ** temporary file name to use
31167 */
31168 if( !zUtf8Name ){
31169 int rc = getTempname(MAX_PATH+1, zTmpname);
 
31170 if( rc!=SQLITE_OK ){
31171 return rc;
31172 }
31173 zUtf8Name = zTmpname;
31174 }
@@ -31177,33 +31564,35 @@
31177 zConverted = convertUtf8Filename(zUtf8Name);
31178 if( zConverted==0 ){
31179 return SQLITE_NOMEM;
31180 }
31181
31182 if( flags & SQLITE_OPEN_READWRITE ){
31183 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31184 }else{
31185 dwDesiredAccess = GENERIC_READ;
31186 }
 
31187 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
31188 ** created. SQLite doesn't use it to indicate "exclusive access"
31189 ** as it is usually understood.
31190 */
31191 assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
31192 if( flags & SQLITE_OPEN_EXCLUSIVE ){
31193 /* Creates a new file, only if it does not already exist. */
31194 /* If the file exists, it fails. */
31195 dwCreationDisposition = CREATE_NEW;
31196 }else if( flags & SQLITE_OPEN_CREATE ){
31197 /* Open existing file, or create if it doesn't exist */
31198 dwCreationDisposition = OPEN_ALWAYS;
31199 }else{
31200 /* Opens a file, only if it exists. */
31201 dwCreationDisposition = OPEN_EXISTING;
31202 }
 
31203 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31204 if( flags & SQLITE_OPEN_DELETEONCLOSE ){
 
31205 #if SQLITE_OS_WINCE
31206 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31207 isTemp = 1;
31208 #else
31209 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
@@ -31216,10 +31605,11 @@
31216 /* Reports from the internet are that performance is always
31217 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
31218 #if SQLITE_OS_WINCE
31219 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31220 #endif
 
31221 if( isNT() ){
31222 h = CreateFileW((WCHAR*)zConverted,
31223 dwDesiredAccess,
31224 dwShareMode,
31225 NULL,
@@ -31241,41 +31631,45 @@
31241 dwFlagsAndAttributes,
31242 NULL
31243 );
31244 #endif
31245 }
 
31246 OSTRACE(("OPEN %d %s 0x%lx %s\n",
31247 h, zName, dwDesiredAccess,
31248 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
 
31249 if( h==INVALID_HANDLE_VALUE ){
31250 pFile->lastErrno = GetLastError();
31251 free(zConverted);
31252 if( flags & SQLITE_OPEN_READWRITE ){
31253 return winOpen(pVfs, zName, id,
31254 ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
31255 }else{
31256 return SQLITE_CANTOPEN_BKPT;
31257 }
31258 }
 
31259 if( pOutFlags ){
31260 if( flags & SQLITE_OPEN_READWRITE ){
31261 *pOutFlags = SQLITE_OPEN_READWRITE;
31262 }else{
31263 *pOutFlags = SQLITE_OPEN_READONLY;
31264 }
31265 }
 
31266 memset(pFile, 0, sizeof(*pFile));
31267 pFile->pMethod = &winIoMethod;
31268 pFile->h = h;
31269 pFile->lastErrno = NO_ERROR;
31270 pFile->pVfs = pVfs;
31271 pFile->pShm = 0;
31272 pFile->zPath = zName;
31273 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
 
31274 #if SQLITE_OS_WINCE
31275 if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
31276 (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
31277 && !winceCreateLock(zName, pFile)
31278 ){
31279 CloseHandle(h);
31280 free(zConverted);
31281 return SQLITE_CANTOPEN_BKPT;
@@ -31285,12 +31679,13 @@
31285 }else
31286 #endif
31287 {
31288 free(zConverted);
31289 }
 
31290 OpenCounter(+1);
31291 return SQLITE_OK;
31292 }
31293
31294 /*
31295 ** Delete the named file.
31296 **
@@ -31804,10 +32199,17 @@
31804 winSleep, /* xSleep */
31805 winCurrentTime, /* xCurrentTime */
31806 winGetLastError, /* xGetLastError */
31807 winCurrentTimeInt64, /* xCurrentTimeInt64 */
31808 };
 
 
 
 
 
 
 
31809
31810 sqlite3_vfs_register(&winVfs, 1);
31811 return SQLITE_OK;
31812 }
31813 SQLITE_API int sqlite3_os_end(void){
@@ -32369,16 +32771,20 @@
32369 ** Initialize and shutdown the page cache subsystem. Neither of these
32370 ** functions are threadsafe.
32371 */
32372 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32373 if( sqlite3GlobalConfig.pcache.xInit==0 ){
 
 
 
32374 sqlite3PCacheSetDefault();
32375 }
32376 return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32377 }
32378 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32379 if( sqlite3GlobalConfig.pcache.xShutdown ){
 
32380 sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32381 }
32382 }
32383
32384 /*
@@ -32835,12 +33241,17 @@
32835
32836 typedef struct PCache1 PCache1;
32837 typedef struct PgHdr1 PgHdr1;
32838 typedef struct PgFreeslot PgFreeslot;
32839
32840 /* Pointers to structures of this type are cast and returned as
32841 ** opaque sqlite3_pcache* handles
 
 
 
 
 
32842 */
32843 struct PCache1 {
32844 /* Cache configuration parameters. Page size (szPage) and the purgeable
32845 ** flag (bPurgeable) are set when the cache is created. nMax may be
32846 ** modified at any time by a call to the pcache1CacheSize() method.
@@ -32896,10 +33307,13 @@
32896 int nCurrentPage; /* Number of purgeable pages allocated */
32897 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
32898
32899 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
32900 int szSlot; /* Size of each free slot */
 
 
 
32901 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
32902 PgFreeslot *pFree; /* Free page blocks */
32903 int isInit; /* True if initialized */
32904 } pcache1_g;
32905
@@ -32943,10 +33357,12 @@
32943 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
32944 if( pcache1.isInit ){
32945 PgFreeslot *p;
32946 sz = ROUNDDOWN8(sz);
32947 pcache1.szSlot = sz;
 
 
32948 pcache1.pStart = pBuf;
32949 pcache1.pFree = 0;
32950 while( n-- ){
32951 p = (PgFreeslot*)pBuf;
32952 p->pNext = pcache1.pFree;
@@ -32969,10 +33385,12 @@
32969 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
32970 if( nByte<=pcache1.szSlot && pcache1.pFree ){
32971 assert( pcache1.isInit );
32972 p = (PgHdr1 *)pcache1.pFree;
32973 pcache1.pFree = pcache1.pFree->pNext;
 
 
32974 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
32975 }else{
32976
32977 /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
32978 ** global pcache mutex and unlock the pager-cache object pCache. This is
@@ -33002,10 +33420,12 @@
33002 PgFreeslot *pSlot;
33003 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33004 pSlot = (PgFreeslot*)p;
33005 pSlot->pNext = pcache1.pFree;
33006 pcache1.pFree = pSlot;
 
 
33007 }else{
33008 int iSize;
33009 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33010 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33011 iSize = sqlite3MallocSize(p);
@@ -33014,11 +33434,11 @@
33014 }
33015 }
33016
33017 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33018 /*
33019 ** Return the size of a pache allocation
33020 */
33021 static int pcache1MemSize(void *p){
33022 assert( sqlite3_mutex_held(pcache1.mutex) );
33023 if( p>=pcache1.pStart && p<pcache1.pEnd ){
33024 return pcache1.szSlot;
@@ -33087,10 +33507,36 @@
33087 pcache1EnterMutex();
33088 pcache1Free(p);
33089 pcache1LeaveMutex();
33090 }
33091
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33092 /******************************************************************************/
33093 /******** General Implementation Functions ************************************/
33094
33095 /*
33096 ** This function is used to resize the hash table used by the cache passed
@@ -33328,18 +33774,20 @@
33328 ** copy of the requested page. If one is found, it is returned.
33329 **
33330 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
33331 ** returned.
33332 **
33333 ** 3. If createFlag is 1, and the page is not already in the cache,
33334 ** and if either of the following are true, return NULL:
 
33335 **
33336 ** (a) the number of pages pinned by the cache is greater than
33337 ** PCache1.nMax, or
 
33338 ** (b) the number of pages pinned by the cache is greater than
33339 ** the sum of nMax for all purgeable caches, less the sum of
33340 ** nMin for all other purgeable caches.
33341 **
33342 ** 4. If none of the first three conditions apply and the cache is marked
33343 ** as purgeable, and if one of the following is true:
33344 **
33345 ** (a) The number of pages allocated for the cache is already
@@ -33346,10 +33794,13 @@
33346 ** PCache1.nMax, or
33347 **
33348 ** (b) The number of pages allocated for all purgeable caches is
33349 ** already equal to or greater than the sum of nMax for all
33350 ** purgeable caches,
 
 
 
33351 **
33352 ** then attempt to recycle a page from the LRU list. If it is the right
33353 ** size, return the recycled buffer. Otherwise, free the buffer and
33354 ** proceed to step 5.
33355 **
@@ -33378,10 +33829,11 @@
33378 /* Step 3 of header comment. */
33379 nPinned = pCache->nPage - pCache->nRecyclable;
33380 if( createFlag==1 && (
33381 nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33382 || nPinned>=(pCache->nMax * 9 / 10)
 
33383 )){
33384 goto fetch_out;
33385 }
33386
33387 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
@@ -33388,11 +33840,13 @@
33388 goto fetch_out;
33389 }
33390
33391 /* Step 4. Try to recycle a page buffer if appropriate. */
33392 if( pCache->bPurgeable && pcache1.pLruTail && (
33393 (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
 
 
33394 )){
33395 pPage = pcache1.pLruTail;
33396 pcache1RemoveFromHash(pPage);
33397 pcache1PinPage(pPage);
33398 if( pPage->pCache->szPage!=pCache->szPage ){
@@ -33531,10 +33985,11 @@
33531 **
33532 ** Destroy a cache allocated using pcache1Create().
33533 */
33534 static void pcache1Destroy(sqlite3_pcache *p){
33535 PCache1 *pCache = (PCache1 *)p;
 
33536 pcache1EnterMutex();
33537 pcache1TruncateUnsafe(pCache, 0);
33538 pcache1.nMaxPage -= pCache->nMax;
33539 pcache1.nMinPage -= pCache->nMin;
33540 pcache1EnforceMaxPage();
@@ -33578,11 +34033,11 @@
33578 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
33579 int nFree = 0;
33580 if( pcache1.pStart==0 ){
33581 PgHdr1 *p;
33582 pcache1EnterMutex();
33583 while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
33584 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
33585 pcache1PinPage(p);
33586 pcache1RemoveFromHash(p);
33587 pcache1FreePage(p);
33588 }
@@ -37120,16 +37575,17 @@
37120 ** the duplicate call is harmless.
37121 */
37122 sqlite3WalEndReadTransaction(pPager->pWal);
37123
37124 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37125 if( rc==SQLITE_OK && changed ){
37126 pager_reset(pPager);
37127 }
37128
37129 return rc;
37130 }
 
37131
37132 /*
37133 ** This function is called as part of the transition from PAGER_OPEN
37134 ** to PAGER_READER state to determine the size of the database file
37135 ** in pages (assuming the page size currently stored in Pager.pageSize).
@@ -37182,11 +37638,11 @@
37182
37183 *pnPage = nPage;
37184 return SQLITE_OK;
37185 }
37186
37187
37188 /*
37189 ** Check if the *-wal file that corresponds to the database opened by pPager
37190 ** exists if the database is not empy, or verify that the *-wal file does
37191 ** not exist (by deleting it) if the database file is empty.
37192 **
@@ -38374,10 +38830,17 @@
38374 journalFileSize = ROUND8(sqlite3MemJournalSize());
38375 }
38376
38377 /* Set the output variable to NULL in case an error occurs. */
38378 *ppPager = 0;
 
 
 
 
 
 
 
38379
38380 /* Compute and store the full pathname in an allocated buffer pointed
38381 ** to by zPathname, length nPathname. Or, if this is a temporary file,
38382 ** leave both nPathname and zPathname set to 0.
38383 */
@@ -38385,21 +38848,12 @@
38385 nPathname = pVfs->mxPathname+1;
38386 zPathname = sqlite3Malloc(nPathname*2);
38387 if( zPathname==0 ){
38388 return SQLITE_NOMEM;
38389 }
38390 #ifndef SQLITE_OMIT_MEMORYDB
38391 if( strcmp(zFilename,":memory:")==0 ){
38392 memDb = 1;
38393 zPathname[0] = 0;
38394 }else
38395 #endif
38396 {
38397 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38398 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
38399 }
38400
38401 nPathname = sqlite3Strlen30(zPathname);
38402 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
38403 /* This branch is taken when the journal path required by
38404 ** the database being opened will be more than pVfs->mxPathname
38405 ** bytes in length. This means the database cannot be opened,
@@ -38450,34 +38904,31 @@
38450 pPager->zFilename = (char*)(pPtr += journalFileSize);
38451 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
38452
38453 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
38454 if( zPathname ){
 
38455 pPager->zJournal = (char*)(pPtr += nPathname + 1);
38456 memcpy(pPager->zFilename, zPathname, nPathname);
38457 memcpy(pPager->zJournal, zPathname, nPathname);
38458 memcpy(&pPager->zJournal[nPathname], "-journal", 8);
38459 if( pPager->zFilename[0]==0 ){
38460 pPager->zJournal[0] = 0;
38461 }
38462 #ifndef SQLITE_OMIT_WAL
38463 else{
38464 pPager->zWal = &pPager->zJournal[nPathname+8+1];
38465 memcpy(pPager->zWal, zPathname, nPathname);
38466 memcpy(&pPager->zWal[nPathname], "-wal", 4);
38467 }
38468 #endif
38469 sqlite3_free(zPathname);
38470 }
38471 pPager->pVfs = pVfs;
38472 pPager->vfsFlags = vfsFlags;
38473
38474 /* Open the pager file.
38475 */
38476 if( zFilename && zFilename[0] && !memDb ){
38477 int fout = 0; /* VFS flags returned by xOpen() */
38478 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
 
38479 readOnly = (fout&SQLITE_OPEN_READONLY);
38480
38481 /* If the file was successfully opened for read/write access,
38482 ** choose a default page size in case we have to create the
38483 ** database file. The default page size is the maximum of:
@@ -38927,11 +39378,13 @@
38927
38928 /* If there is a WAL file in the file-system, open this database in WAL
38929 ** mode. Otherwise, the following function call is a no-op.
38930 */
38931 rc = pagerOpenWalIfPresent(pPager);
 
38932 assert( pPager->pWal==0 || rc==SQLITE_OK );
 
38933 }
38934
38935 if( pagerUseWal(pPager) ){
38936 assert( rc==SQLITE_OK );
38937 rc = pagerBeginReadTransaction(pPager);
@@ -43292,11 +43745,11 @@
43292 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43293 if( rc!=SQLITE_OK ){
43294 return rc;
43295 }
43296 }
43297 assert( pWal->szPage==szPage );
43298
43299 /* Write the log file. */
43300 for(p=pList; p; p=p->pDirty){
43301 u32 nDbsize; /* Db-size field for frame header */
43302 i64 iOffset; /* Write offset in log file */
@@ -43952,10 +44405,11 @@
43952 MemPage *pPage1; /* First page of the database */
43953 u8 readOnly; /* True if the underlying file is readonly */
43954 u8 pageSizeFixed; /* True if the page size can no longer be changed */
43955 u8 secureDelete; /* True if secure_delete is enabled */
43956 u8 initiallyEmpty; /* Database is empty at start of transaction */
 
43957 #ifndef SQLITE_OMIT_AUTOVACUUM
43958 u8 autoVacuum; /* True if auto-vacuum is enabled */
43959 u8 incrVacuum; /* True if incr-vacuum is enabled */
43960 #endif
43961 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
@@ -46202,15 +46656,24 @@
46202
46203 /*
46204 ** Open a database file.
46205 **
46206 ** zFilename is the name of the database file. If zFilename is NULL
46207 ** a new database with a random name is created. This randomly named
46208 ** database file will be deleted when sqlite3BtreeClose() is called.
 
 
 
46209 ** If zFilename is ":memory:" then an in-memory database is created
46210 ** that is automatically destroyed when it is closed.
46211 **
 
 
 
 
 
 
46212 ** If the database is already opened in the same database connection
46213 ** and we are in shared cache mode, then the open will fail with an
46214 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
46215 ** objects in the same database connection since doing so will lead
46216 ** to problems with locking.
@@ -46227,10 +46690,13 @@
46227 Btree *p; /* Handle to return */
46228 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
46229 int rc = SQLITE_OK; /* Result code from this function */
46230 u8 nReserve; /* Byte of unused space on each page */
46231 unsigned char zDbHeader[100]; /* Database header content */
 
 
 
46232
46233 /* Set the variable isMemdb to true for an in-memory database, or
46234 ** false for a file-based database. This symbol is only required if
46235 ** either of the shared-data or autovacuum features are compiled
46236 ** into the library.
@@ -46237,17 +46703,34 @@
46237 */
46238 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
46239 #ifdef SQLITE_OMIT_MEMORYDB
46240 const int isMemdb = 0;
46241 #else
46242 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
 
46243 #endif
46244 #endif
46245
46246 assert( db!=0 );
46247 assert( sqlite3_mutex_held(db->mutex) );
 
46248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46249 pVfs = db->pVfs;
46250 p = sqlite3MallocZero(sizeof(Btree));
46251 if( !p ){
46252 return SQLITE_NOMEM;
46253 }
@@ -46261,11 +46744,11 @@
46261 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46262 /*
46263 ** If this Btree is a candidate for shared cache, try to find an
46264 ** existing BtShared object that we can share with
46265 */
46266 if( isMemdb==0 && zFilename && zFilename[0] ){
46267 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
46268 int nFullPathname = pVfs->mxPathname+1;
46269 char *zFullPathname = sqlite3Malloc(nFullPathname);
46270 sqlite3_mutex *mutexShared;
46271 p->sharable = 1;
@@ -46336,10 +46819,11 @@
46336 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
46337 }
46338 if( rc!=SQLITE_OK ){
46339 goto btree_open_out;
46340 }
 
46341 pBt->db = db;
46342 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
46343 p->pBt = pBt;
46344
46345 pBt->pCursor = 0;
@@ -46440,10 +46924,18 @@
46440 sqlite3PagerClose(pBt->pPager);
46441 }
46442 sqlite3_free(pBt);
46443 sqlite3_free(p);
46444 *ppBtree = 0;
 
 
 
 
 
 
 
 
46445 }
46446 if( mutexOpen ){
46447 assert( sqlite3_mutex_held(mutexOpen) );
46448 sqlite3_mutex_leave(mutexOpen);
46449 }
@@ -51390,15 +51882,16 @@
51390 ** flags might not work:
51391 **
51392 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
51393 ** BTREE_ZERODATA Used for SQL indices
51394 */
51395 static int btreeCreateTable(Btree *p, int *piTable, int flags){
51396 BtShared *pBt = p->pBt;
51397 MemPage *pRoot;
51398 Pgno pgnoRoot;
51399 int rc;
 
51400
51401 assert( sqlite3BtreeHoldsMutex(p) );
51402 assert( pBt->inTransaction==TRANS_WRITE );
51403 assert( !pBt->readOnly );
51404
@@ -51513,12 +52006,18 @@
51513 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
51514 if( rc ) return rc;
51515 }
51516 #endif
51517 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51518 zeroPage(pRoot, flags | PTF_LEAF);
 
 
 
 
 
51519 sqlite3PagerUnref(pRoot->pDbPage);
 
51520 *piTable = (int)pgnoRoot;
51521 return SQLITE_OK;
51522 }
51523 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
51524 int rc;
@@ -52774,11 +53273,14 @@
52774 sqlite3Error(
52775 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
52776 );
52777 p = 0;
52778 }else {
52779 /* Allocate space for a new sqlite3_backup object */
 
 
 
52780 p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
52781 if( !p ){
52782 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
52783 }
52784 }
@@ -53157,10 +53659,13 @@
53157 if( p->pDestDb ){
53158 sqlite3_mutex_leave(p->pDestDb->mutex);
53159 }
53160 sqlite3BtreeLeave(p->pSrc);
53161 if( p->pDestDb ){
 
 
 
53162 sqlite3_free(p);
53163 }
53164 sqlite3_mutex_leave(mutex);
53165 return rc;
53166 }
@@ -53408,10 +53913,13 @@
53408 return SQLITE_NOMEM;
53409 }
53410 pMem->z[pMem->n] = 0;
53411 pMem->z[pMem->n+1] = 0;
53412 pMem->flags |= MEM_Term;
 
 
 
53413 }
53414
53415 return SQLITE_OK;
53416 }
53417
@@ -53528,11 +54036,11 @@
53528 memset(&ctx, 0, sizeof(ctx));
53529 ctx.s.flags = MEM_Null;
53530 ctx.s.db = pMem->db;
53531 ctx.pMem = pMem;
53532 ctx.pFunc = pFunc;
53533 pFunc->xFinalize(&ctx);
53534 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
53535 sqlite3DbFree(pMem->db, pMem->zMalloc);
53536 memcpy(pMem, &ctx.s, sizeof(ctx.s));
53537 rc = ctx.isError;
53538 }
@@ -53869,10 +54377,32 @@
53869 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
53870 }
53871 return 0;
53872 }
53873
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53874 /*
53875 ** Size of struct Mem not including the Mem.zMalloc member.
53876 */
53877 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
53878
@@ -54237,11 +54767,11 @@
54237 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
54238 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
54239 return 0;
54240 }
54241 }
54242 sqlite3VdbeMemNulTerminate(pVal);
54243 }else{
54244 assert( (pVal->flags&MEM_Blob)==0 );
54245 sqlite3VdbeMemStringify(pVal, enc);
54246 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
54247 }
@@ -56152,13 +56682,14 @@
56152 */
56153 for(i=0; i<db->nDb; i++){
56154 Btree *pBt = db->aDb[i].pBt;
56155 if( sqlite3BtreeIsInTrans(pBt) ){
56156 char const *zFile = sqlite3BtreeGetJournalname(pBt);
56157 if( zFile==0 || zFile[0]==0 ){
56158 continue; /* Ignore TEMP and :memory: databases */
56159 }
 
56160 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
56161 needSync = 1;
56162 }
56163 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
56164 offset += sqlite3Strlen30(zFile)+1;
@@ -57618,10 +58149,12 @@
57618 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
57619 */
57620 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
57621 int rc;
57622 if( pStmt==0 ){
 
 
57623 rc = SQLITE_OK;
57624 }else{
57625 Vdbe *v = (Vdbe*)pStmt;
57626 sqlite3 *db = v->db;
57627 #if SQLITE_THREADSAFE
@@ -57694,11 +58227,11 @@
57694 Mem *p = (Mem*)pVal;
57695 if( p->flags & (MEM_Blob|MEM_Str) ){
57696 sqlite3VdbeMemExpandBlob(p);
57697 p->flags &= ~MEM_Str;
57698 p->flags |= MEM_Blob;
57699 return p->z;
57700 }else{
57701 return sqlite3_value_text(pVal);
57702 }
57703 }
57704 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
@@ -58048,10 +58581,16 @@
58048 }
58049
58050 /*
58051 ** Extract the user data from a sqlite3_context structure and return a
58052 ** pointer to it.
 
 
 
 
 
 
58053 */
58054 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
58055 assert( p && p->pFunc );
58056 return p->s.db;
58057 }
@@ -58257,12 +58796,11 @@
58257 ** sqlite3_column_text()
58258 ** sqlite3_column_text16()
58259 ** sqlite3_column_real()
58260 ** sqlite3_column_bytes()
58261 ** sqlite3_column_bytes16()
58262 **
58263 ** But not for sqlite3_column_blob(), which never calls malloc().
58264 */
58265 static void columnMallocFailure(sqlite3_stmt *pStmt)
58266 {
58267 /* If malloc() failed during an encoding conversion within an
58268 ** sqlite3_column_XXX API, then set the return code of the statement to
@@ -58526,10 +59064,16 @@
58526 pVar->flags = MEM_Null;
58527 sqlite3Error(p->db, SQLITE_OK, 0);
58528
58529 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
58530 ** binding a new value to this variable invalidates the current query plan.
 
 
 
 
 
 
58531 */
58532 if( p->isPrepareV2 &&
58533 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
58534 ){
58535 p->expired = 1;
@@ -59023,10 +59567,21 @@
59023 ** of the code in this file is, therefore, important. See other comments
59024 ** in this file for details. If in doubt, do not deviate from existing
59025 ** commenting and indentation practices when changing or adding code.
59026 */
59027
 
 
 
 
 
 
 
 
 
 
 
59028 /*
59029 ** The following global variable is incremented every time a cursor
59030 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
59031 ** procedures use this information to make sure that indices are
59032 ** working correctly. This variable has no function other than to
@@ -60132,38 +60687,44 @@
60132 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
60133 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
60134 assert( pOp->p2>0 );
60135 assert( pOp->p2<=p->nMem );
60136 pOut = &aMem[pOp->p2];
 
60137 sqlite3VdbeMemReleaseExternal(pOut);
60138 pOut->flags = MEM_Int;
60139 }
60140
60141 /* Sanity checking on other operands */
60142 #ifdef SQLITE_DEBUG
60143 if( (pOp->opflags & OPFLG_IN1)!=0 ){
60144 assert( pOp->p1>0 );
60145 assert( pOp->p1<=p->nMem );
 
60146 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
60147 }
60148 if( (pOp->opflags & OPFLG_IN2)!=0 ){
60149 assert( pOp->p2>0 );
60150 assert( pOp->p2<=p->nMem );
 
60151 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
60152 }
60153 if( (pOp->opflags & OPFLG_IN3)!=0 ){
60154 assert( pOp->p3>0 );
60155 assert( pOp->p3<=p->nMem );
 
60156 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
60157 }
60158 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
60159 assert( pOp->p2>0 );
60160 assert( pOp->p2<=p->nMem );
 
60161 }
60162 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
60163 assert( pOp->p3>0 );
60164 assert( pOp->p3<=p->nMem );
 
60165 }
60166 #endif
60167
60168 switch( pOp->opcode ){
60169
@@ -60221,10 +60782,11 @@
60221 ** and then jump to address P2.
60222 */
60223 case OP_Gosub: { /* jump, in1 */
60224 pIn1 = &aMem[pOp->p1];
60225 assert( (pIn1->flags & MEM_Dyn)==0 );
 
60226 pIn1->flags = MEM_Int;
60227 pIn1->u.i = pc;
60228 REGISTER_TRACE(pOp->p1, pIn1);
60229 pc = pOp->p2 - 1;
60230 break;
@@ -60428,15 +60990,11 @@
60428
60429
60430 /* Opcode: Blob P1 P2 * P4
60431 **
60432 ** P4 points to a blob of data P1 bytes long. Store this
60433 ** blob in register P2. This instruction is not coded directly
60434 ** by the compiler. Instead, the compiler layer specifies
60435 ** an OP_HexBlob opcode, with the hex string representation of
60436 ** the blob as P4. This opcode is transformed to an OP_Blob
60437 ** the first time it is executed.
60438 */
60439 case OP_Blob: { /* out2-prerelease */
60440 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
60441 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
60442 pOut->enc = encoding;
@@ -60490,10 +61048,12 @@
60490 pIn1 = &aMem[u.ac.p1];
60491 pOut = &aMem[u.ac.p2];
60492 while( u.ac.n-- ){
60493 assert( pOut<=&aMem[p->nMem] );
60494 assert( pIn1<=&aMem[p->nMem] );
 
 
60495 u.ac.zMalloc = pOut->zMalloc;
60496 pOut->zMalloc = 0;
60497 sqlite3VdbeMemMove(pOut, pIn1);
60498 pIn1->zMalloc = u.ac.zMalloc;
60499 REGISTER_TRACE(u.ac.p2++, pOut);
@@ -60535,10 +61095,13 @@
60535 case OP_SCopy: { /* in1, out2 */
60536 pIn1 = &aMem[pOp->p1];
60537 pOut = &aMem[pOp->p2];
60538 assert( pOut!=pIn1 );
60539 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
 
 
 
60540 REGISTER_TRACE(pOp->p2, pOut);
60541 break;
60542 }
60543
60544 /* Opcode: ResultRow P1 P2 * * *
@@ -60595,10 +61158,14 @@
60595 ** and have an assigned type. The results are de-ephemeralized as
60596 ** as side effect.
60597 */
60598 u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
60599 for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
 
 
 
 
60600 sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
60601 sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
60602 REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
60603 }
60604 if( db->mallocFailed ) goto no_mem;
@@ -60826,16 +61393,21 @@
60826 #endif /* local variables moved into u.ag */
60827
60828 u.ag.n = pOp->p5;
60829 u.ag.apVal = p->apArg;
60830 assert( u.ag.apVal || u.ag.n==0 );
 
 
 
60831
60832 assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
60833 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
60834 u.ag.pArg = &aMem[pOp->p2];
60835 for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
 
60836 u.ag.apVal[u.ag.i] = u.ag.pArg;
 
60837 sqlite3VdbeMemStoreType(u.ag.pArg);
60838 REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
60839 }
60840
60841 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
@@ -60845,12 +61417,10 @@
60845 }else{
60846 u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
60847 u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
60848 }
60849
60850 assert( pOp->p3>0 && pOp->p3<=p->nMem );
60851 pOut = &aMem[pOp->p3];
60852 u.ag.ctx.s.flags = MEM_Null;
60853 u.ag.ctx.s.db = db;
60854 u.ag.ctx.s.xDel = 0;
60855 u.ag.ctx.s.zMalloc = 0;
60856
@@ -60866,11 +61436,11 @@
60866 assert( pOp>aOp );
60867 assert( pOp[-1].p4type==P4_COLLSEQ );
60868 assert( pOp[-1].opcode==OP_CollSeq );
60869 u.ag.ctx.pColl = pOp[-1].p4.pColl;
60870 }
60871 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
60872 if( db->mallocFailed ){
60873 /* Even though a malloc() has failed, the implementation of the
60874 ** user function may have called an sqlite3_result_XXX() function
60875 ** to return a value. The following call releases any resources
60876 ** associated with such a value.
@@ -60918,11 +61488,11 @@
60918 ** If either input is NULL, the result is NULL.
60919 */
60920 /* Opcode: ShiftLeft P1 P2 P3 * *
60921 **
60922 ** Shift the integer value in register P2 to the left by the
60923 ** number of bits specified by the integer in regiser P1.
60924 ** Store the result in register P3.
60925 ** If either input is NULL, the result is NULL.
60926 */
60927 /* Opcode: ShiftRight P1 P2 P3 * *
60928 **
@@ -60968,10 +61538,11 @@
60968 **
60969 ** To force any register to be an integer, just add 0.
60970 */
60971 case OP_AddImm: { /* in1 */
60972 pIn1 = &aMem[pOp->p1];
 
60973 sqlite3VdbeMemIntegerify(pIn1);
60974 pIn1->u.i += pOp->p2;
60975 break;
60976 }
60977
@@ -60982,10 +61553,11 @@
60982 ** without data loss, then jump immediately to P2, or if P2==0
60983 ** raise an SQLITE_MISMATCH exception.
60984 */
60985 case OP_MustBeInt: { /* jump, in1 */
60986 pIn1 = &aMem[pOp->p1];
 
60987 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
60988 if( (pIn1->flags & MEM_Int)==0 ){
60989 if( pOp->p2==0 ){
60990 rc = SQLITE_MISMATCH;
60991 goto abort_due_to_error;
@@ -61008,10 +61580,11 @@
61008 ** integers, for space efficiency, but after extraction we want them
61009 ** to have only a real value.
61010 */
61011 case OP_RealAffinity: { /* in1 */
61012 pIn1 = &aMem[pOp->p1];
 
61013 if( pIn1->flags & MEM_Int ){
61014 sqlite3VdbeMemRealify(pIn1);
61015 }
61016 break;
61017 }
@@ -61027,10 +61600,11 @@
61027 **
61028 ** A NULL value is not changed by this routine. It remains NULL.
61029 */
61030 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
61031 pIn1 = &aMem[pOp->p1];
 
61032 if( pIn1->flags & MEM_Null ) break;
61033 assert( MEM_Str==(MEM_Blob>>3) );
61034 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
61035 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61036 rc = ExpandBlob(pIn1);
@@ -61049,10 +61623,11 @@
61049 **
61050 ** A NULL value is not changed by this routine. It remains NULL.
61051 */
61052 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
61053 pIn1 = &aMem[pOp->p1];
 
61054 if( pIn1->flags & MEM_Null ) break;
61055 if( (pIn1->flags & MEM_Blob)==0 ){
61056 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61057 assert( pIn1->flags & MEM_Str || db->mallocFailed );
61058 MemSetTypeFlag(pIn1, MEM_Blob);
@@ -61073,28 +61648,30 @@
61073 **
61074 ** A NULL value is not changed by this routine. It remains NULL.
61075 */
61076 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
61077 pIn1 = &aMem[pOp->p1];
 
61078 if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
61079 sqlite3VdbeMemNumerify(pIn1);
61080 }
61081 break;
61082 }
61083 #endif /* SQLITE_OMIT_CAST */
61084
61085 /* Opcode: ToInt P1 * * * *
61086 **
61087 ** Force the value in register P1 be an integer. If
61088 ** The value is currently a real number, drop its fractional part.
61089 ** If the value is text or blob, try to convert it to an integer using the
61090 ** equivalent of atoi() and store 0 if no such conversion is possible.
61091 **
61092 ** A NULL value is not changed by this routine. It remains NULL.
61093 */
61094 case OP_ToInt: { /* same as TK_TO_INT, in1 */
61095 pIn1 = &aMem[pOp->p1];
 
61096 if( (pIn1->flags & MEM_Null)==0 ){
61097 sqlite3VdbeMemIntegerify(pIn1);
61098 }
61099 break;
61100 }
@@ -61109,10 +61686,11 @@
61109 **
61110 ** A NULL value is not changed by this routine. It remains NULL.
61111 */
61112 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
61113 pIn1 = &aMem[pOp->p1];
 
61114 if( (pIn1->flags & MEM_Null)==0 ){
61115 sqlite3VdbeMemRealify(pIn1);
61116 }
61117 break;
61118 }
@@ -61123,11 +61701,11 @@
61123 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
61124 ** jump to address P2.
61125 **
61126 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
61127 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
61128 ** bit is clear then fall thru if either operand is NULL.
61129 **
61130 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
61131 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
61132 ** to coerce both inputs according to this affinity before the
61133 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
@@ -61203,10 +61781,12 @@
61203 u16 flags3; /* Copy of initial value of pIn3->flags */
61204 #endif /* local variables moved into u.ai */
61205
61206 pIn1 = &aMem[pOp->p1];
61207 pIn3 = &aMem[pOp->p3];
 
 
61208 u.ai.flags1 = pIn1->flags;
61209 u.ai.flags3 = pIn3->flags;
61210 if( (pIn1->flags | pIn3->flags)&MEM_Null ){
61211 /* One or both operands are NULL */
61212 if( pOp->p5 & SQLITE_NULLEQ ){
@@ -61253,10 +61833,11 @@
61253 default: u.ai.res = u.ai.res>=0; break;
61254 }
61255
61256 if( pOp->p5 & SQLITE_STOREP2 ){
61257 pOut = &aMem[pOp->p2];
 
61258 MemSetTypeFlag(pOut, MEM_Int);
61259 pOut->u.i = u.ai.res;
61260 REGISTER_TRACE(pOp->p2, pOut);
61261 }else if( u.ai.res ){
61262 pc = pOp->p2-1;
@@ -61284,12 +61865,12 @@
61284 break;
61285 }
61286
61287 /* Opcode: Compare P1 P2 P3 P4 *
61288 **
61289 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
61290 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
61291 ** the comparison for use by the next OP_Jump instruct.
61292 **
61293 ** P4 is a KeyInfo structure that defines collating sequences and sort
61294 ** orders for the comparison. The permutation applies to registers
61295 ** only. The KeyInfo elements are used sequentially.
@@ -61327,10 +61908,12 @@
61327 assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
61328 }
61329 #endif /* SQLITE_DEBUG */
61330 for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
61331 u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
 
 
61332 REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
61333 REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
61334 assert( u.aj.i<u.aj.pKeyInfo->nField );
61335 u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
61336 u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
@@ -61558,10 +62141,11 @@
61558 u.am.pC = 0;
61559 memset(&u.am.sMem, 0, sizeof(u.am.sMem));
61560 assert( u.am.p1<p->nCursor );
61561 assert( pOp->p3>0 && pOp->p3<=p->nMem );
61562 u.am.pDest = &aMem[pOp->p3];
 
61563 MemSetTypeFlag(u.am.pDest, MEM_Null);
61564 u.am.zRec = 0;
61565
61566 /* This block sets the variable u.am.payloadSize to be the total number of
61567 ** bytes in the record.
@@ -61605,10 +62189,11 @@
61605 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
61606 }
61607 }else if( u.am.pC->pseudoTableReg>0 ){
61608 u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
61609 assert( u.am.pReg->flags & MEM_Blob );
 
61610 u.am.payloadSize = u.am.pReg->n;
61611 u.am.zRec = u.am.pReg->z;
61612 u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
61613 assert( u.am.payloadSize==0 || u.am.zRec!=0 );
61614 }else{
@@ -61829,25 +62414,24 @@
61829 assert( u.an.zAffinity!=0 );
61830 assert( u.an.zAffinity[pOp->p2]==0 );
61831 pIn1 = &aMem[pOp->p1];
61832 while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
61833 assert( pIn1 <= &p->aMem[p->nMem] );
 
 
61834 ExpandBlob(pIn1);
61835 applyAffinity(pIn1, u.an.cAff, encoding);
61836 pIn1++;
61837 }
61838 break;
61839 }
61840
61841 /* Opcode: MakeRecord P1 P2 P3 P4 *
61842 **
61843 ** Convert P2 registers beginning with P1 into a single entry
61844 ** suitable for use as a data record in a database table or as a key
61845 ** in an index. The details of the format are irrelevant as long as
61846 ** the OP_Column opcode can decode the record later.
61847 ** Refer to source code comments for the details of the record
61848 ** format.
61849 **
61850 ** P4 may be a string that is P2 characters long. The nth character of the
61851 ** string indicates the column affinity that should be used for the nth
61852 ** field of the index key.
61853 **
@@ -61899,16 +62483,23 @@
61899 assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
61900 u.ao.pData0 = &aMem[u.ao.nField];
61901 u.ao.nField = pOp->p2;
61902 u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
61903 u.ao.file_format = p->minWriteFileFormat;
 
 
 
 
 
61904
61905 /* Loop through the elements that will make up the record to figure
61906 ** out how much space is required for the new record.
61907 */
61908 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
 
61909 if( u.ao.zAffinity ){
 
61910 applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
61911 }
61912 if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
61913 sqlite3VdbeMemExpandBlob(u.ao.pRec);
61914 }
@@ -61938,12 +62529,10 @@
61938 /* Make sure the output register has a buffer large enough to store
61939 ** the new record. The output register (pOp->p3) is not allowed to
61940 ** be one of the input registers (because the following call to
61941 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
61942 */
61943 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
61944 pOut = &aMem[pOp->p3];
61945 if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
61946 goto no_mem;
61947 }
61948 u.ao.zNewRecord = (u8 *)pOut->z;
61949
@@ -62112,10 +62701,11 @@
62112 }
62113 }
62114 if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
62115 sqlite3ExpirePreparedStatements(db);
62116 sqlite3ResetInternalSchema(db, 0);
 
62117 }
62118 }
62119
62120 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
62121 ** savepoints nested inside of the savepoint being operated on. */
@@ -62502,10 +63092,12 @@
62502 }
62503 if( pOp->p5 ){
62504 assert( u.aw.p2>0 );
62505 assert( u.aw.p2<=p->nMem );
62506 pIn2 = &aMem[u.aw.p2];
 
 
62507 sqlite3VdbeMemIntegerify(pIn2);
62508 u.aw.p2 = (int)pIn2->u.i;
62509 /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
62510 ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
62511 ** If there were a failure, the prepared statement would have halted
@@ -62524,10 +63116,11 @@
62524 }
62525 assert( pOp->p1>=0 );
62526 u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
62527 if( u.aw.pCur==0 ) goto no_mem;
62528 u.aw.pCur->nullRow = 1;
 
62529 rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
62530 u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
62531
62532 /* Since it performs no memory allocation or IO, the only values that
62533 ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
@@ -62576,11 +63169,11 @@
62576 case OP_OpenAutoindex:
62577 case OP_OpenEphemeral: {
62578 #if 0 /* local variables moved into u.ax */
62579 VdbeCursor *pCx;
62580 #endif /* local variables moved into u.ax */
62581 static const int openFlags =
62582 SQLITE_OPEN_READWRITE |
62583 SQLITE_OPEN_CREATE |
62584 SQLITE_OPEN_EXCLUSIVE |
62585 SQLITE_OPEN_DELETEONCLOSE |
62586 SQLITE_OPEN_TRANSIENT_DB;
@@ -62587,25 +63180,25 @@
62587
62588 assert( pOp->p1>=0 );
62589 u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
62590 if( u.ax.pCx==0 ) goto no_mem;
62591 u.ax.pCx->nullRow = 1;
62592 rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
62593 &u.ax.pCx->pBt);
62594 if( rc==SQLITE_OK ){
62595 rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
62596 }
62597 if( rc==SQLITE_OK ){
62598 /* If a transient index is required, create it by calling
62599 ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
62600 ** opening it. If a transient table is required, just use the
62601 ** automatically created table with root-page 1 (an INTKEY table).
62602 */
62603 if( pOp->p4.pKeyInfo ){
62604 int pgno;
62605 assert( pOp->p4type==P4_KEYINFO );
62606 rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
62607 if( rc==SQLITE_OK ){
62608 assert( pgno==MASTER_ROOT+1 );
62609 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
62610 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
62611 u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
@@ -62615,10 +63208,11 @@
62615 }else{
62616 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
62617 u.ax.pCx->isTable = 1;
62618 }
62619 }
 
62620 u.ax.pCx->isIndex = !u.ax.pCx->isTable;
62621 break;
62622 }
62623
62624 /* Opcode: OpenPseudo P1 P2 P3 * *
@@ -62734,10 +63328,11 @@
62734 assert( u.az.pC!=0 );
62735 assert( u.az.pC->pseudoTableReg==0 );
62736 assert( OP_SeekLe == OP_SeekLt+1 );
62737 assert( OP_SeekGe == OP_SeekLt+2 );
62738 assert( OP_SeekGt == OP_SeekLt+3 );
 
62739 if( u.az.pC->pCursor!=0 ){
62740 u.az.oc = pOp->opcode;
62741 u.az.pC->nullRow = 0;
62742 if( u.az.pC->isTable ){
62743 /* The input value in P3 might be of any type: integer, real, string,
@@ -62816,10 +63411,13 @@
62816 assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
62817 assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
62818 assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
62819
62820 u.az.r.aMem = &aMem[pOp->p3];
 
 
 
62821 ExpandBlob(u.az.r.aMem);
62822 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
62823 if( rc!=SQLITE_OK ){
62824 goto abort_due_to_error;
62825 }
@@ -62944,15 +63542,18 @@
62944 assert( u.bb.pC->isTable==0 );
62945 if( pOp->p4.i>0 ){
62946 u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
62947 u.bb.r.nField = (u16)pOp->p4.i;
62948 u.bb.r.aMem = pIn3;
 
 
 
62949 u.bb.r.flags = UNPACKED_PREFIX_MATCH;
62950 u.bb.pIdxKey = &u.bb.r;
62951 }else{
62952 assert( pIn3->flags & MEM_Blob );
62953 ExpandBlob(pIn3);
62954 u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
62955 u.bb.aTempRec, sizeof(u.bb.aTempRec));
62956 if( u.bb.pIdxKey==0 ){
62957 goto no_mem;
62958 }
@@ -63043,10 +63644,13 @@
63043 /* Populate the index search key. */
63044 u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
63045 u.bc.r.nField = u.bc.nField + 1;
63046 u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
63047 u.bc.r.aMem = u.bc.aMx;
 
 
 
63048
63049 /* Extract the value of u.bc.R from register P3. */
63050 sqlite3VdbeMemIntegerify(pIn3);
63051 u.bc.R = pIn3->u.i;
63052
@@ -63065,11 +63669,11 @@
63065
63066 /* Opcode: NotExists P1 P2 P3 * *
63067 **
63068 ** Use the content of register P3 as a integer key. If a record
63069 ** with that key does not exist in table of P1, then jump to P2.
63070 ** If the record does exist, then fall thru. The cursor is left
63071 ** pointing to the record if it exists.
63072 **
63073 ** The difference between this operation and NotFound is that this
63074 ** operation assumes the key is an integer and that P1 is a table whereas
63075 ** NotFound assumes key is a blob constructed from MakeRecord and
@@ -63223,11 +63827,13 @@
63223 u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
63224 }else{
63225 /* Assert that P3 is a valid memory cell. */
63226 assert( pOp->p3<=p->nMem );
63227 u.be.pMem = &aMem[pOp->p3];
 
63228 }
 
63229
63230 REGISTER_TRACE(pOp->p3, u.be.pMem);
63231 sqlite3VdbeMemIntegerify(u.be.pMem);
63232 assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
63233 if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
@@ -63242,33 +63848,40 @@
63242 #endif
63243
63244 sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
63245 }
63246 if( u.be.pC->useRandomRowid ){
63247 /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
63248 ** largest possible integer (9223372036854775807) then the database
63249 ** engine starts picking candidate ROWIDs at random until it finds one
63250 ** that is not previously used.
63251 */
63252 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
63253 ** an AUTOINCREMENT table. */
 
63254 u.be.v = db->lastRowid;
 
 
63255 u.be.cnt = 0;
63256 do{
63257 if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
63258 u.be.v++;
 
 
 
 
 
 
63259 }else{
63260 sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63261 if( u.be.cnt<5 ) u.be.v &= 0xffffff;
63262 }
63263 rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
63264 u.be.cnt++;
63265 }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
63266 if( rc==SQLITE_OK && u.be.res==0 ){
63267 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
63268 goto abort_due_to_error;
63269 }
 
63270 }
63271 u.be.pC->rowidIsValid = 0;
63272 u.be.pC->deferredMoveto = 0;
63273 u.be.pC->cacheStatus = CACHE_STALE;
63274 }
@@ -63334,10 +63947,11 @@
63334 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63335 #endif /* local variables moved into u.bf */
63336
63337 u.bf.pData = &aMem[pOp->p2];
63338 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
 
63339 u.bf.pC = p->apCsr[pOp->p1];
63340 assert( u.bf.pC!=0 );
63341 assert( u.bf.pC->pCursor!=0 );
63342 assert( u.bf.pC->pseudoTableReg==0 );
63343 assert( u.bf.pC->isTable );
@@ -63344,10 +63958,11 @@
63344 REGISTER_TRACE(pOp->p2, u.bf.pData);
63345
63346 if( pOp->opcode==OP_Insert ){
63347 u.bf.pKey = &aMem[pOp->p3];
63348 assert( u.bf.pKey->flags & MEM_Int );
 
63349 REGISTER_TRACE(pOp->p3, u.bf.pKey);
63350 u.bf.iKey = u.bf.pKey->u.i;
63351 }else{
63352 assert( pOp->opcode==OP_InsertInt );
63353 u.bf.iKey = pOp->p3;
@@ -63495,10 +64110,11 @@
63495 u32 n;
63496 i64 n64;
63497 #endif /* local variables moved into u.bh */
63498
63499 pOut = &aMem[pOp->p2];
 
63500
63501 /* Note that RowKey and RowData are really exactly the same instruction */
63502 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63503 u.bh.pC = p->apCsr[pOp->p1];
63504 assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
@@ -63837,10 +64453,13 @@
63837 if( ALWAYS(u.bo.pCrsr!=0) ){
63838 u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
63839 u.bo.r.nField = (u16)pOp->p3;
63840 u.bo.r.flags = 0;
63841 u.bo.r.aMem = &aMem[pOp->p2];
 
 
 
63842 rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
63843 if( rc==SQLITE_OK && u.bo.res==0 ){
63844 rc = sqlite3BtreeDelete(u.bo.pCrsr);
63845 }
63846 assert( u.bo.pC->deferredMoveto==0 );
@@ -63921,10 +64540,11 @@
63921 #endif /* local variables moved into u.bq */
63922
63923 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63924 u.bq.pC = p->apCsr[pOp->p1];
63925 assert( u.bq.pC!=0 );
 
63926 if( ALWAYS(u.bq.pC->pCursor!=0) ){
63927 assert( u.bq.pC->deferredMoveto==0 );
63928 assert( pOp->p5==0 || pOp->p5==1 );
63929 assert( pOp->p4type==P4_INT32 );
63930 u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
@@ -63933,10 +64553,13 @@
63933 u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
63934 }else{
63935 u.bq.r.flags = UNPACKED_IGNORE_ROWID;
63936 }
63937 u.bq.r.aMem = &aMem[pOp->p3];
 
 
 
63938 rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
63939 if( pOp->opcode==OP_IdxLT ){
63940 u.bq.res = -u.bq.res;
63941 }else{
63942 assert( pOp->opcode==OP_IdxGE );
@@ -64036,10 +64659,12 @@
64036 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
64037 );
64038 if( pOp->p3 ){
64039 p->nChange += u.bs.nChange;
64040 if( pOp->p3>0 ){
 
 
64041 aMem[pOp->p3].u.i += u.bs.nChange;
64042 }
64043 }
64044 break;
64045 }
@@ -64079,13 +64704,13 @@
64079 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64080 u.bt.pDb = &db->aDb[pOp->p1];
64081 assert( u.bt.pDb->pBt!=0 );
64082 if( pOp->opcode==OP_CreateTable ){
64083 /* u.bt.flags = BTREE_INTKEY; */
64084 u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
64085 }else{
64086 u.bt.flags = BTREE_ZERODATA;
64087 }
64088 rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
64089 pOut->u.i = u.bt.pgno;
64090 break;
64091 }
@@ -64410,10 +65035,11 @@
64410 void *t; /* Token identifying trigger */
64411 #endif /* local variables moved into u.by */
64412
64413 u.by.pProgram = pOp->p4.pProgram;
64414 u.by.pRt = &aMem[pOp->p3];
 
64415 assert( u.by.pProgram->nOp>0 );
64416
64417 /* If the p5 flag is clear, then recursive invocation of triggers is
64418 ** disabled for backwards compatibility (p5 is set if this sub-program
64419 ** is really a trigger, not a foreign key action, and the flag set
@@ -64583,10 +65209,11 @@
64583 for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
64584 u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
64585 }else{
64586 u.ca.pIn1 = &aMem[pOp->p1];
64587 }
 
64588 sqlite3VdbeMemIntegerify(u.ca.pIn1);
64589 pIn2 = &aMem[pOp->p2];
64590 sqlite3VdbeMemIntegerify(pIn2);
64591 if( u.ca.pIn1->u.i<pIn2->u.i){
64592 u.ca.pIn1->u.i = pIn2->u.i;
@@ -64669,11 +65296,13 @@
64669 assert( u.cb.n>=0 );
64670 u.cb.pRec = &aMem[pOp->p2];
64671 u.cb.apVal = p->apArg;
64672 assert( u.cb.apVal || u.cb.n==0 );
64673 for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
 
64674 u.cb.apVal[u.cb.i] = u.cb.pRec;
 
64675 sqlite3VdbeMemStoreType(u.cb.pRec);
64676 }
64677 u.cb.ctx.pFunc = pOp->p4.pFunc;
64678 assert( pOp->p3>0 && pOp->p3<=p->nMem );
64679 u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
@@ -64689,11 +65318,11 @@
64689 assert( pOp>p->aOp );
64690 assert( pOp[-1].p4type==P4_COLLSEQ );
64691 assert( pOp[-1].opcode==OP_CollSeq );
64692 u.cb.ctx.pColl = pOp[-1].p4.pColl;
64693 }
64694 (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
64695 if( u.cb.ctx.isError ){
64696 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
64697 rc = u.cb.ctx.isError;
64698 }
64699 sqlite3VdbeMemRelease(&u.cb.ctx.s);
@@ -65076,10 +65705,11 @@
65076 #endif /* local variables moved into u.ch */
65077
65078 u.ch.pQuery = &aMem[pOp->p3];
65079 u.ch.pArgc = &u.ch.pQuery[1];
65080 u.ch.pCur = p->apCsr[pOp->p1];
 
65081 REGISTER_TRACE(pOp->p3, u.ch.pQuery);
65082 assert( u.ch.pCur->pVtabCursor );
65083 u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
65084 u.ch.pVtab = u.ch.pVtabCursor->pVtab;
65085 u.ch.pModule = u.ch.pVtab->pModule;
@@ -65133,10 +65763,11 @@
65133
65134 VdbeCursor *pCur = p->apCsr[pOp->p1];
65135 assert( pCur->pVtabCursor );
65136 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65137 u.ci.pDest = &aMem[pOp->p3];
 
65138 if( pCur->nullRow ){
65139 sqlite3VdbeMemSetNull(u.ci.pDest);
65140 break;
65141 }
65142 u.ci.pVtab = pCur->pVtabCursor->pVtab;
@@ -65235,14 +65866,16 @@
65235 #endif /* local variables moved into u.ck */
65236
65237 u.ck.pVtab = pOp->p4.pVtab->pVtab;
65238 u.ck.pName = &aMem[pOp->p1];
65239 assert( u.ck.pVtab->pModule->xRename );
 
65240 REGISTER_TRACE(pOp->p1, u.ck.pName);
65241 assert( u.ck.pName->flags & MEM_Str );
65242 rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
65243 importVtabErrMsg(p, u.ck.pVtab);
 
65244
65245 break;
65246 }
65247 #endif
65248
@@ -65287,10 +65920,12 @@
65287 assert( pOp->p4type==P4_VTAB );
65288 if( ALWAYS(u.cl.pModule->xUpdate) ){
65289 u.cl.apArg = p->apArg;
65290 u.cl.pX = &aMem[pOp->p3];
65291 for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
 
 
65292 sqlite3VdbeMemStoreType(u.cl.pX);
65293 u.cl.apArg[u.cl.i] = u.cl.pX;
65294 u.cl.pX++;
65295 }
65296 rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
@@ -66341,12 +66976,11 @@
66341 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
66342 return pJfd->pMethods==&MemJournalMethods;
66343 }
66344
66345 /*
66346 ** Return the number of bytes required to store a MemJournal that uses vfs
66347 ** pVfs to create the underlying on-disk files.
66348 */
66349 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
66350 return sizeof(MemJournal);
66351 }
66352
@@ -69226,12 +69860,12 @@
69226 return eType;
69227 }
69228 #endif
69229
69230 /*
69231 ** Generate code for scalar subqueries used as an expression
69232 ** and IN operators. Examples:
69233 **
69234 ** (SELECT a FROM b) -- subquery
69235 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
69236 ** x IN (4,5,11) -- IN operator with list on right-hand side
69237 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
@@ -69290,14 +69924,14 @@
69290 assert( testAddr>0 || pParse->db->mallocFailed );
69291 }
69292
69293 switch( pExpr->op ){
69294 case TK_IN: {
69295 char affinity;
69296 KeyInfo keyInfo;
69297 int addr; /* Address of OP_OpenEphemeral instruction */
69298 Expr *pLeft = pExpr->pLeft;
69299
69300 if( rMayHaveNull ){
69301 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
69302 }
69303
@@ -69316,10 +69950,11 @@
69316 ** 'x' nor the SELECT... statement are columns, then numeric affinity
69317 ** is used.
69318 */
69319 pExpr->iTable = pParse->nTab++;
69320 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
 
69321 memset(&keyInfo, 0, sizeof(keyInfo));
69322 keyInfo.nField = 1;
69323
69324 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69325 /* Case 1: expr IN (SELECT ...)
@@ -69924,77 +70559,10 @@
69924 }
69925 return 0;
69926 }
69927 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
69928
69929 /*
69930 ** If the last instruction coded is an ephemeral copy of any of
69931 ** the registers in the nReg registers beginning with iReg, then
69932 ** convert the last instruction from OP_SCopy to OP_Copy.
69933 */
69934 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
69935 VdbeOp *pOp;
69936 Vdbe *v;
69937
69938 assert( pParse->db->mallocFailed==0 );
69939 v = pParse->pVdbe;
69940 assert( v!=0 );
69941 pOp = sqlite3VdbeGetOp(v, -1);
69942 assert( pOp!=0 );
69943 if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
69944 pOp->opcode = OP_Copy;
69945 }
69946 }
69947
69948 /*
69949 ** Generate code to store the value of the iAlias-th alias in register
69950 ** target. The first time this is called, pExpr is evaluated to compute
69951 ** the value of the alias. The value is stored in an auxiliary register
69952 ** and the number of that register is returned. On subsequent calls,
69953 ** the register number is returned without generating any code.
69954 **
69955 ** Note that in order for this to work, code must be generated in the
69956 ** same order that it is executed.
69957 **
69958 ** Aliases are numbered starting with 1. So iAlias is in the range
69959 ** of 1 to pParse->nAlias inclusive.
69960 **
69961 ** pParse->aAlias[iAlias-1] records the register number where the value
69962 ** of the iAlias-th alias is stored. If zero, that means that the
69963 ** alias has not yet been computed.
69964 */
69965 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
69966 #if 0
69967 sqlite3 *db = pParse->db;
69968 int iReg;
69969 if( pParse->nAliasAlloc<pParse->nAlias ){
69970 pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
69971 sizeof(pParse->aAlias[0])*pParse->nAlias );
69972 testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
69973 if( db->mallocFailed ) return 0;
69974 memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
69975 (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
69976 pParse->nAliasAlloc = pParse->nAlias;
69977 }
69978 assert( iAlias>0 && iAlias<=pParse->nAlias );
69979 iReg = pParse->aAlias[iAlias-1];
69980 if( iReg==0 ){
69981 if( pParse->iCacheLevel>0 ){
69982 iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
69983 }else{
69984 iReg = ++pParse->nMem;
69985 sqlite3ExprCode(pParse, pExpr, iReg);
69986 pParse->aAlias[iAlias-1] = iReg;
69987 }
69988 }
69989 return iReg;
69990 #else
69991 UNUSED_PARAMETER(iAlias);
69992 return sqlite3ExprCodeTarget(pParse, pExpr, target);
69993 #endif
69994 }
69995
69996 /*
69997 ** Generate code into the current Vdbe to evaluate the given
69998 ** expression. Attempt to store the results in register "target".
69999 ** Return the register where results are stored.
70000 **
@@ -70099,11 +70667,11 @@
70099 case TK_REGISTER: {
70100 inReg = pExpr->iTable;
70101 break;
70102 }
70103 case TK_AS: {
70104 inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
70105 break;
70106 }
70107 #ifndef SQLITE_OMIT_CAST
70108 case TK_CAST: {
70109 /* Expressions of the form: CAST(pLeft AS token) */
@@ -70531,10 +71099,15 @@
70531 testcase( regFree1==0 );
70532 cacheX.op = TK_REGISTER;
70533 opCompare.op = TK_EQ;
70534 opCompare.pLeft = &cacheX;
70535 pTest = &opCompare;
 
 
 
 
 
70536 }
70537 for(i=0; i<nExpr; i=i+2){
70538 sqlite3ExprCachePush(pParse);
70539 if( pX ){
70540 assert( pTest!=0 );
@@ -70624,14 +71197,18 @@
70624 */
70625 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
70626 int inReg;
70627
70628 assert( target>0 && target<=pParse->nMem );
70629 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
70630 assert( pParse->pVdbe || pParse->db->mallocFailed );
70631 if( inReg!=target && pParse->pVdbe ){
70632 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
 
 
 
 
70633 }
70634 return target;
70635 }
70636
70637 /*
@@ -70800,23 +71377,18 @@
70800 ){
70801 struct ExprList_item *pItem;
70802 int i, n;
70803 assert( pList!=0 );
70804 assert( target>0 );
 
70805 n = pList->nExpr;
70806 for(pItem=pList->a, i=0; i<n; i++, pItem++){
70807 if( pItem->iAlias ){
70808 int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
70809 Vdbe *v = sqlite3GetVdbe(pParse);
70810 if( iReg!=target+i ){
70811 sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
70812 }
70813 }else{
70814 sqlite3ExprCode(pParse, pItem->pExpr, target+i);
70815 }
70816 if( doHardCopy && !pParse->db->mallocFailed ){
70817 sqlite3ExprHardCopy(pParse, target, n);
70818 }
70819 }
70820 return n;
70821 }
70822
@@ -71794,10 +72366,15 @@
71794 if( pTrig->pSchema==pTempSchema ){
71795 zWhere = whereOrName(db, zWhere, pTrig->zName);
71796 }
71797 }
71798 }
 
 
 
 
 
71799 return zWhere;
71800 }
71801
71802 /*
71803 ** Generate code to drop and reload the internal representation of table
@@ -72401,11 +72978,12 @@
72401 int iIdxCur; /* Cursor open on index being analyzed */
72402 Vdbe *v; /* The virtual machine being built up */
72403 int i; /* Loop counter */
72404 int topOfLoop; /* The top of the loop */
72405 int endOfLoop; /* The end of the loop */
72406 int addr; /* The address of an instruction */
 
72407 int iDb; /* Index of database containing pTab */
72408 int regTabname = iMem++; /* Register containing table name */
72409 int regIdxname = iMem++; /* Register containing index name */
72410 int regSampleno = iMem++; /* Register containing next sample number */
72411 int regCol = iMem++; /* Content of a column analyzed table */
@@ -72420,12 +72998,19 @@
72420 int regLast = iMem++; /* Index of last sample to record */
72421 int regFirst = iMem++; /* Index of first sample to record */
72422 #endif
72423
72424 v = sqlite3GetVdbe(pParse);
72425 if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
72426 /* Do no analysis for tables that have no indices */
 
 
 
 
 
 
 
72427 return;
72428 }
72429 assert( sqlite3BtreeHoldsAllMutexes(db) );
72430 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72431 assert( iDb>=0 );
@@ -72438,10 +73023,11 @@
72438
72439 /* Establish a read-lock on the table at the shared-cache level. */
72440 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72441
72442 iIdxCur = pParse->nTab++;
 
72443 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
72444 int nCol = pIdx->nColumn;
72445 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72446
72447 if( iMem+1+(nCol*2)>pParse->nMem ){
@@ -72452,14 +73038,11 @@
72452 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
72453 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
72454 (char *)pKey, P4_KEYINFO_HANDOFF);
72455 VdbeComment((v, "%s", pIdx->zName));
72456
72457 /* Populate the registers containing the table and index names. */
72458 if( pTab->pIndex==pIdx ){
72459 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
72460 }
72461 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
72462
72463 #ifdef SQLITE_ENABLE_STAT2
72464
72465 /* If this iteration of the loop is generating code to analyze the
@@ -72590,12 +73173,14 @@
72590 **
72591 ** If K==0 then no entry is made into the sqlite_stat1 table.
72592 ** If K>0 then it is always the case the D>0 so division by zero
72593 ** is never possible.
72594 */
72595 addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
72596 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
 
 
 
72597 for(i=0; i<nCol; i++){
72598 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
72599 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
72600 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
72601 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
@@ -72605,17 +73190,39 @@
72605 }
72606 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
72607 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
72608 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
72609 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72610 sqlite3VdbeJumpHere(v, addr);
72611 }
72612 }
72613
72614 /*
72615 ** Generate code that will cause the most recent index analysis to
72616 ** be laoded into internal hash tables where is can be used.
72617 */
72618 static void loadAnalysis(Parse *pParse, int iDb){
72619 Vdbe *v = sqlite3GetVdbe(pParse);
72620 if( v ){
72621 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
@@ -72741,37 +73348,50 @@
72741
72742 /*
72743 ** This callback is invoked once for each index when reading the
72744 ** sqlite_stat1 table.
72745 **
72746 ** argv[0] = name of the index
72747 ** argv[1] = results of analysis - on integer for each column
 
 
 
 
72748 */
72749 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
72750 analysisInfo *pInfo = (analysisInfo*)pData;
72751 Index *pIndex;
72752 int i, c;
 
72753 unsigned int v;
72754 const char *z;
72755
72756 assert( argc==2 );
72757 UNUSED_PARAMETER2(NotUsed, argc);
72758
72759 if( argv==0 || argv[0]==0 || argv[1]==0 ){
72760 return 0;
72761 }
72762 pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
72763 if( pIndex==0 ){
72764 return 0;
72765 }
72766 z = argv[1];
72767 for(i=0; *z && i<=pIndex->nColumn; i++){
 
 
 
 
 
 
72768 v = 0;
72769 while( (c=z[0])>='0' && c<='9' ){
72770 v = v*10 + c - '0';
72771 z++;
72772 }
 
 
72773 pIndex->aiRowEst[i] = v;
72774 if( *z==' ' ) z++;
72775 }
72776 return 0;
72777 }
@@ -72843,11 +73463,11 @@
72843 return SQLITE_ERROR;
72844 }
72845
72846 /* Load new statistics out of the sqlite_stat1 table */
72847 zSql = sqlite3MPrintf(db,
72848 "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
72849 if( zSql==0 ){
72850 rc = SQLITE_NOMEM;
72851 }else{
72852 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
72853 sqlite3DbFree(db, zSql);
@@ -73060,13 +73680,12 @@
73060
73061 /* Open the database file. If the btree is successfully opened, use
73062 ** it to obtain the database schema. At this point the schema may
73063 ** or may not be initialised.
73064 */
73065 rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
73066 db->openFlags | SQLITE_OPEN_MAIN_DB,
73067 &aNew->pBt);
73068 db->nDb++;
73069 if( rc==SQLITE_CONSTRAINT ){
73070 rc = SQLITE_ERROR;
73071 zErrDyn = sqlite3MPrintf(db, "database is already attached");
73072 }else if( rc==SQLITE_OK ){
@@ -73303,11 +73922,12 @@
73303 0, /* pNext */
73304 detachFunc, /* xFunc */
73305 0, /* xStep */
73306 0, /* xFinalize */
73307 "sqlite_detach", /* zName */
73308 0 /* pHash */
 
73309 };
73310 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
73311 }
73312
73313 /*
@@ -73324,11 +73944,12 @@
73324 0, /* pNext */
73325 attachFunc, /* xFunc */
73326 0, /* xStep */
73327 0, /* xFinalize */
73328 "sqlite_attach", /* zName */
73329 0 /* pHash */
 
73330 };
73331 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
73332 }
73333 #endif /* SQLITE_OMIT_ATTACH */
73334
@@ -74453,12 +75074,13 @@
74453 ** set to the index of the database that the table or view is to be
74454 ** created in.
74455 */
74456 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
74457 if( iDb<0 ) return;
74458 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
74459 /* If creating a temp table, the name may not be qualified */
 
74460 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
74461 return;
74462 }
74463 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
74464
@@ -74502,21 +75124,22 @@
74502 ** to an sqlite3_declare_vtab() call. In that case only the column names
74503 ** and types will be used, so there is no need to test for namespace
74504 ** collisions.
74505 */
74506 if( !IN_DECLARE_VTAB ){
 
74507 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74508 goto begin_table_error;
74509 }
74510 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
74511 if( pTable ){
74512 if( !noErr ){
74513 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
74514 }
74515 goto begin_table_error;
74516 }
74517 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
74518 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
74519 goto begin_table_error;
74520 }
74521 }
74522
@@ -74529,10 +75152,11 @@
74529 }
74530 pTable->zName = zName;
74531 pTable->iPKey = -1;
74532 pTable->pSchema = db->aDb[iDb].pSchema;
74533 pTable->nRef = 1;
 
74534 assert( pParse->pNewTable==0 );
74535 pParse->pNewTable = pTable;
74536
74537 /* If this is the magic sqlite_sequence table used by autoincrement,
74538 ** then record a pointer to this table in the main database structure
@@ -75375,16 +75999,14 @@
75375 sqlite3SelectDelete(db, pSelect);
75376 return;
75377 }
75378 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
75379 p = pParse->pNewTable;
75380 if( p==0 ){
75381 sqlite3SelectDelete(db, pSelect);
75382 return;
75383 }
75384 assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
75385 ** there could not have been an error */
75386 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75387 iDb = sqlite3SchemaToIndex(db, p->pSchema);
75388 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
75389 && sqlite3FixSelect(&sFix, pSelect)
75390 ){
@@ -76498,11 +77120,12 @@
76498 */
76499 if( pTblName ){
76500 sqlite3RefillIndex(pParse, pIndex, iMem);
76501 sqlite3ChangeCookie(pParse, iDb);
76502 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
76503 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
 
76504 sqlite3VdbeAddOp1(v, OP_Expire, 0);
76505 }
76506 }
76507
76508 /* When adding an index to the list of indices for a table, make
@@ -76559,18 +77182,18 @@
76559 ** are based on typical values found in actual indices.
76560 */
76561 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
76562 unsigned *a = pIdx->aiRowEst;
76563 int i;
 
76564 assert( a!=0 );
76565 a[0] = 1000000;
76566 for(i=pIdx->nColumn; i>=5; i--){
76567 a[i] = 5;
76568 }
76569 while( i>=1 ){
76570 a[i] = 11 - i;
76571 i--;
76572 }
76573 if( pIdx->onError!=OE_None ){
76574 a[pIdx->nColumn] = 1;
76575 }
76576 }
@@ -76626,11 +77249,11 @@
76626 /* Generate code to remove the index and from the master table */
76627 v = sqlite3GetVdbe(pParse);
76628 if( v ){
76629 sqlite3BeginWriteOperation(pParse, 1, iDb);
76630 sqlite3NestedParse(pParse,
76631 "DELETE FROM %Q.%s WHERE name=%Q",
76632 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76633 pIndex->zName
76634 );
76635 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
76636 sqlite3NestedParse(pParse,
@@ -77118,11 +77741,11 @@
77118 SQLITE_OPEN_CREATE |
77119 SQLITE_OPEN_EXCLUSIVE |
77120 SQLITE_OPEN_DELETEONCLOSE |
77121 SQLITE_OPEN_TEMP_DB;
77122
77123 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
77124 if( rc!=SQLITE_OK ){
77125 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
77126 "file for storing temporary tables");
77127 pParse->rc = rc;
77128 return 1;
@@ -77775,11 +78398,11 @@
77775 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
77776 ** functions even if a prior app-defined function was found. And give
77777 ** priority to built-in functions.
77778 **
77779 ** Except, if createFlag is true, that means that we are trying to
77780 ** install a new function. Whatever FuncDef structure is returned will
77781 ** have fields overwritten with new information appropriate for the
77782 ** new function. But the FuncDefs for built-in functions are read-only.
77783 ** So we must not search for built-ins when creating a new function.
77784 */
77785 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
@@ -79956,14 +80579,14 @@
79956 if( caseSensitive ){
79957 pInfo = (struct compareInfo*)&likeInfoAlt;
79958 }else{
79959 pInfo = (struct compareInfo*)&likeInfoNorm;
79960 }
79961 sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79962 sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
79963 sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
79964 (struct compareInfo*)&globInfo, likeFunc, 0,0);
79965 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
79966 setLikeOptFlag(db, "like",
79967 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
79968 }
79969
@@ -80043,14 +80666,14 @@
80043 FUNCTION(upper, 1, 0, 0, upperFunc ),
80044 FUNCTION(lower, 1, 0, 0, lowerFunc ),
80045 FUNCTION(coalesce, 1, 0, 0, 0 ),
80046 FUNCTION(coalesce, 0, 0, 0, 0 ),
80047 /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
80048 {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
80049 FUNCTION(hex, 1, 0, 0, hexFunc ),
80050 /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
80051 {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
80052 FUNCTION(random, 0, 0, 0, randomFunc ),
80053 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
80054 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
80055 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
80056 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
@@ -80073,11 +80696,11 @@
80073 #endif
80074 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
80075 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
80076 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
80077 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
80078 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
80079 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
80080 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
80081 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
80082
80083 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
@@ -80484,11 +81107,11 @@
80484 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80485
80486 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
80487 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
80488 for(i=0; i<nCol; i++){
80489 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
80490 }
80491
80492 /* If the parent table is the same as the child table, and we are about
80493 ** to increment the constraint-counter (i.e. this is an INSERT operation),
80494 ** then check if the row being inserted matches itself. If so, do not
@@ -87131,15 +87754,17 @@
87131 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
87132 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
87133 sqlite3ReleaseTempReg(pParse, r1);
87134 }
87135
 
87136 /*
87137 ** Generate an error message when a SELECT is used within a subexpression
87138 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
87139 ** column. We do this in a subroutine because the error occurs in multiple
87140 ** places.
 
87141 */
87142 static int checkForMultiColumnSelectError(
87143 Parse *pParse, /* Parse context. */
87144 SelectDest *pDest, /* Destination of SELECT results */
87145 int nExpr /* Number of result columns returned by SELECT */
@@ -87151,10 +87776,11 @@
87151 return 1;
87152 }else{
87153 return 0;
87154 }
87155 }
 
87156
87157 /*
87158 ** This routine generates the code for the inside of the inner loop
87159 ** of a SELECT.
87160 **
@@ -87230,14 +87856,10 @@
87230 if( pOrderBy==0 ){
87231 codeOffset(v, p, iContinue);
87232 }
87233 }
87234
87235 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
87236 return;
87237 }
87238
87239 switch( eDest ){
87240 /* In this mode, write each query result to the key of the temporary
87241 ** table iParm.
87242 */
87243 #ifndef SQLITE_OMIT_COMPOUND_SELECT
@@ -88143,10 +88765,11 @@
88143 /* Create the destination temporary table if necessary
88144 */
88145 if( dest.eDest==SRT_EphemTab ){
88146 assert( p->pEList );
88147 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
 
88148 dest.eDest = SRT_Table;
88149 }
88150
88151 /* Make sure all SELECTs in the statement have the same number of elements
88152 ** in their result sets.
@@ -90105,11 +90728,11 @@
90105 ExprList *pList = pF->pExpr->x.pList;
90106 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90107 if( pList ){
90108 nArg = pList->nExpr;
90109 regAgg = sqlite3GetTempRange(pParse, nArg);
90110 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
90111 }else{
90112 nArg = 0;
90113 regAgg = 0;
90114 }
90115 if( pF->iDistinct>=0 ){
@@ -90264,10 +90887,19 @@
90264
90265 /* Begin generating code.
90266 */
90267 v = sqlite3GetVdbe(pParse);
90268 if( v==0 ) goto select_end;
 
 
 
 
 
 
 
 
 
90269
90270 /* Generate code for all sub-queries in the FROM clause
90271 */
90272 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90273 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
@@ -90338,19 +90970,10 @@
90338 }
90339 return multiSelect(pParse, p, pDest);
90340 }
90341 #endif
90342
90343 /* If writing to memory or generating a set
90344 ** only a single column may be output.
90345 */
90346 #ifndef SQLITE_OMIT_SUBQUERY
90347 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90348 goto select_end;
90349 }
90350 #endif
90351
90352 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
90353 ** GROUP BY might use an index, DISTINCT never does.
90354 */
90355 assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
90356 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
@@ -90409,10 +91032,11 @@
90409 assert( isAgg || pGroupBy );
90410 distinct = pParse->nTab++;
90411 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
90412 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
90413 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
 
90414 }else{
90415 distinct = -1;
90416 }
90417
90418 /* Aggregate and non-aggregate queries are handled differently */
@@ -92884,10 +93508,11 @@
92884 ** be stored.
92885 */
92886 assert( v );
92887 ephemTab = pParse->nTab++;
92888 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
 
92889
92890 /* fill the ephemeral table
92891 */
92892 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
92893 sqlite3Select(pParse, pSelect, &dest);
@@ -93022,10 +93647,14 @@
93022 int nDb; /* Number of attached databases */
93023
93024 if( !db->autoCommit ){
93025 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
93026 return SQLITE_ERROR;
 
 
 
 
93027 }
93028
93029 /* Save the current value of the database flags so that it can be
93030 ** restored before returning. Then set the writable-schema flag, and
93031 ** disable CHECK and foreign key constraints. */
@@ -93624,11 +94253,11 @@
93624 sqlite3DbFree(db, zStmt);
93625 v = sqlite3GetVdbe(pParse);
93626 sqlite3ChangeCookie(pParse, iDb);
93627
93628 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93629 zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
93630 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
93631 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
93632 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
93633 }
93634
@@ -94864,15 +95493,16 @@
94864 if( op==TK_REGISTER ){
94865 op = pRight->op2;
94866 }
94867 if( op==TK_VARIABLE ){
94868 Vdbe *pReprepare = pParse->pReprepare;
94869 pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
 
94870 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
94871 z = (char *)sqlite3_value_text(pVal);
94872 }
94873 sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
94874 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
94875 }else if( op==TK_STRING ){
94876 z = pRight->u.zToken;
94877 }
94878 if( z ){
@@ -94886,11 +95516,11 @@
94886 pPrefix = sqlite3Expr(db, TK_STRING, z);
94887 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
94888 *ppPrefix = pPrefix;
94889 if( op==TK_VARIABLE ){
94890 Vdbe *v = pParse->pVdbe;
94891 sqlite3VdbeSetVarmask(v, pRight->iColumn);
94892 if( *pisComplete && pRight->u.zToken[1] ){
94893 /* If the rhs of the LIKE expression is a variable, and the current
94894 ** value of the variable means there is no need to invoke the LIKE
94895 ** function, then no OP_Variable will be added to the program.
94896 ** This causes problems for the sqlite3_bind_parameter_name()
@@ -95900,11 +96530,11 @@
95900 return;
95901 }
95902
95903 assert( pParse->nQueryLoop >= (double)1 );
95904 pTable = pSrc->pTab;
95905 nTableRow = pTable->pIndex ? pTable->pIndex->aiRowEst[0] : 1000000;
95906 logN = estLog(nTableRow);
95907 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
95908 if( costTempIdx>=pCost->rCost ){
95909 /* The cost of creating the transient table would be greater than
95910 ** doing the full table scan */
@@ -96510,11 +97140,11 @@
96510 /* The evalConstExpr() function will have already converted any TK_VARIABLE
96511 ** expression involved in an comparison into a TK_REGISTER. */
96512 assert( pExpr->op!=TK_VARIABLE );
96513 if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
96514 int iVar = pExpr->iColumn;
96515 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
96516 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
96517 return SQLITE_OK;
96518 }
96519 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
96520 }
@@ -96707,27 +97337,18 @@
96707 Index *pFirst; /* Any other index on the table */
96708 memset(&sPk, 0, sizeof(Index));
96709 sPk.nColumn = 1;
96710 sPk.aiColumn = &aiColumnPk;
96711 sPk.aiRowEst = aiRowEstPk;
96712 aiRowEstPk[1] = 1;
96713 sPk.onError = OE_Replace;
96714 sPk.pTable = pSrc->pTab;
 
 
96715 pFirst = pSrc->pTab->pIndex;
96716 if( pSrc->notIndexed==0 ){
96717 sPk.pNext = pFirst;
96718 }
96719 /* The aiRowEstPk[0] is an estimate of the total number of rows in the
96720 ** table. Get this information from the ANALYZE information if it is
96721 ** available. If not available, assume the table 1 million rows in size.
96722 */
96723 if( pFirst ){
96724 assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
96725 aiRowEstPk[0] = pFirst->aiRowEst[0];
96726 }else{
96727 aiRowEstPk[0] = 1000000;
96728 }
96729 pProbe = &sPk;
96730 wsFlagMask = ~(
96731 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
96732 );
96733 eqTermMask = WO_EQ|WO_IN;
@@ -98297,11 +98918,11 @@
98297 ** CREATE TABLE t2(c, d);
98298 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
98299 **
98300 ** The best strategy is to iterate through table t1 first. However it
98301 ** is not possible to determine this with a simple greedy algorithm.
98302 ** However, since the cost of a linear scan through table t2 is the same
98303 ** as the cost of a linear scan through table t1, a simple greedy
98304 ** algorithm may choose to use t2 for the outer loop, which is a much
98305 ** costlier approach.
98306 */
98307 nUnconstrained = 0;
@@ -103366,19 +103987,37 @@
103366
103367 /************** End of sqliteicu.h *******************************************/
103368 /************** Continuing where we left off in main.c ***********************/
103369 #endif
103370
103371 /*
103372 ** The version of the library
103373 */
103374 #ifndef SQLITE_AMALGAMATION
 
 
 
103375 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
103376 #endif
 
 
 
 
103377 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
 
 
 
 
 
103378 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
 
 
 
 
103379 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
 
 
 
 
 
103380 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
103381
103382 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
103383 /*
103384 ** If the following function pointer is not NULL and if
@@ -103495,10 +104134,17 @@
103495 /* Do the rest of the initialization under the recursive mutex so
103496 ** that we will be able to handle recursive calls into
103497 ** sqlite3_initialize(). The recursive calls normally come through
103498 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
103499 ** recursive calls might also be possible.
 
 
 
 
 
 
 
103500 */
103501 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
103502 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
103503 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
103504 sqlite3GlobalConfig.inProgress = 1;
@@ -103775,16 +104421,16 @@
103775 if( cnt<0 ) cnt = 0;
103776 if( sz==0 || cnt==0 ){
103777 sz = 0;
103778 pStart = 0;
103779 }else if( pBuf==0 ){
103780 sz = ROUND8(sz);
103781 sqlite3BeginBenignMalloc();
103782 pStart = sqlite3Malloc( sz*cnt );
103783 sqlite3EndBenignMalloc();
103784 }else{
103785 sz = ROUNDDOWN8(sz);
103786 pStart = pBuf;
103787 }
103788 db->lookaside.pStart = pStart;
103789 db->lookaside.pFree = 0;
103790 db->lookaside.sz = (u16)sz;
@@ -103823,18 +104469,18 @@
103823 va_list ap;
103824 int rc;
103825 va_start(ap, op);
103826 switch( op ){
103827 case SQLITE_DBCONFIG_LOOKASIDE: {
103828 void *pBuf = va_arg(ap, void*);
103829 int sz = va_arg(ap, int);
103830 int cnt = va_arg(ap, int);
103831 rc = setupLookaside(db, pBuf, sz, cnt);
103832 break;
103833 }
103834 default: {
103835 rc = SQLITE_ERROR;
103836 break;
103837 }
103838 }
103839 va_end(ap);
103840 return rc;
@@ -103934,16 +104580,33 @@
103934 }
103935 db->nSavepoint = 0;
103936 db->nStatement = 0;
103937 db->isTransactionSavepoint = 0;
103938 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103939
103940 /*
103941 ** Close an existing SQLite database
103942 */
103943 SQLITE_API int sqlite3_close(sqlite3 *db){
103944 HashElem *i;
103945 int j;
103946
103947 if( !db ){
103948 return SQLITE_OK;
103949 }
@@ -104007,10 +104670,11 @@
104007 for(j=0; j<ArraySize(db->aFunc.a); j++){
104008 FuncDef *pNext, *pHash, *p;
104009 for(p=db->aFunc.a[j]; p; p=pHash){
104010 pHash = p->pHash;
104011 while( p ){
 
104012 pNext = p->pNext;
104013 sqlite3DbFree(db, p);
104014 p = pNext;
104015 }
104016 }
@@ -104281,11 +104945,12 @@
104281 int nArg,
104282 int enc,
104283 void *pUserData,
104284 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104285 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104286 void (*xFinal)(sqlite3_context*)
 
104287 ){
104288 FuncDef *p;
104289 int nName;
104290
104291 assert( sqlite3_mutex_held(db->mutex) );
@@ -104309,14 +104974,14 @@
104309 if( enc==SQLITE_UTF16 ){
104310 enc = SQLITE_UTF16NATIVE;
104311 }else if( enc==SQLITE_ANY ){
104312 int rc;
104313 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
104314 pUserData, xFunc, xStep, xFinal);
104315 if( rc==SQLITE_OK ){
104316 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
104317 pUserData, xFunc, xStep, xFinal);
104318 }
104319 if( rc!=SQLITE_OK ){
104320 return rc;
104321 }
104322 enc = SQLITE_UTF16BE;
@@ -104345,10 +105010,19 @@
104345 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
104346 assert(p || db->mallocFailed);
104347 if( !p ){
104348 return SQLITE_NOMEM;
104349 }
 
 
 
 
 
 
 
 
 
104350 p->flags = 0;
104351 p->xFunc = xFunc;
104352 p->xStep = xStep;
104353 p->xFinalize = xFinal;
104354 p->pUserData = pUserData;
@@ -104359,21 +105033,53 @@
104359 /*
104360 ** Create new user functions.
104361 */
104362 SQLITE_API int sqlite3_create_function(
104363 sqlite3 *db,
104364 const char *zFunctionName,
104365 int nArg,
104366 int enc,
104367 void *p,
104368 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104369 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104370 void (*xFinal)(sqlite3_context*)
104371 ){
104372 int rc;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104373 sqlite3_mutex_enter(db->mutex);
104374 rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104375 rc = sqlite3ApiExit(db, rc);
104376 sqlite3_mutex_leave(db->mutex);
104377 return rc;
104378 }
104379
@@ -104391,11 +105097,11 @@
104391 int rc;
104392 char *zFunc8;
104393 sqlite3_mutex_enter(db->mutex);
104394 assert( !db->mallocFailed );
104395 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
104396 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
104397 sqlite3DbFree(db, zFunc8);
104398 rc = sqlite3ApiExit(db, rc);
104399 sqlite3_mutex_leave(db->mutex);
104400 return rc;
104401 }
@@ -104422,11 +105128,11 @@
104422 int nName = sqlite3Strlen30(zName);
104423 int rc;
104424 sqlite3_mutex_enter(db->mutex);
104425 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
104426 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
104427 0, sqlite3InvalidFunction, 0, 0);
104428 }
104429 rc = sqlite3ApiExit(db, SQLITE_OK);
104430 sqlite3_mutex_leave(db->mutex);
104431 return rc;
104432 }
@@ -104560,11 +105266,14 @@
104560 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
104561 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
104562 ** configured by this function.
104563 */
104564 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
104565 #ifndef SQLITE_OMIT_WAL
 
 
 
104566 if( nFrame>0 ){
104567 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
104568 }else{
104569 sqlite3_wal_hook(db, 0, 0);
104570 }
@@ -104690,64 +105399,10 @@
104690 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
104691 return 0;
104692 #endif
104693 }
104694
104695 /*
104696 ** This routine is called to create a connection to a database BTree
104697 ** driver. If zFilename is the name of a file, then that file is
104698 ** opened and used. If zFilename is the magic name ":memory:" then
104699 ** the database is stored in memory (and is thus forgotten as soon as
104700 ** the connection is closed.) If zFilename is NULL then the database
104701 ** is a "virtual" database for transient use only and is deleted as
104702 ** soon as the connection is closed.
104703 **
104704 ** A virtual database can be either a disk file (that is automatically
104705 ** deleted when the file is closed) or it an be held entirely in memory.
104706 ** The sqlite3TempInMemory() function is used to determine which.
104707 */
104708 SQLITE_PRIVATE int sqlite3BtreeFactory(
104709 sqlite3 *db, /* Main database when opening aux otherwise 0 */
104710 const char *zFilename, /* Name of the file containing the BTree database */
104711 int omitJournal, /* if TRUE then do not journal this file */
104712 int nCache, /* How many pages in the page cache */
104713 int vfsFlags, /* Flags passed through to vfsOpen */
104714 Btree **ppBtree /* Pointer to new Btree object written here */
104715 ){
104716 int btFlags = 0;
104717 int rc;
104718
104719 assert( sqlite3_mutex_held(db->mutex) );
104720 assert( ppBtree != 0);
104721 if( omitJournal ){
104722 btFlags |= BTREE_OMIT_JOURNAL;
104723 }
104724 if( db->flags & SQLITE_NoReadlock ){
104725 btFlags |= BTREE_NO_READLOCK;
104726 }
104727 #ifndef SQLITE_OMIT_MEMORYDB
104728 if( zFilename==0 && sqlite3TempInMemory(db) ){
104729 zFilename = ":memory:";
104730 }
104731 #endif
104732
104733 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
104734 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
104735 }
104736 rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
104737
104738 /* If the B-Tree was successfully opened, set the pager-cache size to the
104739 ** default value. Except, if the call to BtreeOpen() returned a handle
104740 ** open on an existing shared pager-cache, do not change the pager-cache
104741 ** size.
104742 */
104743 if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
104744 sqlite3BtreeSetCacheSize(*ppBtree, nCache);
104745 }
104746 return rc;
104747 }
104748
104749 /*
104750 ** Return UTF-8 encoded English language explanation of the most recent
104751 ** error.
104752 */
104753 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
@@ -104986,21 +105641,43 @@
104986 ** It merely prevents new constructs that exceed the limit
104987 ** from forming.
104988 */
104989 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
104990 int oldLimit;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104991 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
104992 return -1;
104993 }
104994 oldLimit = db->aLimit[limitId];
104995 if( newLimit>=0 ){
104996 if( newLimit>aHardLimit[limitId] ){
104997 newLimit = aHardLimit[limitId];
104998 }
104999 db->aLimit[limitId] = newLimit;
105000 }
105001 return oldLimit;
105002 }
105003
105004 /*
105005 ** This routine does the work of opening a database on behalf of
105006 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
@@ -105019,10 +105696,28 @@
105019 *ppDb = 0;
105020 #ifndef SQLITE_OMIT_AUTOINIT
105021 rc = sqlite3_initialize();
105022 if( rc ) return rc;
105023 #endif
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105024
105025 if( sqlite3GlobalConfig.bCoreMutex==0 ){
105026 isThreadsafe = 0;
105027 }else if( flags & SQLITE_OPEN_NOMUTEX ){
105028 isThreadsafe = 0;
@@ -105053,11 +105748,12 @@
105053 SQLITE_OPEN_MAIN_JOURNAL |
105054 SQLITE_OPEN_TEMP_JOURNAL |
105055 SQLITE_OPEN_SUBJOURNAL |
105056 SQLITE_OPEN_MASTER_JOURNAL |
105057 SQLITE_OPEN_NOMUTEX |
105058 SQLITE_OPEN_FULLMUTEX
 
105059 );
105060
105061 /* Allocate the sqlite data structure */
105062 db = sqlite3MallocZero( sizeof(sqlite3) );
105063 if( db==0 ) goto opendb_out;
@@ -105125,13 +105821,12 @@
105125 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
105126 nocaseCollatingFunc, 0);
105127
105128 /* Open the backend database driver */
105129 db->openFlags = flags;
105130 rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
105131 flags | SQLITE_OPEN_MAIN_DB,
105132 &db->aDb[0].pBt);
105133 if( rc!=SQLITE_OK ){
105134 if( rc==SQLITE_IOERR_NOMEM ){
105135 rc = SQLITE_NOMEM;
105136 }
105137 sqlite3Error(db, rc, 0);
@@ -105833,10 +106528,26 @@
105833 */
105834 case SQLITE_TESTCTRL_PGHDRSZ: {
105835 rc = sizeof(PgHdr);
105836 break;
105837 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105838
105839 }
105840 va_end(ap);
105841 #endif /* SQLITE_OMIT_BUILTIN_TEST */
105842 return rc;
@@ -107022,10 +107733,11 @@
107022 );
107023 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
107024 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
107025 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
107026 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
 
107027
107028 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
107029 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
107030 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
107031 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
@@ -108971,10 +109683,13 @@
108971 zQuery);
108972 }
108973 return rc;
108974 }
108975
 
 
 
108976 rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
108977 pCsr->pNextId = pCsr->aDoclist;
108978 pCsr->iPrevId = 0;
108979 }
108980
@@ -109349,15 +110064,18 @@
109349 static int fts3RenameMethod(
109350 sqlite3_vtab *pVtab, /* Virtual table handle */
109351 const char *zName /* New name of table */
109352 ){
109353 Fts3Table *p = (Fts3Table *)pVtab;
109354 sqlite3 *db; /* Database connection */
109355 int rc; /* Return Code */
109356
109357 db = p->db;
109358 rc = SQLITE_OK;
 
 
 
109359 fts3DbExec(&rc, db,
109360 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
109361 p->zDb, p->zName, zName
109362 );
109363 if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
@@ -112512,10 +113230,40 @@
112512 return SQLITE_CORRUPT;
112513 }
112514 }
112515 return SQLITE_OK;
112516 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112517
112518 /*
112519 ** Set *ppStmt to a statement handle that may be used to iterate through
112520 ** all rows in the %_segdir table, from oldest to newest. If successful,
112521 ** return SQLITE_OK. If an error occurs while preparing the statement,
@@ -116003,10 +116751,49 @@
116003 **
116004 *************************************************************************
116005 ** This file contains code for implementations of the r-tree and r*-tree
116006 ** algorithms packaged as an SQLite virtual table module.
116007 */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116008
116009 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
116010
116011 /*
116012 ** This file contains an implementation of a couple of different variants
@@ -116044,18 +116831,22 @@
116044 #endif
116045 #if VARIANT_RSTARTREE_SPLIT
116046 #define AssignCells splitNodeStartree
116047 #endif
116048
 
 
 
116049
116050 #ifndef SQLITE_CORE
116051 SQLITE_EXTENSION_INIT1
116052 #else
116053 #endif
116054
116055
116056 #ifndef SQLITE_AMALGAMATION
 
116057 typedef sqlite3_int64 i64;
116058 typedef unsigned char u8;
116059 typedef unsigned int u32;
116060 #endif
116061
@@ -116062,10 +116853,12 @@
116062 typedef struct Rtree Rtree;
116063 typedef struct RtreeCursor RtreeCursor;
116064 typedef struct RtreeNode RtreeNode;
116065 typedef struct RtreeCell RtreeCell;
116066 typedef struct RtreeConstraint RtreeConstraint;
 
 
116067 typedef union RtreeCoord RtreeCoord;
116068
116069 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
116070 #define RTREE_MAX_DIMENSIONS 5
116071
@@ -116131,10 +116924,19 @@
116131 */
116132 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
116133 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
116134 #define RTREE_MAXCELLS 51
116135
 
 
 
 
 
 
 
 
 
116136 /*
116137 ** An rtree cursor object.
116138 */
116139 struct RtreeCursor {
116140 sqlite3_vtab_cursor base;
@@ -116163,39 +116965,27 @@
116163
116164 /*
116165 ** A search constraint.
116166 */
116167 struct RtreeConstraint {
116168 int iCoord; /* Index of constrained coordinate */
116169 int op; /* Constraining operation */
116170 double rValue; /* Constraint value. */
 
 
116171 };
116172
116173 /* Possible values for RtreeConstraint.op */
116174 #define RTREE_EQ 0x41
116175 #define RTREE_LE 0x42
116176 #define RTREE_LT 0x43
116177 #define RTREE_GE 0x44
116178 #define RTREE_GT 0x45
 
116179
116180 /*
116181 ** An rtree structure node.
116182 **
116183 ** Data format (RtreeNode.zData):
116184 **
116185 ** 1. If the node is the root node (node 1), then the first 2 bytes
116186 ** of the node contain the tree depth as a big-endian integer.
116187 ** For non-root nodes, the first 2 bytes are left unused.
116188 **
116189 ** 2. The next 2 bytes contain the number of entries currently
116190 ** stored in the node.
116191 **
116192 ** 3. The remainder of the node contains the node entries. Each entry
116193 ** consists of a single 8-byte integer followed by an even number
116194 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
116195 ** of a record. For internal nodes it is the node number of a
116196 ** child page.
116197 */
116198 struct RtreeNode {
116199 RtreeNode *pParent; /* Parent node */
116200 i64 iNode;
116201 int nRef;
@@ -116211,10 +117001,44 @@
116211 struct RtreeCell {
116212 i64 iRowid;
116213 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
116214 };
116215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116216 #ifndef MAX
116217 # define MAX(x,y) ((x) < (y) ? (y) : (x))
116218 #endif
116219 #ifndef MIN
116220 # define MIN(x,y) ((x) > (y) ? (y) : (x))
@@ -116293,14 +117117,12 @@
116293
116294 /*
116295 ** Clear the content of node p (set all bytes to 0x00).
116296 */
116297 static void nodeZero(Rtree *pRtree, RtreeNode *p){
116298 if( p ){
116299 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
116300 p->isDirty = 1;
116301 }
116302 }
116303
116304 /*
116305 ** Given a node number iNode, return the corresponding key to use
116306 ** in the Rtree.aHash table.
@@ -116316,26 +117138,23 @@
116316 ** Search the node hash table for node iNode. If found, return a pointer
116317 ** to it. Otherwise, return 0.
116318 */
116319 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
116320 RtreeNode *p;
116321 assert( iNode!=0 );
116322 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
116323 return p;
116324 }
116325
116326 /*
116327 ** Add node pNode to the node hash table.
116328 */
116329 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
116330 if( pNode ){
116331 int iHash;
116332 assert( pNode->pNext==0 );
116333 iHash = nodeHash(pNode->iNode);
116334 pNode->pNext = pRtree->aHash[iHash];
116335 pRtree->aHash[iHash] = pNode;
116336 }
116337 }
116338
116339 /*
116340 ** Remove node pNode from the node hash table.
116341 */
@@ -116353,15 +117172,15 @@
116353 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
116354 ** indicating that node has not yet been assigned a node number. It is
116355 ** assigned a node number when nodeWrite() is called to write the
116356 ** node contents out to the database.
116357 */
116358 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
116359 RtreeNode *pNode;
116360 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116361 if( pNode ){
116362 memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
116363 pNode->zData = (u8 *)&pNode[1];
116364 pNode->nRef = 1;
116365 pNode->pParent = pParent;
116366 pNode->isDirty = 1;
116367 nodeReference(pParent);
@@ -116378,10 +117197,11 @@
116378 i64 iNode, /* Node number to load */
116379 RtreeNode *pParent, /* Either the parent node or NULL */
116380 RtreeNode **ppNode /* OUT: Acquired node */
116381 ){
116382 int rc;
 
116383 RtreeNode *pNode;
116384
116385 /* Check if the requested node is already in the hash table. If so,
116386 ** increase its reference count and return it.
116387 */
@@ -116394,43 +117214,67 @@
116394 pNode->nRef++;
116395 *ppNode = pNode;
116396 return SQLITE_OK;
116397 }
116398
116399 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
116400 if( !pNode ){
116401 *ppNode = 0;
116402 return SQLITE_NOMEM;
116403 }
116404 pNode->pParent = pParent;
116405 pNode->zData = (u8 *)&pNode[1];
116406 pNode->nRef = 1;
116407 pNode->iNode = iNode;
116408 pNode->isDirty = 0;
116409 pNode->pNext = 0;
116410
116411 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
116412 rc = sqlite3_step(pRtree->pReadNode);
116413 if( rc==SQLITE_ROW ){
116414 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
116415 assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
116416 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
116417 nodeReference(pParent);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116418 }else{
116419 sqlite3_free(pNode);
116420 pNode = 0;
116421 }
116422
116423 *ppNode = pNode;
116424 rc = sqlite3_reset(pRtree->pReadNode);
116425
116426 if( rc==SQLITE_OK && iNode==1 ){
116427 pRtree->iDepth = readInt16(pNode->zData);
116428 }
116429
116430 assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
116431 nodeHashInsert(pRtree, pNode);
116432
116433 return rc;
116434 }
116435
116436 /*
@@ -116479,12 +117323,11 @@
116479 int nMaxCell; /* Maximum number of cells for pNode */
116480
116481 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
116482 nCell = NCELL(pNode);
116483
116484 assert(nCell<=nMaxCell);
116485
116486 if( nCell<nMaxCell ){
116487 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
116488 writeInt16(&pNode->zData[2], nCell+1);
116489 pNode->isDirty = 1;
116490 }
@@ -116700,18 +117543,37 @@
116700 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
116701
116702 return rc;
116703 }
116704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116705 /*
116706 ** Rtree virtual table module xClose method.
116707 */
116708 static int rtreeClose(sqlite3_vtab_cursor *cur){
116709 Rtree *pRtree = (Rtree *)(cur->pVtab);
116710 int rc;
116711 RtreeCursor *pCsr = (RtreeCursor *)cur;
116712 sqlite3_free(pCsr->aConstraint);
116713 rc = nodeRelease(pRtree, pCsr->pNode);
116714 sqlite3_free(pCsr);
116715 return rc;
116716 }
116717
@@ -116723,18 +117585,44 @@
116723 */
116724 static int rtreeEof(sqlite3_vtab_cursor *cur){
116725 RtreeCursor *pCsr = (RtreeCursor *)cur;
116726 return (pCsr->pNode==0);
116727 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116728
116729 /*
116730 ** Cursor pCursor currently points to a cell in a non-leaf page.
116731 ** Return true if the sub-tree headed by the cell is filtered
116732 ** (excluded) by the constraints in the pCursor->aConstraint[]
116733 ** array, or false otherwise.
 
 
 
116734 */
116735 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
116736 RtreeCell cell;
116737 int ii;
116738 int bRes = 0;
116739
116740 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
@@ -116742,56 +117630,92 @@
116742 RtreeConstraint *p = &pCursor->aConstraint[ii];
116743 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
116744 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
116745
116746 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116747 || p->op==RTREE_GT || p->op==RTREE_EQ
116748 );
116749
116750 switch( p->op ){
116751 case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
116752 case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
116753 case RTREE_EQ:
 
 
 
 
 
 
116754 bRes = (p->rValue>cell_max || p->rValue<cell_min);
116755 break;
 
 
 
 
 
 
 
 
 
 
 
116756 }
116757 }
116758
116759 return bRes;
 
116760 }
116761
116762 /*
116763 ** Return true if the cell that cursor pCursor currently points to
116764 ** would be filtered (excluded) by the constraints in the
116765 ** pCursor->aConstraint[] array, or false otherwise.
 
 
 
 
 
116766 **
116767 ** This function assumes that the cell is part of a leaf node.
116768 */
116769 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
116770 RtreeCell cell;
116771 int ii;
 
116772
116773 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
116774 for(ii=0; ii<pCursor->nConstraint; ii++){
116775 RtreeConstraint *p = &pCursor->aConstraint[ii];
116776 double coord = DCOORD(cell.aCoord[p->iCoord]);
116777 int res;
116778 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
116779 || p->op==RTREE_GT || p->op==RTREE_EQ
116780 );
116781 switch( p->op ){
116782 case RTREE_LE: res = (coord<=p->rValue); break;
116783 case RTREE_LT: res = (coord<p->rValue); break;
116784 case RTREE_GE: res = (coord>=p->rValue); break;
116785 case RTREE_GT: res = (coord>p->rValue); break;
116786 case RTREE_EQ: res = (coord==p->rValue); break;
 
 
 
 
 
 
 
 
 
116787 }
116788
116789 if( !res ) return 1;
 
 
 
116790 }
116791
116792 return 0;
116793 }
116794
116795 /*
116796 ** Cursor pCursor currently points at a node that heads a sub-tree of
116797 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
@@ -116814,17 +117738,17 @@
116814 int iSavedCell = pCursor->iCell;
116815
116816 assert( iHeight>=0 );
116817
116818 if( iHeight==0 ){
116819 isEof = testRtreeEntry(pRtree, pCursor);
116820 }else{
116821 isEof = testRtreeCell(pRtree, pCursor);
116822 }
116823 if( isEof || iHeight==0 ){
116824 *pEof = isEof;
116825 return SQLITE_OK;
116826 }
116827
116828 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
116829 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
116830 if( rc!=SQLITE_OK ){
@@ -116856,45 +117780,59 @@
116856
116857 /*
116858 ** One of the cells in node pNode is guaranteed to have a 64-bit
116859 ** integer value equal to iRowid. Return the index of this cell.
116860 */
116861 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
 
 
 
 
 
116862 int ii;
116863 for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
116864 assert( ii<(NCELL(pNode)-1) );
 
 
 
 
116865 }
116866 return ii;
116867 }
116868
116869 /*
116870 ** Return the index of the cell containing a pointer to node pNode
116871 ** in its parent. If pNode is the root node, return -1.
116872 */
116873 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
116874 RtreeNode *pParent = pNode->pParent;
116875 if( pParent ){
116876 return nodeRowidIndex(pRtree, pParent, pNode->iNode);
116877 }
116878 return -1;
 
116879 }
116880
116881 /*
116882 ** Rtree virtual table module xNext method.
116883 */
116884 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
116885 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
116886 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
116887 int rc = SQLITE_OK;
 
 
 
 
 
 
116888
116889 if( pCsr->iStrategy==1 ){
116890 /* This "scan" is a direct lookup by rowid. There is no next entry. */
116891 nodeRelease(pRtree, pCsr->pNode);
116892 pCsr->pNode = 0;
116893 }
116894
116895 else if( pCsr->pNode ){
116896 /* Move to the next entry that matches the configured constraints. */
116897 int iHeight = 0;
116898 while( pCsr->pNode ){
116899 RtreeNode *pNode = pCsr->pNode;
116900 int nCell = NCELL(pNode);
@@ -116904,11 +117842,14 @@
116904 if( rc!=SQLITE_OK || !isEof ){
116905 return rc;
116906 }
116907 }
116908 pCsr->pNode = pNode->pParent;
116909 pCsr->iCell = nodeParentIndex(pRtree, pNode);
 
 
 
116910 nodeReference(pCsr->pNode);
116911 nodeRelease(pRtree, pNode);
116912 iHeight++;
116913 }
116914 }
@@ -116972,10 +117913,55 @@
116972 rc = sqlite3_reset(pRtree->pReadRowid);
116973 }
116974 return rc;
116975 }
116976
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116977
116978 /*
116979 ** Rtree virtual table module xFilter method.
116980 */
116981 static int rtreeFilter(
@@ -116990,22 +117976,22 @@
116990 int ii;
116991 int rc = SQLITE_OK;
116992
116993 rtreeReference(pRtree);
116994
116995 sqlite3_free(pCsr->aConstraint);
116996 pCsr->aConstraint = 0;
116997 pCsr->iStrategy = idxNum;
116998
116999 if( idxNum==1 ){
117000 /* Special case - lookup by rowid. */
117001 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
117002 i64 iRowid = sqlite3_value_int64(argv[0]);
117003 rc = findLeafNode(pRtree, iRowid, &pLeaf);
117004 pCsr->pNode = pLeaf;
117005 if( pLeaf && rc==SQLITE_OK ){
117006 pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
 
117007 }
117008 }else{
117009 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
117010 ** with the configured constraints.
117011 */
@@ -117013,16 +117999,28 @@
117013 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
117014 pCsr->nConstraint = argc;
117015 if( !pCsr->aConstraint ){
117016 rc = SQLITE_NOMEM;
117017 }else{
 
117018 assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
117019 for(ii=0; ii<argc; ii++){
117020 RtreeConstraint *p = &pCsr->aConstraint[ii];
117021 p->op = idxStr[ii*2];
117022 p->iCoord = idxStr[ii*2+1]-'a';
117023 p->rValue = sqlite3_value_double(argv[ii]);
 
 
 
 
 
 
 
 
 
 
 
117024 }
117025 }
117026 }
117027
117028 if( rc==SQLITE_OK ){
@@ -117078,10 +118076,11 @@
117078 ** = 0x41 ('A')
117079 ** <= 0x42 ('B')
117080 ** < 0x43 ('C')
117081 ** >= 0x44 ('D')
117082 ** > 0x45 ('E')
 
117083 ** ----------------------
117084 **
117085 ** The second of each pair of bytes identifies the coordinate column
117086 ** to which the constraint applies. The leftmost coordinate column
117087 ** is 'a', the second from the left 'b' etc.
@@ -117116,43 +118115,47 @@
117116 */
117117 pIdxInfo->estimatedCost = 10.0;
117118 return SQLITE_OK;
117119 }
117120
117121 if( p->usable && p->iColumn>0 ){
 
 
117122 u8 op = 0;
117123 switch( p->op ){
117124 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
117125 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
117126 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
117127 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
117128 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
117129 }
117130 if( op ){
117131 /* Make sure this particular constraint has not been used before.
117132 ** If it has been used before, ignore it.
117133 **
117134 ** A <= or < can be used if there is a prior >= or >.
117135 ** A >= or > can be used if there is a prior < or <=.
117136 ** A <= or < is disqualified if there is a prior <=, <, or ==.
117137 ** A >= or > is disqualified if there is a prior >=, >, or ==.
117138 ** A == is disqualifed if there is any prior constraint.
117139 */
117140 int j, opmsk;
117141 static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
117142 assert( compatible[RTREE_EQ & 7]==0 );
117143 assert( compatible[RTREE_LT & 7]==1 );
117144 assert( compatible[RTREE_LE & 7]==1 );
117145 assert( compatible[RTREE_GT & 7]==2 );
117146 assert( compatible[RTREE_GE & 7]==2 );
117147 cCol = p->iColumn - 1 + 'a';
117148 opmsk = compatible[op & 7];
117149 for(j=0; j<iIdx; j+=2){
117150 if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
117151 op = 0;
117152 break;
117153 }
 
 
117154 }
117155 }
117156 if( op ){
117157 assert( iIdx<sizeof(zIdxStr)-1 );
117158 zIdxStr[iIdx++] = op;
@@ -117256,11 +118259,16 @@
117256 int iExclude
117257 ){
117258 int ii;
117259 float overlap = 0.0;
117260 for(ii=0; ii<nCell; ii++){
117261 if( ii!=iExclude ){
 
 
 
 
 
117262 int jj;
117263 float o = 1.0;
117264 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
117265 double x1;
117266 double x2;
@@ -117349,26 +118357,35 @@
117349 /* Select the child node which will be enlarged the least if pCell
117350 ** is inserted into it. Resolve ties by choosing the entry with
117351 ** the smallest area.
117352 */
117353 for(iCell=0; iCell<nCell; iCell++){
 
117354 float growth;
117355 float area;
117356 float overlap = 0.0;
117357 nodeGetCell(pRtree, pNode, iCell, &cell);
117358 growth = cellGrowth(pRtree, &cell, pCell);
117359 area = cellArea(pRtree, &cell);
 
117360 #if VARIANT_RSTARTREE_CHOOSESUBTREE
117361 if( ii==(pRtree->iDepth-1) ){
117362 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
117363 }
117364 #endif
117365 if( (iCell==0)
117366 || (overlap<fMinOverlap)
117367 || (overlap==fMinOverlap && growth<fMinGrowth)
117368 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
117369 ){
 
 
 
 
 
 
 
 
117370 fMinOverlap = overlap;
117371 fMinGrowth = growth;
117372 fMinArea = area;
117373 iBest = cell.iRowid;
117374 }
@@ -117387,29 +118404,34 @@
117387 /*
117388 ** A cell with the same content as pCell has just been inserted into
117389 ** the node pNode. This function updates the bounding box cells in
117390 ** all ancestor elements.
117391 */
117392 static void AdjustTree(
117393 Rtree *pRtree, /* Rtree table */
117394 RtreeNode *pNode, /* Adjust ancestry of this node. */
117395 RtreeCell *pCell /* This cell was just inserted */
117396 ){
117397 RtreeNode *p = pNode;
117398 while( p->pParent ){
117399 RtreeCell cell;
117400 RtreeNode *pParent = p->pParent;
117401 int iCell = nodeParentIndex(pRtree, p);
 
 
 
 
 
117402
117403 nodeGetCell(pRtree, pParent, iCell, &cell);
117404 if( !cellContains(pRtree, &cell, pCell) ){
117405 cellUnion(pRtree, &cell, pCell);
117406 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
117407 }
117408
117409 p = pParent;
117410 }
 
117411 }
117412
117413 /*
117414 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
117415 */
@@ -117934,18 +118956,18 @@
117934 nodeZero(pRtree, pNode);
117935 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
117936 nCell++;
117937
117938 if( pNode->iNode==1 ){
117939 pRight = nodeNew(pRtree, pNode, 1);
117940 pLeft = nodeNew(pRtree, pNode, 1);
117941 pRtree->iDepth++;
117942 pNode->isDirty = 1;
117943 writeInt16(pNode->zData, pRtree->iDepth);
117944 }else{
117945 pLeft = pNode;
117946 pRight = nodeNew(pRtree, pLeft->pParent, 1);
117947 nodeReference(pLeft);
117948 }
117949
117950 if( !pLeft || !pRight ){
117951 rc = SQLITE_NOMEM;
@@ -117958,12 +118980,16 @@
117958 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
117959 if( rc!=SQLITE_OK ){
117960 goto splitnode_out;
117961 }
117962
117963 /* Ensure both child nodes have node numbers assigned to them. */
117964 if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
 
 
 
 
117965 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
117966 ){
117967 goto splitnode_out;
117968 }
117969
@@ -117975,13 +119001,19 @@
117975 if( rc!=SQLITE_OK ){
117976 goto splitnode_out;
117977 }
117978 }else{
117979 RtreeNode *pParent = pLeft->pParent;
117980 int iCell = nodeParentIndex(pRtree, pLeft);
117981 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
117982 AdjustTree(pRtree, pParent, &leftbbox);
 
 
 
 
 
 
117983 }
117984 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
117985 goto splitnode_out;
117986 }
117987
@@ -118021,44 +119053,73 @@
118021 nodeRelease(pRtree, pLeft);
118022 sqlite3_free(aCell);
118023 return rc;
118024 }
118025
 
 
 
 
 
 
 
 
 
 
 
118026 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
118027 int rc = SQLITE_OK;
118028 if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
118029 sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
118030 if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
118031 i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
118032 rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
118033 }else{
118034 rc = SQLITE_ERROR;
118035 }
118036 sqlite3_reset(pRtree->pReadParent);
118037 if( rc==SQLITE_OK ){
118038 rc = fixLeafParent(pRtree, pLeaf->pParent);
118039 }
 
 
 
 
 
 
 
 
 
 
 
 
118040 }
118041 return rc;
118042 }
118043
118044 static int deleteCell(Rtree *, RtreeNode *, int, int);
118045
118046 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
118047 int rc;
 
118048 RtreeNode *pParent;
118049 int iCell;
118050
118051 assert( pNode->nRef==1 );
118052
118053 /* Remove the entry in the parent cell. */
118054 iCell = nodeParentIndex(pRtree, pNode);
118055 pParent = pNode->pParent;
118056 pNode->pParent = 0;
118057 if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
118058 || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
118059 ){
 
 
 
 
 
118060 return rc;
118061 }
118062
118063 /* Remove the xxx_node entry. */
118064 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
@@ -118084,12 +119145,13 @@
118084 pRtree->pDeleted = pNode;
118085
118086 return SQLITE_OK;
118087 }
118088
118089 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
118090 RtreeNode *pParent = pNode->pParent;
 
118091 if( pParent ){
118092 int ii;
118093 int nCell = NCELL(pNode);
118094 RtreeCell box; /* Bounding box for pNode */
118095 nodeGetCell(pRtree, pNode, 0, &box);
@@ -118097,21 +119159,25 @@
118097 RtreeCell cell;
118098 nodeGetCell(pRtree, pNode, ii, &cell);
118099 cellUnion(pRtree, &box, &cell);
118100 }
118101 box.iRowid = pNode->iNode;
118102 ii = nodeParentIndex(pRtree, pNode);
118103 nodeOverwriteCell(pRtree, pParent, &box, ii);
118104 fixBoundingBox(pRtree, pParent);
 
 
118105 }
 
118106 }
118107
118108 /*
118109 ** Delete the cell at index iCell of node pNode. After removing the
118110 ** cell, adjust the r-tree data structure if required.
118111 */
118112 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
 
118113 int rc;
118114
118115 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
118116 return rc;
118117 }
@@ -118124,18 +119190,17 @@
118124 /* If the node is not the tree root and now has less than the minimum
118125 ** number of cells, remove it from the tree. Otherwise, update the
118126 ** cell in the parent node so that it tightly contains the updated
118127 ** node.
118128 */
118129 if( pNode->iNode!=1 ){
118130 RtreeNode *pParent = pNode->pParent;
118131 if( (pParent->iNode!=1 || NCELL(pParent)!=1)
118132 && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
118133 ){
118134 rc = removeNode(pRtree, pNode, iHeight);
118135 }else{
118136 fixBoundingBox(pRtree, pNode);
118137 }
118138 }
118139
118140 return rc;
118141 }
@@ -118214,11 +119279,11 @@
118214 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
118215 }
118216 }
118217 }
118218 if( rc==SQLITE_OK ){
118219 fixBoundingBox(pRtree, pNode);
118220 }
118221 for(; rc==SQLITE_OK && ii<nCell; ii++){
118222 /* Find a node to store this cell in. pNode->iNode currently contains
118223 ** the height of the sub-tree headed by the cell.
118224 */
@@ -118268,15 +119333,17 @@
118268 }
118269 #else
118270 rc = SplitNode(pRtree, pNode, pCell, iHeight);
118271 #endif
118272 }else{
118273 AdjustTree(pRtree, pNode, pCell);
118274 if( iHeight==0 ){
118275 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
118276 }else{
118277 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
 
 
118278 }
118279 }
118280 return rc;
118281 }
118282
@@ -118342,11 +119409,10 @@
118342 int rc = SQLITE_OK;
118343
118344 rtreeReference(pRtree);
118345
118346 assert(nData>=1);
118347 assert(hashIsEmpty(pRtree));
118348
118349 /* If azData[0] is not an SQL NULL value, it is the rowid of a
118350 ** record to delete from the r-tree table. The following block does
118351 ** just that.
118352 */
@@ -118368,12 +119434,14 @@
118368 }
118369
118370 /* Delete the cell in question from the leaf node. */
118371 if( rc==SQLITE_OK ){
118372 int rc2;
118373 iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
118374 rc = deleteCell(pRtree, pLeaf, iCell, 0);
 
 
118375 rc2 = nodeRelease(pRtree, pLeaf);
118376 if( rc==SQLITE_OK ){
118377 rc = rc2;
118378 }
118379 }
@@ -118391,23 +119459,24 @@
118391 **
118392 ** This is equivalent to copying the contents of the child into
118393 ** the root node (the operation that Gutman's paper says to perform
118394 ** in this scenario).
118395 */
118396 if( rc==SQLITE_OK && pRtree->iDepth>0 ){
118397 if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
118398 RtreeNode *pChild;
118399 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
118400 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
118401 if( rc==SQLITE_OK ){
118402 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
118403 }
118404 if( rc==SQLITE_OK ){
118405 pRtree->iDepth--;
118406 writeInt16(pRoot->zData, pRtree->iDepth);
118407 pRoot->isDirty = 1;
118408 }
 
118409 }
118410 }
118411
118412 /* Re-insert the contents of any underfull nodes removed from the tree. */
118413 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
@@ -118693,11 +119762,11 @@
118693 ){
118694 int rc = SQLITE_OK;
118695 Rtree *pRtree;
118696 int nDb; /* Length of string argv[1] */
118697 int nName; /* Length of string argv[2] */
118698 int eCoordType = (int)pAux;
118699
118700 const char *aErrMsg[] = {
118701 0, /* 0 */
118702 "Wrong number of columns for an rtree table", /* 1 */
118703 "Too few columns for an rtree table", /* 2 */
@@ -118839,16 +119908,14 @@
118839 ** Register the r-tree module with database handle db. This creates the
118840 ** virtual table module "rtree" and the debugging/analysis scalar
118841 ** function "rtreenode".
118842 */
118843 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
118844 int rc = SQLITE_OK;
 
118845
118846 if( rc==SQLITE_OK ){
118847 int utf8 = SQLITE_UTF8;
118848 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
118849 }
118850 if( rc==SQLITE_OK ){
118851 int utf8 = SQLITE_UTF8;
118852 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
118853 }
118854 if( rc==SQLITE_OK ){
@@ -118860,10 +119927,74 @@
118860 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
118861 }
118862
118863 return rc;
118864 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118865
118866 #if !SQLITE_CORE
118867 SQLITE_API int sqlite3_extension_init(
118868 sqlite3 *db,
118869 char **pzErrMsg,
118870
--- 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.7.3. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a one 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% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
@@ -352,19 +352,25 @@
352 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X) ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe. 1 means the library is serialized which is the highest
360 ** level of threadsafety. 2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
@@ -642,13 +648,13 @@
648 **
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
652 */
653 #define SQLITE_VERSION "3.7.3"
654 #define SQLITE_VERSION_NUMBER 3007003
655 #define SQLITE_SOURCE_ID "2010-09-29 23:09:23 1ef0dc9328f47506cb2dcd142150e96cb4755216"
656
657 /*
658 ** CAPI3REF: Run-Time Library Version Numbers
659 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
660 **
@@ -1292,19 +1298,23 @@
1298 ** object once the object has been registered.
1299 **
1300 ** The zName field holds the name of the VFS module. The name must
1301 ** be unique across all VFS modules.
1302 **
1303 ** ^SQLite guarantees that the zFilename parameter to xOpen
1304 ** is either a NULL pointer or string obtained
1305 ** from xFullPathname() with an optional suffix added.
1306 ** ^If a suffix is added to the zFilename parameter, it will
1307 ** consist of a single "-" character followed by no more than
1308 ** 10 alphanumeric and/or "-" characters.
1309 ** ^SQLite further guarantees that
1310 ** the string will be valid and unchanged until xClose() is
1311 ** called. Because of the previous sentence,
1312 ** the [sqlite3_file] can safely store a pointer to the
1313 ** filename if it needs to remember the filename for some reason.
1314 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1315 ** must invent its own temporary name for the file. ^Whenever the
1316 ** xFilename parameter is NULL it will also be the case that the
1317 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1318 **
1319 ** The flags argument to xOpen() includes all bits set in
1320 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -1311,11 +1321,11 @@
1321 ** or [sqlite3_open16()] is used, then flags includes at least
1322 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1323 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1324 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1325 **
1326 ** ^(SQLite will also add one of the following flags to the xOpen()
1327 ** call, depending on the object being opened:
1328 **
1329 ** <ul>
1330 ** <li> [SQLITE_OPEN_MAIN_DB]
1331 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -1322,11 +1332,12 @@
1332 ** <li> [SQLITE_OPEN_TEMP_DB]
1333 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1334 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1335 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1336 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1337 ** <li> [SQLITE_OPEN_WAL]
1338 ** </ul>)^
1339 **
1340 ** The file I/O implementation can use the object type flags to
1341 ** change the way it deals with files. For example, an application
1342 ** that does not care about crash recovery or rollback might make
1343 ** the open of a journal file a no-op. Writes to this journal would
@@ -1341,39 +1352,40 @@
1352 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1353 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1354 ** </ul>
1355 **
1356 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1357 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1358 ** will be set for TEMP databases and their journals, transient
1359 ** databases, and subjournals.
1360 **
1361 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1362 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1363 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1364 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1365 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1366 ** be created, and that it is an error if it already exists.
1367 ** It is <i>not</i> used to indicate the file should be opened
1368 ** for exclusive access.
1369 **
1370 ** ^At least szOsFile bytes of memory are allocated by SQLite
1371 ** to hold the [sqlite3_file] structure passed as the third
1372 ** argument to xOpen. The xOpen method does not have to
1373 ** allocate the structure; it should just fill it in. Note that
1374 ** the xOpen method must set the sqlite3_file.pMethods to either
1375 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1376 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1377 ** element will be valid after xOpen returns regardless of the success
1378 ** or failure of the xOpen call.
1379 **
1380 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1381 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1382 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1383 ** to test whether a file is at least readable. The file can be a
1384 ** directory.
1385 **
1386 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1387 ** output buffer xFullPathname. The exact size of the output buffer
1388 ** is also passed as a parameter to both methods. If the output buffer
1389 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1390 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1391 ** to prevent this by setting mxPathname to a sufficiently large value.
@@ -1383,14 +1395,14 @@
1395 ** included in the VFS structure for completeness.
1396 ** The xRandomness() function attempts to return nBytes bytes
1397 ** of good-quality randomness into zOut. The return value is
1398 ** the actual number of bytes of randomness obtained.
1399 ** The xSleep() method causes the calling thread to sleep for at
1400 ** least the number of microseconds given. ^The xCurrentTime()
1401 ** method returns a Julian Day Number for the current date and time as
1402 ** a floating point value.
1403 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1404 ** Day Number multipled by 86400000 (the number of milliseconds in
1405 ** a 24-hour day).
1406 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1407 ** date and time if that method is available (if iVersion is 2 or
1408 ** greater and the function pointer is not NULL) and will fall back
@@ -1783,11 +1795,11 @@
1795 ** statistics. ^(When memory allocation statistics are disabled, the
1796 ** following SQLite interfaces become non-operational:
1797 ** <ul>
1798 ** <li> [sqlite3_memory_used()]
1799 ** <li> [sqlite3_memory_highwater()]
1800 ** <li> [sqlite3_soft_heap_limit64()]
1801 ** <li> [sqlite3_status()]
1802 ** </ul>)^
1803 ** ^Memory allocation statistics are enabled by default unless SQLite is
1804 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1805 ** allocation statistics are disabled by default.
@@ -1797,19 +1809,18 @@
1809 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1810 ** scratch memory. There are three arguments: A pointer an 8-byte
1811 ** aligned memory buffer from which the scrach allocations will be
1812 ** drawn, the size of each scratch allocation (sz),
1813 ** and the maximum number of scratch allocations (N). The sz
1814 ** argument must be a multiple of 16.
 
1815 ** The first argument must be a pointer to an 8-byte aligned buffer
1816 ** of at least sz*N bytes of memory.
1817 ** ^SQLite will use no more than two scratch buffers per thread. So
1818 ** N should be set to twice the expected maximum number of threads.
1819 ** ^SQLite will never require a scratch buffer that is more than 6
1820 ** times the database page size. ^If SQLite needs needs additional
1821 ** scratch memory beyond what is provided by this configuration option, then
1822 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1823 **
1824 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1825 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1826 ** the database page cache with the default page cache implemenation.
@@ -1825,12 +1836,11 @@
1836 ** argument should point to an allocation of at least sz*N bytes of memory.
1837 ** ^SQLite will use the memory provided by the first argument to satisfy its
1838 ** memory needs for the first N pages that it adds to cache. ^If additional
1839 ** page cache memory is needed beyond what is provided by this option, then
1840 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1841 ** The pointer in the first argument must
 
1842 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1843 ** will be undefined.</dd>
1844 **
1845 ** <dt>SQLITE_CONFIG_HEAP</dt>
1846 ** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1955,12 +1965,18 @@
1965 ** size of each lookaside buffer slot. ^The third argument is the number of
1966 ** slots. The size of the buffer in the first argument must be greater than
1967 ** or equal to the product of the second and third arguments. The buffer
1968 ** must be aligned to an 8-byte boundary. ^If the second argument to
1969 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1970 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1971 ** configuration for a database connection can only be changed when that
1972 ** connection is not currently using lookaside memory, or in other words
1973 ** when the "current value" returned by
1974 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1975 ** Any attempt to change the lookaside memory configuration when lookaside
1976 ** memory is in use leaves the configuration unchanged and returns
1977 ** [SQLITE_BUSY].)^</dd>
1978 **
1979 ** </dl>
1980 */
1981 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1982
@@ -2260,10 +2276,13 @@
2276 */
2277 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2278
2279 /*
2280 ** CAPI3REF: Convenience Routines For Running Queries
2281 **
2282 ** This is a legacy interface that is preserved for backwards compatibility.
2283 ** Use of this interface is not recommended.
2284 **
2285 ** Definition: A <b>result table</b> is memory data structure created by the
2286 ** [sqlite3_get_table()] interface. A result table records the
2287 ** complete query results from one or more queries.
2288 **
@@ -2281,11 +2300,11 @@
2300 **
2301 ** A result table might consist of one or more memory allocations.
2302 ** It is not safe to pass a result table directly to [sqlite3_free()].
2303 ** A result table should be deallocated using [sqlite3_free_table()].
2304 **
2305 ** ^(As an example of the result table format, suppose a query result
2306 ** is as follows:
2307 **
2308 ** <blockquote><pre>
2309 ** Name | Age
2310 ** -----------------------
@@ -2305,31 +2324,31 @@
2324 ** azResult&#91;3] = "43";
2325 ** azResult&#91;4] = "Bob";
2326 ** azResult&#91;5] = "28";
2327 ** azResult&#91;6] = "Cindy";
2328 ** azResult&#91;7] = "21";
2329 ** </pre></blockquote>)^
2330 **
2331 ** ^The sqlite3_get_table() function evaluates one or more
2332 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2333 ** string of its 2nd parameter and returns a result table to the
2334 ** pointer given in its 3rd parameter.
2335 **
2336 ** After the application has finished with the result from sqlite3_get_table(),
2337 ** it must pass the result table pointer to sqlite3_free_table() in order to
2338 ** release the memory that was malloced. Because of the way the
2339 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2340 ** function must not try to call [sqlite3_free()] directly. Only
2341 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2342 **
2343 ** The sqlite3_get_table() interface is implemented as a wrapper around
2344 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2345 ** to any internal data structures of SQLite. It uses only the public
2346 ** interface defined here. As a consequence, errors that occur in the
2347 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2348 ** reflected in subsequent calls to [sqlite3_errcode()] or
2349 ** [sqlite3_errmsg()].
2350 */
2351 SQLITE_API int sqlite3_get_table(
2352 sqlite3 *db, /* An open database */
2353 const char *zSql, /* SQL to be evaluated */
2354 char ***pazResult, /* Results of the query */
@@ -2477,11 +2496,13 @@
2496 ** by sqlite3_realloc() and the prior allocation is freed.
2497 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2498 ** is not freed.
2499 **
2500 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2501 ** is always aligned to at least an 8 byte boundary, or to a
2502 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2503 ** option is used.
2504 **
2505 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2506 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2507 ** implementation of these routines to be omitted. That capability
2508 ** is no longer provided. Only built-in memory allocators can be used.
@@ -2735,21 +2756,32 @@
2756 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2757
2758 /*
2759 ** CAPI3REF: Query Progress Callbacks
2760 **
2761 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2762 ** function X to be invoked periodically during long running calls to
2763 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2764 ** database connection D. An example use for this
2765 ** interface is to keep a GUI updated during a large query.
2766 **
2767 ** ^The parameter P is passed through as the only parameter to the
2768 ** callback function X. ^The parameter N is the number of
2769 ** [virtual machine instructions] that are evaluated between successive
2770 ** invocations of the callback X.
2771 **
2772 ** ^Only a single progress handler may be defined at one time per
2773 ** [database connection]; setting a new progress handler cancels the
2774 ** old one. ^Setting parameter X to NULL disables the progress handler.
2775 ** ^The progress handler is also disabled by setting N to a value less
2776 ** than 1.
2777 **
2778 ** ^If the progress callback returns non-zero, the operation is
2779 ** interrupted. This feature can be used to implement a
2780 ** "Cancel" button on a GUI progress dialog box.
2781 **
2782 ** The progress handler callback must not do anything that will modify
2783 ** the database connection that invoked the progress handler.
2784 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2785 ** database connections for the meaning of "modify" in this paragraph.
2786 **
2787 */
@@ -2804,11 +2836,11 @@
2836 ** </dl>
2837 **
2838 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2839 ** combinations shown above or one of the combinations shown above combined
2840 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2841 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2842 ** then the behavior is undefined.
2843 **
2844 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2845 ** opens in the multi-thread [threading mode] as long as the single-thread
2846 ** mode has not been set at compile-time or start-time. ^If the
@@ -2929,21 +2961,26 @@
2961 ** ^(This interface allows the size of various constructs to be limited
2962 ** on a connection by connection basis. The first parameter is the
2963 ** [database connection] whose limit is to be set or queried. The
2964 ** second parameter is one of the [limit categories] that define a
2965 ** class of constructs to be size limited. The third parameter is the
2966 ** new limit for that construct.)^
2967 **
2968 ** ^If the new limit is a negative number, the limit is unchanged.
2969 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
2970 ** [limits | hard upper bound]
2971 ** set at compile-time by a C preprocessor macro called
2972 ** [limits | SQLITE_MAX_<i>NAME</i>].
2973 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2974 ** ^Attempts to increase a limit above its hard upper bound are
2975 ** silently truncated to the hard upper bound.
2976 **
2977 ** ^Regardless of whether or not the limit was changed, the
2978 ** [sqlite3_limit()] interface returns the prior value of the limit.
2979 ** ^Hence, to find the current value of a limit without changing it,
2980 ** simply invoke this interface with the third parameter set to -1.
2981 **
2982 ** Run-time limits are intended for use in applications that manage
2983 ** both their own internal database and also databases that are controlled
2984 ** by untrusted external sources. An example application might be a
2985 ** web browser that has its own databases for storing history and
2986 ** separate databases controlled by JavaScript applications downloaded
@@ -2968,11 +3005,11 @@
3005 ** The synopsis of the meanings of the various limits is shown below.
3006 ** Additional information is available at [limits | Limits in SQLite].
3007 **
3008 ** <dl>
3009 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3010 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3011 **
3012 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3013 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3014 **
3015 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2986,11 +3023,13 @@
3023 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3024 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3025 **
3026 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3027 ** <dd>The maximum number of instructions in a virtual machine program
3028 ** used to implement an SQL statement. This limit is not currently
3029 ** enforced, though that might be added in some future release of
3030 ** SQLite.</dd>)^
3031 **
3032 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3033 ** <dd>The maximum number of arguments on a function.</dd>)^
3034 **
3035 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2999,12 +3038,11 @@
3038 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3039 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3040 ** [GLOB] operators.</dd>)^
3041 **
3042 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3043 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
 
3044 **
3045 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3046 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3047 ** </dl>
3048 */
@@ -3072,16 +3110,11 @@
3110 **
3111 ** <ol>
3112 ** <li>
3113 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3114 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3115 ** statement and try to run it again.
 
 
 
 
 
3116 ** </li>
3117 **
3118 ** <li>
3119 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3120 ** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -3090,15 +3123,20 @@
3123 ** in order to find the underlying cause of the problem. With the "v2" prepare
3124 ** interfaces, the underlying reason for the error is returned immediately.
3125 ** </li>
3126 **
3127 ** <li>
3128 ** ^If the specific value bound to [parameter | host parameter] in the
3129 ** WHERE clause might influence the choice of query plan for a statement,
3130 ** then the statement will be automatically recompiled, as if there had been
3131 ** a schema change, on the first [sqlite3_step()] call following any change
3132 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3133 ** ^The specific value of WHERE-clause [parameter] might influence the
3134 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3135 ** or [GLOB] operator or if the parameter is compared to an indexed column
3136 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3137 ** the
3138 ** </li>
3139 ** </ol>
3140 */
3141 SQLITE_API int sqlite3_prepare(
3142 sqlite3 *db, /* Database handle */
@@ -3161,11 +3199,11 @@
3199 ** or if SQLite is run in one of reduced mutex modes
3200 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3201 ** then there is no distinction between protected and unprotected
3202 ** sqlite3_value objects and they can be used interchangeably. However,
3203 ** for maximum code portability it is recommended that applications
3204 ** still make the distinction between protected and unprotected
3205 ** sqlite3_value objects even when not strictly required.
3206 **
3207 ** ^The sqlite3_value objects that are passed as parameters into the
3208 ** implementation of [application-defined SQL functions] are protected.
3209 ** ^The sqlite3_value object returned by
@@ -3356,10 +3394,12 @@
3394 ** CAPI3REF: Number Of Columns In A Result Set
3395 **
3396 ** ^Return the number of columns in the result set returned by the
3397 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3398 ** statement that does not return data (for example an [UPDATE]).
3399 **
3400 ** See also: [sqlite3_data_count()]
3401 */
3402 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3403
3404 /*
3405 ** CAPI3REF: Column Names In A Result Set
@@ -3546,12 +3586,18 @@
3586 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3587
3588 /*
3589 ** CAPI3REF: Number of columns in a result set
3590 **
3591 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3592 ** current row of the result set of [prepared statement] P.
3593 ** ^If prepared statement P does not have results ready to return
3594 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3595 ** interfaces) then sqlite3_data_count(P) returns 0.
3596 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3597 **
3598 ** See also: [sqlite3_column_count()]
3599 */
3600 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3601
3602 /*
3603 ** CAPI3REF: Fundamental Datatypes
@@ -3627,22 +3673,30 @@
3673 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3674 ** the string to UTF-8 and then returns the number of bytes.
3675 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3676 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3677 ** the number of bytes in that string.
3678 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3679 **
3680 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3681 ** routine returns the number of bytes in that BLOB or string.
3682 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3683 ** the string to UTF-16 and then returns the number of bytes.
3684 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3685 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3686 ** the number of bytes in that string.
3687 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3688 **
3689 ** ^The values returned by [sqlite3_column_bytes()] and
3690 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3691 ** of the string. ^For clarity: the values returned by
3692 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3693 ** bytes in the string, not the number of characters.
3694 **
3695 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3696 ** even empty strings, are always zero terminated. ^The return
3697 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
 
 
 
 
 
3698 **
3699 ** ^The object returned by [sqlite3_column_value()] is an
3700 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3701 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3702 ** If the [unprotected sqlite3_value] object returned by
@@ -3683,14 +3737,14 @@
3737 ** and atof(). SQLite does not really use these functions. It has its
3738 ** own equivalent internal routines. The atoi() and atof() names are
3739 ** used in the table for brevity and because they are familiar to most
3740 ** C programmers.
3741 **
3742 ** Note that when type conversions occur, pointers returned by prior
3743 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3744 ** sqlite3_column_text16() may be invalidated.
3745 ** Type conversions and pointer invalidations might occur
3746 ** in the following cases:
3747 **
3748 ** <ul>
3749 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3750 ** sqlite3_column_text16() is called. A zero-terminator might
@@ -3699,26 +3753,26 @@
3753 ** sqlite3_column_text16() is called. The content must be converted
3754 ** to UTF-16.</li>
3755 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3756 ** sqlite3_column_text() is called. The content must be converted
3757 ** to UTF-8.</li>
3758 ** </ul>
3759 **
3760 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3761 ** not invalidate a prior pointer, though of course the content of the buffer
3762 ** that the prior pointer references will have been modified. Other kinds
3763 ** of conversion are done in place when it is possible, but sometimes they
3764 ** are not possible and in those cases prior pointers are invalidated.
3765 **
3766 ** The safest and easiest to remember policy is to invoke these routines
3767 ** in one of the following ways:
3768 **
3769 ** <ul>
3770 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3771 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3772 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3773 ** </ul>
3774 **
3775 ** In other words, you should call sqlite3_column_text(),
3776 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3777 ** into the desired format, then invoke sqlite3_column_bytes() or
3778 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3752,21 +3806,30 @@
3806
3807 /*
3808 ** CAPI3REF: Destroy A Prepared Statement Object
3809 **
3810 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3811 ** ^If the most recent evaluation of the statement encountered no errors or
3812 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3813 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3814 ** sqlite3_finalize(S) returns the appropriate [error code] or
3815 ** [extended error code].
3816 **
3817 ** ^The sqlite3_finalize(S) routine can be called at any point during
3818 ** the life cycle of [prepared statement] S:
3819 ** before statement S is ever evaluated, after
3820 ** one or more calls to [sqlite3_reset()], or after any call
3821 ** to [sqlite3_step()] regardless of whether or not the statement has
3822 ** completed execution.
3823 **
3824 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3825 **
3826 ** The application must finalize every [prepared statement] in order to avoid
3827 ** resource leaks. It is a grievous error for the application to try to use
3828 ** a prepared statement after it has been finalized. Any use of a prepared
3829 ** statement after it has been finalized can result in undefined and
3830 ** undesirable behavior such as segfaults and heap corruption.
3831 */
3832 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3833
3834 /*
3835 ** CAPI3REF: Reset A Prepared Statement Object
@@ -3798,40 +3861,42 @@
3861 ** CAPI3REF: Create Or Redefine SQL Functions
3862 ** KEYWORDS: {function creation routines}
3863 ** KEYWORDS: {application-defined SQL function}
3864 ** KEYWORDS: {application-defined SQL functions}
3865 **
3866 ** ^These functions (collectively known as "function creation routines")
3867 ** are used to add SQL functions or aggregates or to redefine the behavior
3868 ** of existing SQL functions or aggregates. The only differences between
3869 ** these routines are the text encoding expected for
3870 ** the the second parameter (the name of the function being created)
3871 ** and the presence or absence of a destructor callback for
3872 ** the application data pointer.
3873 **
3874 ** ^The first parameter is the [database connection] to which the SQL
3875 ** function is to be added. ^If an application uses more than one database
3876 ** connection then application-defined SQL functions must be added
3877 ** to each database connection separately.
3878 **
3879 ** ^The second parameter is the name of the SQL function to be created or
3880 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
3881 ** representation, exclusive of the zero-terminator. ^Note that the name
3882 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
3883 ** ^Any attempt to create a function with a longer name
3884 ** will result in [SQLITE_MISUSE] being returned.
3885 **
3886 ** ^The third parameter (nArg)
3887 ** is the number of arguments that the SQL function or
3888 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3889 ** aggregate may take any number of arguments between 0 and the limit
3890 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
3891 ** parameter is less than -1 or greater than 127 then the behavior is
3892 ** undefined.
3893 **
3894 ** ^The fourth parameter, eTextRep, specifies what
3895 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3896 ** its parameters. Every SQL function implementation must be able to work
3897 ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3898 ** more efficient with one encoding than another. ^An application may
3899 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3900 ** times with the same function but with different values of eTextRep.
3901 ** ^When multiple implementations of the same function are available, SQLite
3902 ** will pick the one that involves the least amount of data conversion.
@@ -3839,17 +3904,25 @@
3904 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3905 **
3906 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
3907 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3908 **
3909 ** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3910 ** pointers to C-language functions that implement the SQL function or
3911 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3912 ** callback only; NULL pointers must be passed as the xStep and xFinal
3913 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3914 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3915 ** SQL function or aggregate, pass NULL poiners for all three function
3916 ** callbacks.
3917 **
3918 ** ^If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3919 ** then it is invoked when the function is deleted, either by being
3920 ** overloaded or when the database connection closes.
3921 ** ^When the destructure callback of the tenth parameter is invoked, it
3922 ** is passed a single argument which is a copy of the pointer which was
3923 ** the fifth parameter to sqlite3_create_function_v2().
3924 **
3925 ** ^It is permitted to register multiple implementations of the same
3926 ** functions with the same name but with either differing numbers of
3927 ** arguments or differing preferred text encodings. ^SQLite will use
3928 ** the implementation that most closely matches the way in which the
@@ -3861,15 +3934,10 @@
3934 ** ^A function where the encoding difference is between UTF16le and UTF16be
3935 ** is a closer match than a function where the encoding difference is
3936 ** between UTF8 and UTF16.
3937 **
3938 ** ^Built-in functions may be overloaded by new application-defined functions.
 
 
 
 
 
3939 **
3940 ** ^An application-defined function is permitted to call other
3941 ** SQLite interfaces. However, such calls must not
3942 ** close the database connection nor finalize or reset the prepared
3943 ** statement in which the function is running.
@@ -3891,10 +3959,21 @@
3959 int eTextRep,
3960 void *pApp,
3961 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3962 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3963 void (*xFinal)(sqlite3_context*)
3964 );
3965 SQLITE_API int sqlite3_create_function_v2(
3966 sqlite3 *db,
3967 const char *zFunctionName,
3968 int nArg,
3969 int eTextRep,
3970 void *pApp,
3971 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3972 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3973 void (*xFinal)(sqlite3_context*),
3974 void(*xDestroy)(void*)
3975 );
3976
3977 /*
3978 ** CAPI3REF: Text Encodings
3979 **
@@ -4238,73 +4317,97 @@
4317 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4318
4319 /*
4320 ** CAPI3REF: Define New Collating Sequences
4321 **
4322 ** ^These functions add, remove, or modify a [collation] associated
4323 ** with the [database connection] specified as the first argument.
4324 **
4325 ** ^The name of the collation is a UTF-8 string
4326 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4327 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4328 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4329 ** considered to be the same name.
4330 **
4331 ** ^(The third argument (eTextRep) must be one of the constants:
4332 ** <ul>
4333 ** <li> [SQLITE_UTF8],
4334 ** <li> [SQLITE_UTF16LE],
4335 ** <li> [SQLITE_UTF16BE],
4336 ** <li> [SQLITE_UTF16], or
4337 ** <li> [SQLITE_UTF16_ALIGNED].
4338 ** </ul>)^
4339 ** ^The eTextRep argument determines the encoding of strings passed
4340 ** to the collating function callback, xCallback.
4341 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4342 ** force strings to be UTF16 with native byte order.
4343 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4344 ** on an even byte address.
4345 **
4346 ** ^The fourth argument, pArg, is a application data pointer that is passed
4347 ** through as the first argument to the collating function callback.
4348 **
4349 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4350 ** ^Multiple collating functions can be registered using the same name but
4351 ** with different eTextRep parameters and SQLite will use whichever
4352 ** function requires the least amount of data transformation.
4353 ** ^If the xCallback argument is NULL then the collating function is
4354 ** deleted. ^When all collating functions having the same name are deleted,
4355 ** that collation is no longer usable.
4356 **
4357 ** ^The collating function callback is invoked with a copy of the pArg
4358 ** application data pointer and with two strings in the encoding specified
4359 ** by the eTextRep argument. The collating function must return an
4360 ** integer that is negative, zero, or positive
4361 ** if the first string is less than, equal to, or greater than the second,
4362 ** respectively. A collating function must alway return the same answer
4363 ** given the same inputs. If two or more collating functions are registered
4364 ** to the same collation name (using different eTextRep values) then all
4365 ** must give an equivalent answer when invoked with equivalent strings.
4366 ** The collating function must obey the following properties for all
4367 ** strings A, B, and C:
4368 **
4369 ** <ol>
4370 ** <li> If A==B then B==A.
4371 ** <li> If A==B and B==C then A==C.
4372 ** <li> If A&lt;B THEN B&gt;A.
4373 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4374 ** </ol>
4375 **
4376 ** If a collating function fails any of the above constraints and that
4377 ** collating function is registered and used, then the behavior of SQLite
4378 ** is undefined.
4379 **
4380 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4381 ** with the addition that the xDestroy callback is invoked on pArg when
4382 ** the collating function is deleted.
4383 ** ^Collating functions are deleted when they are overridden by later
4384 ** calls to the collation creation functions or when the
4385 ** [database connection] is closed using [sqlite3_close()].
 
 
4386 **
4387 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4388 */
4389 SQLITE_API int sqlite3_create_collation(
4390 sqlite3*,
4391 const char *zName,
4392 int eTextRep,
4393 void *pArg,
4394 int(*xCompare)(void*,int,const void*,int,const void*)
4395 );
4396 SQLITE_API int sqlite3_create_collation_v2(
4397 sqlite3*,
4398 const char *zName,
4399 int eTextRep,
4400 void *pArg,
4401 int(*xCompare)(void*,int,const void*,int,const void*),
4402 void(*xDestroy)(void*)
4403 );
4404 SQLITE_API int sqlite3_create_collation16(
4405 sqlite3*,
4406 const void *zName,
4407 int eTextRep,
4408 void *pArg,
4409 int(*xCompare)(void*,int,const void*,int,const void*)
4410 );
4411
4412 /*
4413 ** CAPI3REF: Collation Needed Callbacks
@@ -4389,20 +4492,23 @@
4492 #endif
4493
4494 /*
4495 ** CAPI3REF: Suspend Execution For A Short Time
4496 **
4497 ** The sqlite3_sleep() function causes the current thread to suspend execution
4498 ** for at least a number of milliseconds specified in its parameter.
4499 **
4500 ** If the operating system does not support sleep requests with
4501 ** millisecond time resolution, then the time will be rounded up to
4502 ** the nearest second. The number of milliseconds of sleep actually
4503 ** requested from the operating system is returned.
4504 **
4505 ** ^SQLite implements this interface by calling the xSleep()
4506 ** method of the default [sqlite3_vfs] object. If the xSleep() method
4507 ** of the default VFS is not implemented correctly, or not implemented at
4508 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4509 ** in the previous paragraphs.
4510 */
4511 SQLITE_API int sqlite3_sleep(int);
4512
4513 /*
4514 ** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4620,44 +4726,77 @@
4726 ** of heap memory by deallocating non-essential memory allocations
4727 ** held by the database library. Memory used to cache database
4728 ** pages to improve performance is an example of non-essential memory.
4729 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4730 ** which might be more or less than the amount requested.
4731 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4732 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4733 */
4734 SQLITE_API int sqlite3_release_memory(int);
4735
4736 /*
4737 ** CAPI3REF: Impose A Limit On Heap Size
4738 **
4739 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4740 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4741 ** ^SQLite strives to keep heap memory utilization below the soft heap
4742 ** limit by reducing the number of pages held in the page cache
4743 ** as heap memory usages approaches the limit.
4744 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4745 ** below the limit, it will exceed the limit rather than generate
4746 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
4747 ** is advisory only.
4748 **
4749 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4750 ** the soft heap limit prior to the call. ^If the argument N is negative
4751 ** then no change is made to the soft heap limit. Hence, the current
4752 ** size of the soft heap limit can be determined by invoking
4753 ** sqlite3_soft_heap_limit64() with a negative argument.
4754 **
4755 ** ^If the argument N is zero then the soft heap limit is disabled.
4756 **
4757 ** ^(The soft heap limit is not enforced in the current implementation
4758 ** if one or more of following conditions are true:
4759 **
4760 ** <ul>
4761 ** <li> The soft heap limit is set to zero.
4762 ** <li> Memory accounting is disabled using a combination of the
4763 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4764 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4765 ** <li> An alternative page cache implementation is specifed using
4766 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4767 ** <li> The page cache allocates from its own memory pool supplied
4768 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4769 ** from the heap.
4770 ** </ul>)^
4771 **
4772 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4773 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4774 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4775 ** the soft heap limit is enforced on every memory allocation. Without
4776 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4777 ** when memory is allocated by the page cache. Testing suggests that because
4778 ** the page cache is the predominate memory user in SQLite, most
4779 ** applications will achieve adequate soft heap limit enforcement without
4780 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4781 **
4782 ** The circumstances under which SQLite will enforce the soft heap limit may
4783 ** changes in future releases of SQLite.
4784 */
4785 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4786
4787 /*
4788 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4789 ** DEPRECATED
4790 **
4791 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4792 ** interface. This routine is provided for historical compatibility
4793 ** only. All new applications should use the
4794 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4795 */
4796 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4797
4798
4799 /*
4800 ** CAPI3REF: Extract Metadata About A Column Of A Table
4801 **
4802 ** ^This routine returns metadata about a specific column of a specific
@@ -4777,38 +4916,51 @@
4916 ** it back off again.
4917 */
4918 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4919
4920 /*
4921 ** CAPI3REF: Automatically Load Statically Linked Extensions
4922 **
4923 ** ^This interface causes the xEntryPoint() function to be invoked for
4924 ** each new [database connection] that is created. The idea here is that
4925 ** xEntryPoint() is the entry point for a statically linked SQLite extension
4926 ** that is to be automatically loaded into all new database connections.
4927 **
4928 ** ^(Even though the function prototype shows that xEntryPoint() takes
4929 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
4930 ** arguments and expects and integer result as if the signature of the
4931 ** entry point where as follows:
4932 **
4933 ** <blockquote><pre>
4934 ** &nbsp; int xEntryPoint(
4935 ** &nbsp; sqlite3 *db,
4936 ** &nbsp; const char **pzErrMsg,
4937 ** &nbsp; const struct sqlite3_api_routines *pThunk
4938 ** &nbsp; );
4939 ** </pre></blockquote>)^
4940 **
4941 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4942 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4943 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
4944 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
4945 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
4946 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4947 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4948 **
4949 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4950 ** on the list of automatic extensions is a harmless no-op. ^No entry point
4951 ** will be called more than once for each database connection that is opened.
4952 **
4953 ** See also: [sqlite3_reset_auto_extension()].
4954 */
4955 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4956
4957 /*
4958 ** CAPI3REF: Reset Automatic Extension Loading
4959 **
4960 ** ^This interface disables all automatic extensions previously
4961 ** registered using [sqlite3_auto_extension()].
 
 
 
4962 */
4963 SQLITE_API void sqlite3_reset_auto_extension(void);
4964
4965 /*
4966 ** The interface to the virtual-table mechanism is currently considered
@@ -5443,11 +5595,11 @@
5595 ** output variable when querying the system for the current mutex
5596 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5597 **
5598 ** ^The xMutexInit method defined by this structure is invoked as
5599 ** part of system initialization by the sqlite3_initialize() function.
5600 ** ^The xMutexInit routine is called by SQLite exactly once for each
5601 ** effective call to [sqlite3_initialize()].
5602 **
5603 ** ^The xMutexEnd method defined by this structure is invoked as
5604 ** part of system shutdown by the sqlite3_shutdown() function. The
5605 ** implementation of this method is expected to release all outstanding
@@ -5640,11 +5792,12 @@
5792 #define SQLITE_TESTCTRL_ALWAYS 13
5793 #define SQLITE_TESTCTRL_RESERVE 14
5794 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
5795 #define SQLITE_TESTCTRL_ISKEYWORD 16
5796 #define SQLITE_TESTCTRL_PGHDRSZ 17
5797 #define SQLITE_TESTCTRL_SCRATCHMALLOC 18
5798 #define SQLITE_TESTCTRL_LAST 18
5799
5800 /*
5801 ** CAPI3REF: SQLite Runtime Status
5802 **
5803 ** ^This interface is used to retrieve runtime status information
@@ -5659,11 +5812,11 @@
5812 ** value. For those parameters
5813 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5814 ** ^(Other parameters record only the highwater mark and not the current
5815 ** value. For these latter parameters nothing is written into *pCurrent.)^
5816 **
5817 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5818 ** non-zero [error code] on failure.
5819 **
5820 ** This routine is threadsafe but is not atomic. This routine can be
5821 ** called while other threads are running the same or different SQLite
5822 ** interfaces. However the values returned in *pCurrent and
@@ -5709,11 +5862,11 @@
5862 ** [SQLITE_CONFIG_PAGECACHE]. The
5863 ** value returned is in pages, not in bytes.</dd>)^
5864 **
5865 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5866 ** <dd>This parameter returns the number of bytes of page cache
5867 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
5868 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
5869 ** returned value includes allocations that overflowed because they
5870 ** where too large (they were larger than the "sz" parameter to
5871 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5872 ** no space was left in the page cache.</dd>)^
@@ -5732,11 +5885,11 @@
5885 ** outstanding at time, this parameter also reports the number of threads
5886 ** using scratch memory at the same time.</dd>)^
5887 **
5888 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5889 ** <dd>This parameter returns the number of bytes of scratch memory
5890 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
5891 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
5892 ** returned include overflows because the requested allocation was too
5893 ** larger (that is, because the requested allocation was larger than the
5894 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5895 ** slots were available.
@@ -5780,10 +5933,13 @@
5933 **
5934 ** ^The current value of the requested parameter is written into *pCur
5935 ** and the highest instantaneous value is written into *pHiwtr. ^If
5936 ** the resetFlg is true, then the highest instantaneous value is
5937 ** reset back down to the current value.
5938 **
5939 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5940 ** non-zero [error code] on failure.
5941 **
5942 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5943 */
5944 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5945
@@ -5907,122 +6063,134 @@
6063 ** CAPI3REF: Application Defined Page Cache.
6064 ** KEYWORDS: {page cache}
6065 **
6066 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6067 ** register an alternative page cache implementation by passing in an
6068 ** instance of the sqlite3_pcache_methods structure.)^
6069 ** In many applications, most of the heap memory allocated by
6070 ** SQLite is used for the page cache.
6071 ** By implementing a
6072 ** custom page cache using this API, an application can better control
6073 ** the amount of memory consumed by SQLite, the way in which
6074 ** that memory is allocated and released, and the policies used to
6075 ** determine exactly which parts of a database file are cached and for
6076 ** how long.
6077 **
6078 ** The alternative page cache mechanism is an
6079 ** extreme measure that is only needed by the most demanding applications.
6080 ** The built-in page cache is recommended for most uses.
6081 **
6082 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6083 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6084 ** the application may discard the parameter after the call to
6085 ** [sqlite3_config()] returns.)^
6086 **
6087 ** ^(The xInit() method is called once for each effective
6088 ** call to [sqlite3_initialize()])^
6089 ** (usually only once during the lifetime of the process). ^(The xInit()
6090 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6091 ** The intent of the xInit() method is to set up global data structures
6092 ** required by the custom page cache implementation.
6093 ** ^(If the xInit() method is NULL, then the
6094 ** built-in default page cache is used instead of the application defined
6095 ** page cache.)^
6096 **
6097 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6098 ** It can be used to clean up
6099 ** any outstanding resources before process shutdown, if required.
6100 ** ^The xShutdown() method may be NULL.
6101 **
6102 ** ^SQLite automatically serializes calls to the xInit method,
6103 ** so the xInit method need not be threadsafe. ^The
6104 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6105 ** not need to be threadsafe either. All other methods must be threadsafe
6106 ** in multithreaded applications.
6107 **
6108 ** ^SQLite will never invoke xInit() more than once without an intervening
6109 ** call to xShutdown().
6110 **
6111 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6112 ** SQLite will typically create one cache instance for each open database file,
6113 ** though this is not guaranteed. ^The
6114 ** first parameter, szPage, is the size in bytes of the pages that must
6115 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
6116 ** will the page size of the database file that is to be cached plus an
6117 ** increment (here called "R") of about 100 or 200. SQLite will use the
6118 ** extra R bytes on each page to store metadata about the underlying
6119 ** database page on disk. The value of R depends
6120 ** on the SQLite version, the target platform, and how SQLite was compiled.
6121 ** ^R is constant for a particular build of SQLite. ^The second argument to
6122 ** xCreate(), bPurgeable, is true if the cache being created will
6123 ** be used to cache database pages of a file stored on disk, or
6124 ** false if it is used for an in-memory database. The cache implementation
6125 ** does not have to do anything special based with the value of bPurgeable;
6126 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
6127 ** never invoke xUnpin() except to deliberately delete a page.
6128 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6129 ** false will always have the "discard" flag set to true.
6130 ** ^Hence, a cache created with bPurgeable false will
6131 ** never contain any unpinned pages.
6132 **
6133 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6134 ** suggested maximum cache-size (number of pages stored by) the cache
6135 ** instance passed as the first argument. This is the value configured using
6136 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
6137 ** parameter, the implementation is not required to do anything with this
6138 ** value; it is advisory only.
6139 **
6140 ** The xPagecount() method must return the number of pages currently
6141 ** stored in the cache, both pinned and unpinned.
6142 **
6143 ** The xFetch() method locates a page in the cache and returns a pointer to
6144 ** the page, or a NULL pointer.
6145 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6146 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6147 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
6148 ** is considered to be "pinned".
6149 **
6150 ** If the requested page is already in the page cache, then the page cache
6151 ** implementation must return a pointer to the page buffer with its content
6152 ** intact. If the requested page is not already in the cache, then the
6153 ** behavior of the cache implementation should use the value of the createFlag
6154 ** parameter to help it determined what action to take:
6155 **
6156 ** <table border=1 width=85% align=center>
6157 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6158 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
6159 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6160 ** Otherwise return NULL.
6161 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
6162 ** NULL if allocating a new page is effectively impossible.
6163 ** </table>
6164 **
6165 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6166 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6167 ** failed.)^ In between the to xFetch() calls, SQLite may
6168 ** attempt to unpin one or more cache pages by spilling the content of
6169 ** pinned pages to disk and synching the operating system disk cache.
 
 
6170 **
6171 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6172 ** as its second argument. If the third parameter, discard, is non-zero,
6173 ** then the page must be evicted from the cache.
6174 ** ^If the discard parameter is
6175 ** zero, then the page may be discarded or retained at the discretion of
6176 ** page cache implementation. ^The page cache implementation
6177 ** may choose to evict unpinned pages at any time.
6178 **
6179 ** The cache must not perform any reference counting. A single
6180 ** call to xUnpin() unpins the page regardless of the number of prior calls
6181 ** to xFetch().
6182 **
6183 ** The xRekey() method is used to change the key value associated with the
6184 ** page passed as the second argument. If the cache
6185 ** previously contains an entry associated with newKey, it must be
6186 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6187 ** to be pinned.
6188 **
6189 ** When SQLite calls the xTruncate() method, the cache must discard all
6190 ** existing cache entries with page numbers (keys) greater than or equal
6191 ** to the value of the iLimit parameter passed to xTruncate(). If any
6192 ** of these pages are pinned, they are implicitly unpinned, meaning that
6193 ** they can be safely discarded.
6194 **
6195 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6196 ** All resources associated with the specified cache should be freed. ^After
@@ -6496,10 +6664,66 @@
6664 #if 0
6665 } /* End of the 'extern "C"' block */
6666 #endif
6667 #endif
6668
6669 /*
6670 ** 2010 August 30
6671 **
6672 ** The author disclaims copyright to this source code. In place of
6673 ** a legal notice, here is a blessing:
6674 **
6675 ** May you do good and not evil.
6676 ** May you find forgiveness for yourself and forgive others.
6677 ** May you share freely, never taking more than you give.
6678 **
6679 *************************************************************************
6680 */
6681
6682 #ifndef _SQLITE3RTREE_H_
6683 #define _SQLITE3RTREE_H_
6684
6685
6686 #if 0
6687 extern "C" {
6688 #endif
6689
6690 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6691
6692 /*
6693 ** Register a geometry callback named zGeom that can be used as part of an
6694 ** R-Tree geometry query as follows:
6695 **
6696 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6697 */
6698 SQLITE_API int sqlite3_rtree_geometry_callback(
6699 sqlite3 *db,
6700 const char *zGeom,
6701 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6702 void *pContext
6703 );
6704
6705
6706 /*
6707 ** A pointer to a structure of the following type is passed as the first
6708 ** argument to callbacks registered using rtree_geometry_callback().
6709 */
6710 struct sqlite3_rtree_geometry {
6711 void *pContext; /* Copy of pContext passed to s_r_g_c() */
6712 int nParam; /* Size of array aParam[] */
6713 double *aParam; /* Parameters passed to SQL geom function */
6714 void *pUser; /* Callback implementation user data */
6715 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
6716 };
6717
6718
6719 #if 0
6720 } /* end of the 'extern "C"' block */
6721 #endif
6722
6723 #endif /* ifndef _SQLITE3RTREE_H_ */
6724
6725
6726 /************** End of sqlite3.h *********************************************/
6727 /************** Continuing where we left off in sqliteInt.h ******************/
6728 /************** Include hash.h in the middle of sqliteInt.h ******************/
6729 /************** Begin file hash.h ********************************************/
@@ -7066,10 +7290,11 @@
7290 typedef struct Schema Schema;
7291 typedef struct Expr Expr;
7292 typedef struct ExprList ExprList;
7293 typedef struct ExprSpan ExprSpan;
7294 typedef struct FKey FKey;
7295 typedef struct FuncDestructor FuncDestructor;
7296 typedef struct FuncDef FuncDef;
7297 typedef struct FuncDefHash FuncDefHash;
7298 typedef struct IdList IdList;
7299 typedef struct Index Index;
7300 typedef struct IndexSample IndexSample;
@@ -7172,16 +7397,15 @@
7397 ** following values.
7398 **
7399 ** NOTE: These values must match the corresponding PAGER_ values in
7400 ** pager.h.
7401 */
7402 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
7403 #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
7404 #define BTREE_MEMORY 4 /* This is an in-memory DB */
7405 #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
7406 #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
 
7407
7408 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7409 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7410 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
7411 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
@@ -7213,15 +7437,21 @@
7437 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7438
7439 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7440
7441 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7442 ** of the flags shown below.
7443 **
7444 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7445 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7446 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
7447 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7448 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
7449 ** indices.)
7450 */
7451 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
7452 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
 
7453
7454 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7455 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7456 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7457
@@ -7838,10 +8068,11 @@
8068 **
8069 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8070 */
8071 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
8072 #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
8073 #define PAGER_MEMORY 0x0004 /* In-memory database */
8074
8075 /*
8076 ** Valid values for the second argument to sqlite3PagerLockingMode().
8077 */
8078 #define PAGER_LOCKINGMODE_QUERY -1
@@ -8472,12 +8703,12 @@
8703 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
8704 #define sqlite3_mutex_free(X)
8705 #define sqlite3_mutex_enter(X)
8706 #define sqlite3_mutex_try(X) SQLITE_OK
8707 #define sqlite3_mutex_leave(X)
8708 #define sqlite3_mutex_held(X) ((void)(X),1)
8709 #define sqlite3_mutex_notheld(X) ((void)(X),1)
8710 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
8711 #define sqlite3MutexInit() SQLITE_OK
8712 #define sqlite3MutexEnd()
8713 #endif /* defined(SQLITE_MUTEX_OMIT) */
8714
@@ -8795,10 +9026,31 @@
9026 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9027 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9028 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
9029 char *zName; /* SQL name of the function. */
9030 FuncDef *pHash; /* Next with a different name but the same hash */
9031 FuncDestructor *pDestructor; /* Reference counted destructor function */
9032 };
9033
9034 /*
9035 ** This structure encapsulates a user-function destructor callback (as
9036 ** configured using create_function_v2()) and a reference counter. When
9037 ** create_function_v2() is called to create a function with a destructor,
9038 ** a single object of this type is allocated. FuncDestructor.nRef is set to
9039 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9040 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9041 ** member of each of the new FuncDef objects is set to point to the allocated
9042 ** FuncDestructor.
9043 **
9044 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9045 ** count on this object is decremented. When it reaches 0, the destructor
9046 ** is invoked and the FuncDestructor structure freed.
9047 */
9048 struct FuncDestructor {
9049 int nRef;
9050 void (*xDestroy)(void *);
9051 void *pUserData;
9052 };
9053
9054 /*
9055 ** Possible values for FuncDef.flags
9056 */
@@ -8835,19 +9087,19 @@
9087 ** FuncDef.flags variable is set to the value passed as the flags
9088 ** parameter.
9089 */
9090 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9091 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9092 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9093 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9094 {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9095 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9096 #define LIKEFUNC(zName, nArg, arg, flags) \
9097 {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9098 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9099 {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9100 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9101
9102 /*
9103 ** All current savepoints are stored in a linked list starting at
9104 ** sqlite3.pSavepoint. The first element in the list is the most recently
9105 ** opened savepoint. Savepoints are added to the list by the vdbe
@@ -9063,10 +9315,11 @@
9315 int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
9316 int nCol; /* Number of columns in this table */
9317 Column *aCol; /* Information about each column */
9318 Index *pIndex; /* List of SQL indexes on this table. */
9319 int tnum; /* Root BTree node for this table (see note above) */
9320 unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
9321 Select *pSelect; /* NULL for tables. Points to definition if a view. */
9322 u16 nRef; /* Number of pointers to this Table */
9323 u8 tabFlags; /* Mask of TF_* values */
9324 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
9325 FKey *pFKey; /* Linked list of all foreign keys in this table */
@@ -10341,11 +10594,11 @@
10594 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10595 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10596 SQLITE_PRIVATE void sqlite3PageFree(void*);
10597 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10598 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10599 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10600
10601 /*
10602 ** On systems with ample stack space and that support alloca(), make
10603 ** use of alloca() to obtain space for large automatic objects. By default,
10604 ** obtain space from malloc().
@@ -10512,11 +10765,10 @@
10765 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10766 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10767 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10768 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10769 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
 
10770 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10771 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10772 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10773 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10774 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
@@ -10632,12 +10884,10 @@
10884 # define sqlite3AuthContextPush(a,b,c)
10885 # define sqlite3AuthContextPop(a) ((void)(a))
10886 #endif
10887 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10888 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 
 
10889 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10890 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10891 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10892 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10893 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
@@ -10759,11 +11009,13 @@
11009 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11010 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11011 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11012 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11013 void (*)(sqlite3_context*,int,sqlite3_value **),
11014 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11015 FuncDestructor *pDestructor
11016 );
11017 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11018 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11019
11020 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11021 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
@@ -11679,10 +11931,11 @@
11931 Bool useRandomRowid; /* Generate new record numbers semi-randomly */
11932 Bool nullRow; /* True if pointing to a row with no data */
11933 Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
11934 Bool isTable; /* True if a table requiring integer keys */
11935 Bool isIndex; /* True if an index containing keys only - no data */
11936 Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
11937 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
11938 Btree *pBt; /* Separate file holding temporary table */
11939 int pseudoTableReg; /* Register holding pseudotable content. */
11940 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
11941 int nField; /* Number of fields in the header */
@@ -11773,10 +12026,14 @@
12026 char *z; /* String or BLOB value */
12027 int n; /* Number of characters in string value, excluding '\0' */
12028 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12029 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12030 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12031 #ifdef SQLITE_DEBUG
12032 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
12033 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
12034 #endif
12035 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
12036 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
12037 };
12038
12039 /* One or more of the following flags are set to indicate the validOK
@@ -11799,10 +12056,11 @@
12056 #define MEM_Int 0x0004 /* Value is an integer */
12057 #define MEM_Real 0x0008 /* Value is a real number */
12058 #define MEM_Blob 0x0010 /* Value is a BLOB */
12059 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
12060 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
12061 #define MEM_Invalid 0x0080 /* Value is undefined */
12062 #define MEM_TypeMask 0x00ff /* Mask of type bits */
12063
12064 /* Whenever Mem contains a valid string or blob representation, one of
12065 ** the following flags must be set to determine the memory management
12066 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
@@ -11812,23 +12070,29 @@
12070 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
12071 #define MEM_Static 0x0800 /* Mem.z points to a static string */
12072 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
12073 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
12074 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
 
12075 #ifdef SQLITE_OMIT_INCRBLOB
12076 #undef MEM_Zero
12077 #define MEM_Zero 0x0000
12078 #endif
 
12079
12080 /*
12081 ** Clear any existing type flags from a Mem and replace them with f
12082 */
12083 #define MemSetTypeFlag(p, f) \
12084 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12085
12086 /*
12087 ** Return true if a memory cell is not marked as invalid. This macro
12088 ** is for use inside assert() statements only.
12089 */
12090 #ifdef SQLITE_DEBUG
12091 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
12092 #endif
12093
12094
12095 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12096 ** additional information about auxiliary information bound to arguments
12097 ** of the function. This is used to implement the sqlite3_get_auxdata()
12098 ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
@@ -12012,10 +12276,14 @@
12276 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12277 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12278 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12279 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12280 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12281
12282 #ifdef SQLITE_DEBUG
12283 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12284 #endif
12285
12286 #ifndef SQLITE_OMIT_FOREIGN_KEY
12287 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12288 #else
12289 # define sqlite3VdbeCheckFk(p,i) 0
@@ -13518,10 +13786,16 @@
13786 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13787 return pVfs->xSleep(pVfs, nMicro);
13788 }
13789 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13790 int rc;
13791 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
13792 ** method to get the current date and time if that method is available
13793 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
13794 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
13795 ** unavailable.
13796 */
13797 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13798 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13799 }else{
13800 double r;
13801 rc = pVfs->xCurrentTime(pVfs, &r);
@@ -13901,11 +14175,11 @@
14175 ** routines and redirected to xFree.
14176 */
14177 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14178 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14179 assert( pPrior!=0 && nByte>0 );
14180 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14181 p--;
14182 p = realloc(p, nByte+8 );
14183 if( p ){
14184 p[0] = nByte;
14185 p++;
@@ -14307,10 +14581,11 @@
14581 */
14582 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14583 struct MemBlockHdr *pOldHdr;
14584 void *pNew;
14585 assert( mem.disallow==0 );
14586 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
14587 pOldHdr = sqlite3MemsysGetHeader(pPrior);
14588 pNew = sqlite3MemMalloc(nByte);
14589 if( pNew ){
14590 memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14591 if( nByte>pOldHdr->iSize ){
@@ -15576,11 +15851,11 @@
15851 */
15852 static void *memsys5Realloc(void *pPrior, int nBytes){
15853 int nOld;
15854 void *p;
15855 assert( pPrior!=0 );
15856 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
15857 assert( nBytes>=0 );
15858 if( nBytes==0 ){
15859 return 0;
15860 }
15861 nOld = memsys5Size(pPrior);
@@ -17100,10 +17375,70 @@
17375 *************************************************************************
17376 **
17377 ** Memory allocation functions used throughout sqlite.
17378 */
17379
17380 /*
17381 ** Attempt to release up to n bytes of non-essential memory currently
17382 ** held by SQLite. An example of non-essential memory is memory used to
17383 ** cache database pages that are not currently in use.
17384 */
17385 SQLITE_API int sqlite3_release_memory(int n){
17386 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17387 return sqlite3PcacheReleaseMemory(n);
17388 #else
17389 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17390 ** is a no-op returning zero if SQLite is not compiled with
17391 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17392 UNUSED_PARAMETER(n);
17393 return 0;
17394 #endif
17395 }
17396
17397 /*
17398 ** An instance of the following object records the location of
17399 ** each unused scratch buffer.
17400 */
17401 typedef struct ScratchFreeslot {
17402 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
17403 } ScratchFreeslot;
17404
17405 /*
17406 ** State information local to the memory allocation subsystem.
17407 */
17408 static SQLITE_WSD struct Mem0Global {
17409 sqlite3_mutex *mutex; /* Mutex to serialize access */
17410
17411 /*
17412 ** The alarm callback and its arguments. The mem0.mutex lock will
17413 ** be held while the callback is running. Recursive calls into
17414 ** the memory subsystem are allowed, but no new callbacks will be
17415 ** issued.
17416 */
17417 sqlite3_int64 alarmThreshold;
17418 void (*alarmCallback)(void*, sqlite3_int64,int);
17419 void *alarmArg;
17420
17421 /*
17422 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17423 ** (so that a range test can be used to determine if an allocation
17424 ** being freed came from pScratch) and a pointer to the list of
17425 ** unused scratch allocations.
17426 */
17427 void *pScratchEnd;
17428 ScratchFreeslot *pScratchFree;
17429 u32 nScratchFree;
17430
17431 /*
17432 ** True if heap is nearly "full" where "full" is defined by the
17433 ** sqlite3_soft_heap_limit() setting.
17434 */
17435 int nearlyFull;
17436 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17437
17438 #define mem0 GLOBAL(struct Mem0Global, mem0)
17439
17440 /*
17441 ** This routine runs when the memory allocator sees that the
17442 ** total memory allocation is about to exceed the soft heap
17443 ** limit.
17444 */
@@ -17114,82 +17449,70 @@
17449 ){
17450 UNUSED_PARAMETER2(NotUsed, NotUsed2);
17451 sqlite3_release_memory(allocSize);
17452 }
17453
17454 /*
17455 ** Change the alarm callback
17456 */
17457 static int sqlite3MemoryAlarm(
17458 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17459 void *pArg,
17460 sqlite3_int64 iThreshold
17461 ){
17462 int nUsed;
17463 sqlite3_mutex_enter(mem0.mutex);
17464 mem0.alarmCallback = xCallback;
17465 mem0.alarmArg = pArg;
17466 mem0.alarmThreshold = iThreshold;
17467 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17468 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17469 sqlite3_mutex_leave(mem0.mutex);
17470 return SQLITE_OK;
17471 }
17472
17473 #ifndef SQLITE_OMIT_DEPRECATED
17474 /*
17475 ** Deprecated external interface. Internal/core SQLite code
17476 ** should call sqlite3MemoryAlarm.
17477 */
17478 SQLITE_API int sqlite3_memory_alarm(
17479 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17480 void *pArg,
17481 sqlite3_int64 iThreshold
17482 ){
17483 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17484 }
17485 #endif
17486
17487 /*
17488 ** Set the soft heap-size limit for the library. Passing a zero or
17489 ** negative value indicates no limit.
17490 */
17491 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17492 sqlite3_int64 priorLimit;
17493 sqlite3_int64 excess;
 
 
 
 
 
17494 #ifndef SQLITE_OMIT_AUTOINIT
17495 sqlite3_initialize();
17496 #endif
17497 sqlite3_mutex_enter(mem0.mutex);
17498 priorLimit = mem0.alarmThreshold;
17499 sqlite3_mutex_leave(mem0.mutex);
17500 if( n<0 ) return priorLimit;
17501 if( n>0 ){
17502 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17503 }else{
17504 sqlite3MemoryAlarm(0, 0, 0);
17505 }
17506 excess = sqlite3_memory_used() - n;
17507 if( excess>0 ) sqlite3_release_memory(excess & 0x7fffffff);
17508 return priorLimit;
17509 }
17510 SQLITE_API void sqlite3_soft_heap_limit(int n){
17511 if( n<0 ) n = 0;
17512 sqlite3_soft_heap_limit64(n);
17513 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17514
17515 /*
17516 ** Initialize the memory allocation subsystem.
17517 */
17518 SQLITE_PRIVATE int sqlite3MallocInit(void){
@@ -17199,39 +17522,48 @@
17522 memset(&mem0, 0, sizeof(mem0));
17523 if( sqlite3GlobalConfig.bCoreMutex ){
17524 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17525 }
17526 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17527 && sqlite3GlobalConfig.nScratch>0 ){
17528 int i, n, sz;
17529 ScratchFreeslot *pSlot;
17530 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17531 sqlite3GlobalConfig.szScratch = sz;
17532 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17533 n = sqlite3GlobalConfig.nScratch;
17534 mem0.pScratchFree = pSlot;
17535 mem0.nScratchFree = n;
17536 for(i=0; i<n-1; i++){
17537 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17538 pSlot = pSlot->pNext;
17539 }
17540 pSlot->pNext = 0;
17541 mem0.pScratchEnd = (void*)&pSlot[1];
17542 }else{
17543 mem0.pScratchEnd = 0;
17544 sqlite3GlobalConfig.pScratch = 0;
17545 sqlite3GlobalConfig.szScratch = 0;
17546 sqlite3GlobalConfig.nScratch = 0;
17547 }
17548 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17549 || sqlite3GlobalConfig.nPage<1 ){
 
 
 
 
 
 
 
 
 
 
17550 sqlite3GlobalConfig.pPage = 0;
17551 sqlite3GlobalConfig.szPage = 0;
17552 sqlite3GlobalConfig.nPage = 0;
17553 }
17554 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17555 }
17556
17557 /*
17558 ** Return true if the heap is currently under memory pressure - in other
17559 ** words if the amount of heap used is close to the limit set by
17560 ** sqlite3_soft_heap_limit().
17561 */
17562 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17563 return mem0.nearlyFull;
17564 }
17565
17566 /*
17567 ** Deinitialize the memory allocation subsystem.
17568 */
17569 SQLITE_PRIVATE void sqlite3MallocEnd(void){
@@ -17263,40 +17595,10 @@
17595 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17596 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
17597 return res;
17598 }
17599
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17600 /*
17601 ** Trigger the alarm
17602 */
17603 static void sqlite3MallocAlarm(int nByte){
17604 void (*xCallback)(void*,sqlite3_int64,int);
@@ -17325,18 +17627,23 @@
17627 nFull = sqlite3GlobalConfig.m.xRoundup(n);
17628 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17629 if( mem0.alarmCallback!=0 ){
17630 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17631 if( nUsed+nFull >= mem0.alarmThreshold ){
17632 mem0.nearlyFull = 1;
17633 sqlite3MallocAlarm(nFull);
17634 }else{
17635 mem0.nearlyFull = 0;
17636 }
17637 }
17638 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17639 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17640 if( p==0 && mem0.alarmCallback ){
17641 sqlite3MallocAlarm(nFull);
17642 p = sqlite3GlobalConfig.m.xMalloc(nFull);
17643 }
17644 #endif
17645 if( p ){
17646 nFull = sqlite3MallocSize(p);
17647 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17648 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17649 }
@@ -17348,11 +17655,13 @@
17655 ** Allocate memory. This routine is like sqlite3_malloc() except that it
17656 ** assumes the memory subsystem has already been initialized.
17657 */
17658 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17659 void *p;
17660 if( n<=0 /* IMP: R-65312-04917 */
17661 || n>=0x7fffff00
17662 ){
17663 /* A memory allocation of a number of bytes which is near the maximum
17664 ** signed integer value might cause an integer overflow inside of the
17665 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
17666 ** 255 bytes of overhead. SQLite itself will never use anything near
17667 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
@@ -17362,10 +17671,11 @@
17671 mallocWithAlarm(n, &p);
17672 sqlite3_mutex_leave(mem0.mutex);
17673 }else{
17674 p = sqlite3GlobalConfig.m.xMalloc(n);
17675 }
17676 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
17677 return p;
17678 }
17679
17680 /*
17681 ** This version of the memory allocation is for use by the application.
@@ -17399,64 +17709,70 @@
17709 ** embedded processor.
17710 */
17711 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17712 void *p;
17713 assert( n>0 );
17714
17715 sqlite3_mutex_enter(mem0.mutex);
17716 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
17717 p = mem0.pScratchFree;
17718 mem0.pScratchFree = mem0.pScratchFree->pNext;
17719 mem0.nScratchFree--;
17720 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17721 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17722 sqlite3_mutex_leave(mem0.mutex);
17723 }else{
17724 if( sqlite3GlobalConfig.bMemstat ){
17725 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17726 n = mallocWithAlarm(n, &p);
17727 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17728 sqlite3_mutex_leave(mem0.mutex);
17729 }else{
17730 sqlite3_mutex_leave(mem0.mutex);
17731 p = sqlite3GlobalConfig.m.xMalloc(n);
17732 }
17733 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17734 }
17735 assert( sqlite3_mutex_notheld(mem0.mutex) );
17736
17737
17738 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17739 /* Verify that no more than two scratch allocations per thread
17740 ** are outstanding at one time. (This is only checked in the
17741 ** single-threaded case since checking in the multi-threaded case
17742 ** would be much more complicated.) */
17743 assert( scratchAllocOut<=1 );
17744 if( p ) scratchAllocOut++;
17745 #endif
17746
17747 return p;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17748 }
17749 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17750 if( p ){
17751
17752 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17753 /* Verify that no more than two scratch allocation per thread
17754 ** is outstanding at one time. (This is only checked in the
17755 ** single-threaded case since checking in the multi-threaded case
17756 ** would be much more complicated.) */
17757 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17758 scratchAllocOut--;
17759 #endif
17760
17761 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
17762 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
17763 ScratchFreeslot *pSlot;
17764 pSlot = (ScratchFreeslot*)p;
17765 sqlite3_mutex_enter(mem0.mutex);
17766 pSlot->pNext = mem0.pScratchFree;
17767 mem0.pScratchFree = pSlot;
17768 mem0.nScratchFree++;
17769 assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
17770 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17771 sqlite3_mutex_leave(mem0.mutex);
17772 }else{
17773 /* Release memory back to the heap */
17774 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17775 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17776 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17777 if( sqlite3GlobalConfig.bMemstat ){
17778 int iSize = sqlite3MallocSize(p);
@@ -17467,30 +17783,10 @@
17783 sqlite3GlobalConfig.m.xFree(p);
17784 sqlite3_mutex_leave(mem0.mutex);
17785 }else{
17786 sqlite3GlobalConfig.m.xFree(p);
17787 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17788 }
17789 }
17790 }
17791
17792 /*
@@ -17527,11 +17823,11 @@
17823
17824 /*
17825 ** Free memory previously obtained from sqlite3Malloc().
17826 */
17827 SQLITE_API void sqlite3_free(void *p){
17828 if( p==0 ) return; /* IMP: R-49053-54554 */
17829 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17830 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17831 if( sqlite3GlobalConfig.bMemstat ){
17832 sqlite3_mutex_enter(mem0.mutex);
17833 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
@@ -17574,21 +17870,24 @@
17870 */
17871 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17872 int nOld, nNew;
17873 void *pNew;
17874 if( pOld==0 ){
17875 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
17876 }
17877 if( nBytes<=0 ){
17878 sqlite3_free(pOld); /* IMP: R-31593-10574 */
17879 return 0;
17880 }
17881 if( nBytes>=0x7fffff00 ){
17882 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17883 return 0;
17884 }
17885 nOld = sqlite3MallocSize(pOld);
17886 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
17887 ** argument to xRealloc is always a value returned by a prior call to
17888 ** xRoundup. */
17889 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17890 if( nOld==nNew ){
17891 pNew = pOld;
17892 }else if( sqlite3GlobalConfig.bMemstat ){
17893 sqlite3_mutex_enter(mem0.mutex);
@@ -17610,10 +17909,11 @@
17909 }
17910 sqlite3_mutex_leave(mem0.mutex);
17911 }else{
17912 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17913 }
17914 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
17915 return pNew;
17916 }
17917
17918 /*
17919 ** The public interface to sqlite3Realloc. Make sure that the memory
@@ -19773,10 +20073,16 @@
20073 #define UpperToLower sqlite3UpperToLower
20074
20075 /*
20076 ** Some systems have stricmp(). Others have strcasecmp(). Because
20077 ** there is no consistency, we will define our own.
20078 **
20079 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20080 ** applications and extensions to compare the contents of two buffers
20081 ** containing UTF-8 strings in a case-independent fashion, using the same
20082 ** definition of case independence that SQLite uses internally when
20083 ** comparing identifiers.
20084 */
20085 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20086 register unsigned char *a, *b;
20087 a = (unsigned char *)zLeft;
20088 b = (unsigned char *)zRight;
@@ -26177,11 +26483,11 @@
26483 goto shmpage_out;
26484 }
26485 pShmNode->apRegion = apNew;
26486 while(pShmNode->nRegion<=iRegion){
26487 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
26488 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
26489 );
26490 if( pMem==MAP_FAILED ){
26491 rc = SQLITE_IOERR;
26492 goto shmpage_out;
26493 }
@@ -28000,17 +28306,20 @@
28306 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28307 struct timespec timeout = {1, 0}; /* 1 sec timeout */
28308
28309 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28310 memset(pHostID, 0, PROXY_HOSTIDLEN);
28311 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28312 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28313 if( gethostuuid(pHostID, &timeout) ){
28314 int err = errno;
28315 if( pError ){
28316 *pError = err;
28317 }
28318 return SQLITE_IOERR;
28319 }
28320 #endif
28321 #ifdef SQLITE_TEST
28322 /* simulate multiple hosts by creating unique hostid file paths */
28323 if( sqlite3_hostid_num != 0){
28324 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28325 }
@@ -30339,10 +30648,18 @@
30648 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30649 }
30650
30651 #ifndef SQLITE_OMIT_WAL
30652
30653 /*
30654 ** Windows will only let you create file view mappings
30655 ** on allocation size granularity boundaries.
30656 ** During sqlite3_os_init() we do a GetSystemInfo()
30657 ** to get the granularity size.
30658 */
30659 SYSTEM_INFO winSysInfo;
30660
30661 /*
30662 ** Helper functions to obtain and relinquish the global mutex. The
30663 ** global mutex is used to protect the winLockInfo objects used by
30664 ** this file, all of which may be shared by multiple threads.
30665 **
@@ -30507,19 +30824,26 @@
30824 ** by VFS shared-memory methods.
30825 */
30826 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30827 winShmNode **pp;
30828 winShmNode *p;
30829 BOOL bRc;
30830 assert( winShmMutexHeld() );
30831 pp = &winShmNodeList;
30832 while( (p = *pp)!=0 ){
30833 if( p->nRef==0 ){
30834 int i;
30835 if( p->mutex ) sqlite3_mutex_free(p->mutex);
30836 for(i=0; i<p->nRegion; i++){
30837 bRc = UnmapViewOfFile(p->aRegion[i].pMap);
30838 OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
30839 (int)GetCurrentProcessId(), i,
30840 bRc ? "ok" : "failed"));
30841 bRc = CloseHandle(p->aRegion[i].hMap);
30842 OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
30843 (int)GetCurrentProcessId(), i,
30844 bRc ? "ok" : "failed"));
30845 }
30846 if( p->hFile.h != INVALID_HANDLE_VALUE ){
30847 SimulateIOErrorBenign(1);
30848 winClose((sqlite3_file *)&p->hFile);
30849 SimulateIOErrorBenign(0);
@@ -30592,14 +30916,15 @@
30916 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
30917 if( pShmNode->mutex==0 ){
30918 rc = SQLITE_NOMEM;
30919 goto shm_open_err;
30920 }
30921
30922 rc = winOpen(pDbFd->pVfs,
30923 pShmNode->zFilename, /* Name of the file (UTF-8) */
30924 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
30925 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
30926 0);
30927 if( SQLITE_OK!=rc ){
30928 rc = SQLITE_CANTOPEN_BKPT;
30929 goto shm_open_err;
30930 }
@@ -30903,14 +31228,22 @@
31228 void *pMap = 0; /* Mapped memory region */
31229
31230 hMap = CreateFileMapping(pShmNode->hFile.h,
31231 NULL, PAGE_READWRITE, 0, nByte, NULL
31232 );
31233 OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
31234 (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
31235 hMap ? "ok" : "failed"));
31236 if( hMap ){
31237 int iOffset = pShmNode->nRegion*szRegion;
31238 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31239 pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
31240 0, iOffset - iOffsetShift, szRegion + iOffsetShift
31241 );
31242 OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
31243 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
31244 pMap ? "ok" : "failed"));
31245 }
31246 if( !pMap ){
31247 pShmNode->lastErrno = GetLastError();
31248 rc = SQLITE_IOERR;
31249 if( hMap ) CloseHandle(hMap);
@@ -30923,12 +31256,14 @@
31256 }
31257 }
31258
31259 shmpage_out:
31260 if( pShmNode->nRegion>iRegion ){
31261 int iOffset = iRegion*szRegion;
31262 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31263 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
31264 *pp = (void *)&p[iOffsetShift];
31265 }else{
31266 *pp = 0;
31267 }
31268 sqlite3_mutex_leave(pShmNode->mutex);
31269 return rc;
@@ -31151,13 +31486,64 @@
31486 DWORD dwFlagsAndAttributes = 0;
31487 #if SQLITE_OS_WINCE
31488 int isTemp = 0;
31489 #endif
31490 winFile *pFile = (winFile*)id;
31491 void *zConverted; /* Filename in OS encoding */
31492 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31493
31494 /* If argument zPath is a NULL pointer, this function is required to open
31495 ** a temporary file. Use this buffer to store the file name in.
31496 */
31497 char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
31498
31499 int rc = SQLITE_OK; /* Function Return Code */
31500 #if !defined(NDEBUG) || SQLITE_OS_WINCE
31501 int eType = flags&0xFFFFFF00; /* Type of file to open */
31502 #endif
31503
31504 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
31505 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
31506 int isCreate = (flags & SQLITE_OPEN_CREATE);
31507 #ifndef NDEBUG
31508 int isReadonly = (flags & SQLITE_OPEN_READONLY);
31509 #endif
31510 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
31511
31512 #ifndef NDEBUG
31513 int isOpenJournal = (isCreate && (
31514 eType==SQLITE_OPEN_MASTER_JOURNAL
31515 || eType==SQLITE_OPEN_MAIN_JOURNAL
31516 || eType==SQLITE_OPEN_WAL
31517 ));
31518 #endif
31519
31520 /* Check the following statements are true:
31521 **
31522 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
31523 ** (b) if CREATE is set, then READWRITE must also be set, and
31524 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
31525 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
31526 */
31527 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31528 assert(isCreate==0 || isReadWrite);
31529 assert(isExclusive==0 || isCreate);
31530 assert(isDelete==0 || isCreate);
31531
31532 /* The main DB, main journal, WAL file and master journal are never
31533 ** automatically deleted. Nor are they ever temporary files. */
31534 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31535 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31536 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31537 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31538
31539 /* Assert that the upper layer has set one of the "file-type" flags. */
31540 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
31541 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
31542 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
31543 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31544 );
31545
31546 assert( id!=0 );
31547 UNUSED_PARAMETER(pVfs);
31548
31549 pFile->h = INVALID_HANDLE_VALUE;
@@ -31164,11 +31550,12 @@
31550
31551 /* If the second argument to this function is NULL, generate a
31552 ** temporary file name to use
31553 */
31554 if( !zUtf8Name ){
31555 assert(isDelete && !isOpenJournal);
31556 rc = getTempname(MAX_PATH+1, zTmpname);
31557 if( rc!=SQLITE_OK ){
31558 return rc;
31559 }
31560 zUtf8Name = zTmpname;
31561 }
@@ -31177,33 +31564,35 @@
31564 zConverted = convertUtf8Filename(zUtf8Name);
31565 if( zConverted==0 ){
31566 return SQLITE_NOMEM;
31567 }
31568
31569 if( isReadWrite ){
31570 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31571 }else{
31572 dwDesiredAccess = GENERIC_READ;
31573 }
31574
31575 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
31576 ** created. SQLite doesn't use it to indicate "exclusive access"
31577 ** as it is usually understood.
31578 */
31579 if( isExclusive ){
 
31580 /* Creates a new file, only if it does not already exist. */
31581 /* If the file exists, it fails. */
31582 dwCreationDisposition = CREATE_NEW;
31583 }else if( isCreate ){
31584 /* Open existing file, or create if it doesn't exist */
31585 dwCreationDisposition = OPEN_ALWAYS;
31586 }else{
31587 /* Opens a file, only if it exists. */
31588 dwCreationDisposition = OPEN_EXISTING;
31589 }
31590
31591 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31592
31593 if( isDelete ){
31594 #if SQLITE_OS_WINCE
31595 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31596 isTemp = 1;
31597 #else
31598 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
@@ -31216,10 +31605,11 @@
31605 /* Reports from the internet are that performance is always
31606 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
31607 #if SQLITE_OS_WINCE
31608 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31609 #endif
31610
31611 if( isNT() ){
31612 h = CreateFileW((WCHAR*)zConverted,
31613 dwDesiredAccess,
31614 dwShareMode,
31615 NULL,
@@ -31241,41 +31631,45 @@
31631 dwFlagsAndAttributes,
31632 NULL
31633 );
31634 #endif
31635 }
31636
31637 OSTRACE(("OPEN %d %s 0x%lx %s\n",
31638 h, zName, dwDesiredAccess,
31639 h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31640
31641 if( h==INVALID_HANDLE_VALUE ){
31642 pFile->lastErrno = GetLastError();
31643 free(zConverted);
31644 if( isReadWrite ){
31645 return winOpen(pVfs, zName, id,
31646 ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
31647 }else{
31648 return SQLITE_CANTOPEN_BKPT;
31649 }
31650 }
31651
31652 if( pOutFlags ){
31653 if( isReadWrite ){
31654 *pOutFlags = SQLITE_OPEN_READWRITE;
31655 }else{
31656 *pOutFlags = SQLITE_OPEN_READONLY;
31657 }
31658 }
31659
31660 memset(pFile, 0, sizeof(*pFile));
31661 pFile->pMethod = &winIoMethod;
31662 pFile->h = h;
31663 pFile->lastErrno = NO_ERROR;
31664 pFile->pVfs = pVfs;
31665 pFile->pShm = 0;
31666 pFile->zPath = zName;
31667 pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31668
31669 #if SQLITE_OS_WINCE
31670 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
 
31671 && !winceCreateLock(zName, pFile)
31672 ){
31673 CloseHandle(h);
31674 free(zConverted);
31675 return SQLITE_CANTOPEN_BKPT;
@@ -31285,12 +31679,13 @@
31679 }else
31680 #endif
31681 {
31682 free(zConverted);
31683 }
31684
31685 OpenCounter(+1);
31686 return rc;
31687 }
31688
31689 /*
31690 ** Delete the named file.
31691 **
@@ -31804,10 +32199,17 @@
32199 winSleep, /* xSleep */
32200 winCurrentTime, /* xCurrentTime */
32201 winGetLastError, /* xGetLastError */
32202 winCurrentTimeInt64, /* xCurrentTimeInt64 */
32203 };
32204
32205 #ifndef SQLITE_OMIT_WAL
32206 /* get memory map allocation granularity */
32207 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
32208 GetSystemInfo(&winSysInfo);
32209 assert(winSysInfo.dwAllocationGranularity > 0);
32210 #endif
32211
32212 sqlite3_vfs_register(&winVfs, 1);
32213 return SQLITE_OK;
32214 }
32215 SQLITE_API int sqlite3_os_end(void){
@@ -32369,16 +32771,20 @@
32771 ** Initialize and shutdown the page cache subsystem. Neither of these
32772 ** functions are threadsafe.
32773 */
32774 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32775 if( sqlite3GlobalConfig.pcache.xInit==0 ){
32776 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
32777 ** built-in default page cache is used instead of the application defined
32778 ** page cache. */
32779 sqlite3PCacheSetDefault();
32780 }
32781 return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32782 }
32783 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32784 if( sqlite3GlobalConfig.pcache.xShutdown ){
32785 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
32786 sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32787 }
32788 }
32789
32790 /*
@@ -32835,12 +33241,17 @@
33241
33242 typedef struct PCache1 PCache1;
33243 typedef struct PgHdr1 PgHdr1;
33244 typedef struct PgFreeslot PgFreeslot;
33245
33246 /* Each page cache is an instance of the following object. Every
33247 ** open database file (including each in-memory database and each
33248 ** temporary or transient database) has a single page cache which
33249 ** is an instance of this object.
33250 **
33251 ** Pointers to structures of this type are cast and returned as
33252 ** opaque sqlite3_pcache* handles.
33253 */
33254 struct PCache1 {
33255 /* Cache configuration parameters. Page size (szPage) and the purgeable
33256 ** flag (bPurgeable) are set when the cache is created. nMax may be
33257 ** modified at any time by a call to the pcache1CacheSize() method.
@@ -32896,10 +33307,13 @@
33307 int nCurrentPage; /* Number of purgeable pages allocated */
33308 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
33309
33310 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
33311 int szSlot; /* Size of each free slot */
33312 int nSlot; /* The number of pcache slots */
33313 int nFreeSlot; /* Number of unused pcache slots */
33314 int nReserve; /* Try to keep nFreeSlot above this */
33315 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
33316 PgFreeslot *pFree; /* Free page blocks */
33317 int isInit; /* True if initialized */
33318 } pcache1_g;
33319
@@ -32943,10 +33357,12 @@
33357 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
33358 if( pcache1.isInit ){
33359 PgFreeslot *p;
33360 sz = ROUNDDOWN8(sz);
33361 pcache1.szSlot = sz;
33362 pcache1.nSlot = pcache1.nFreeSlot = n;
33363 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
33364 pcache1.pStart = pBuf;
33365 pcache1.pFree = 0;
33366 while( n-- ){
33367 p = (PgFreeslot*)pBuf;
33368 p->pNext = pcache1.pFree;
@@ -32969,10 +33385,12 @@
33385 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
33386 if( nByte<=pcache1.szSlot && pcache1.pFree ){
33387 assert( pcache1.isInit );
33388 p = (PgHdr1 *)pcache1.pFree;
33389 pcache1.pFree = pcache1.pFree->pNext;
33390 pcache1.nFreeSlot--;
33391 assert( pcache1.nFreeSlot>=0 );
33392 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
33393 }else{
33394
33395 /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
33396 ** global pcache mutex and unlock the pager-cache object pCache. This is
@@ -33002,10 +33420,12 @@
33420 PgFreeslot *pSlot;
33421 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33422 pSlot = (PgFreeslot*)p;
33423 pSlot->pNext = pcache1.pFree;
33424 pcache1.pFree = pSlot;
33425 pcache1.nFreeSlot++;
33426 assert( pcache1.nFreeSlot<=pcache1.nSlot );
33427 }else{
33428 int iSize;
33429 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33430 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33431 iSize = sqlite3MallocSize(p);
@@ -33014,11 +33434,11 @@
33434 }
33435 }
33436
33437 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33438 /*
33439 ** Return the size of a pcache allocation
33440 */
33441 static int pcache1MemSize(void *p){
33442 assert( sqlite3_mutex_held(pcache1.mutex) );
33443 if( p>=pcache1.pStart && p<pcache1.pEnd ){
33444 return pcache1.szSlot;
@@ -33087,10 +33507,36 @@
33507 pcache1EnterMutex();
33508 pcache1Free(p);
33509 pcache1LeaveMutex();
33510 }
33511
33512
33513 /*
33514 ** Return true if it desirable to avoid allocating a new page cache
33515 ** entry.
33516 **
33517 ** If memory was allocated specifically to the page cache using
33518 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
33519 ** it is desirable to avoid allocating a new page cache entry because
33520 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
33521 ** for all page cache needs and we should not need to spill the
33522 ** allocation onto the heap.
33523 **
33524 ** Or, the heap is used for all page cache memory put the heap is
33525 ** under memory pressure, then again it is desirable to avoid
33526 ** allocating a new page cache entry in order to avoid stressing
33527 ** the heap even further.
33528 */
33529 static int pcache1UnderMemoryPressure(PCache1 *pCache){
33530 assert( sqlite3_mutex_held(pcache1.mutex) );
33531 if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
33532 return pcache1.nFreeSlot<pcache1.nReserve;
33533 }else{
33534 return sqlite3HeapNearlyFull();
33535 }
33536 }
33537
33538 /******************************************************************************/
33539 /******** General Implementation Functions ************************************/
33540
33541 /*
33542 ** This function is used to resize the hash table used by the cache passed
@@ -33328,18 +33774,20 @@
33774 ** copy of the requested page. If one is found, it is returned.
33775 **
33776 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
33777 ** returned.
33778 **
33779 ** 3. If createFlag is 1, and the page is not already in the cache, then
33780 ** return NULL (do not allocate a new page) if any of the following
33781 ** conditions are true:
33782 **
33783 ** (a) the number of pages pinned by the cache is greater than
33784 ** PCache1.nMax, or
33785 **
33786 ** (b) the number of pages pinned by the cache is greater than
33787 ** the sum of nMax for all purgeable caches, less the sum of
33788 ** nMin for all other purgeable caches, or
33789 **
33790 ** 4. If none of the first three conditions apply and the cache is marked
33791 ** as purgeable, and if one of the following is true:
33792 **
33793 ** (a) The number of pages allocated for the cache is already
@@ -33346,10 +33794,13 @@
33794 ** PCache1.nMax, or
33795 **
33796 ** (b) The number of pages allocated for all purgeable caches is
33797 ** already equal to or greater than the sum of nMax for all
33798 ** purgeable caches,
33799 **
33800 ** (c) The system is under memory pressure and wants to avoid
33801 ** unnecessary pages cache entry allocations
33802 **
33803 ** then attempt to recycle a page from the LRU list. If it is the right
33804 ** size, return the recycled buffer. Otherwise, free the buffer and
33805 ** proceed to step 5.
33806 **
@@ -33378,10 +33829,11 @@
33829 /* Step 3 of header comment. */
33830 nPinned = pCache->nPage - pCache->nRecyclable;
33831 if( createFlag==1 && (
33832 nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33833 || nPinned>=(pCache->nMax * 9 / 10)
33834 || pcache1UnderMemoryPressure(pCache)
33835 )){
33836 goto fetch_out;
33837 }
33838
33839 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
@@ -33388,11 +33840,13 @@
33840 goto fetch_out;
33841 }
33842
33843 /* Step 4. Try to recycle a page buffer if appropriate. */
33844 if( pCache->bPurgeable && pcache1.pLruTail && (
33845 (pCache->nPage+1>=pCache->nMax)
33846 || pcache1.nCurrentPage>=pcache1.nMaxPage
33847 || pcache1UnderMemoryPressure(pCache)
33848 )){
33849 pPage = pcache1.pLruTail;
33850 pcache1RemoveFromHash(pPage);
33851 pcache1PinPage(pPage);
33852 if( pPage->pCache->szPage!=pCache->szPage ){
@@ -33531,10 +33985,11 @@
33985 **
33986 ** Destroy a cache allocated using pcache1Create().
33987 */
33988 static void pcache1Destroy(sqlite3_pcache *p){
33989 PCache1 *pCache = (PCache1 *)p;
33990 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
33991 pcache1EnterMutex();
33992 pcache1TruncateUnsafe(pCache, 0);
33993 pcache1.nMaxPage -= pCache->nMax;
33994 pcache1.nMinPage -= pCache->nMin;
33995 pcache1EnforceMaxPage();
@@ -33578,11 +34033,11 @@
34033 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
34034 int nFree = 0;
34035 if( pcache1.pStart==0 ){
34036 PgHdr1 *p;
34037 pcache1EnterMutex();
34038 while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
34039 nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
34040 pcache1PinPage(p);
34041 pcache1RemoveFromHash(p);
34042 pcache1FreePage(p);
34043 }
@@ -37120,16 +37575,17 @@
37575 ** the duplicate call is harmless.
37576 */
37577 sqlite3WalEndReadTransaction(pPager->pWal);
37578
37579 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37580 if( rc!=SQLITE_OK || changed ){
37581 pager_reset(pPager);
37582 }
37583
37584 return rc;
37585 }
37586 #endif
37587
37588 /*
37589 ** This function is called as part of the transition from PAGER_OPEN
37590 ** to PAGER_READER state to determine the size of the database file
37591 ** in pages (assuming the page size currently stored in Pager.pageSize).
@@ -37182,11 +37638,11 @@
37638
37639 *pnPage = nPage;
37640 return SQLITE_OK;
37641 }
37642
37643 #ifndef SQLITE_OMIT_WAL
37644 /*
37645 ** Check if the *-wal file that corresponds to the database opened by pPager
37646 ** exists if the database is not empy, or verify that the *-wal file does
37647 ** not exist (by deleting it) if the database file is empty.
37648 **
@@ -38374,10 +38830,17 @@
38830 journalFileSize = ROUND8(sqlite3MemJournalSize());
38831 }
38832
38833 /* Set the output variable to NULL in case an error occurs. */
38834 *ppPager = 0;
38835
38836 #ifndef SQLITE_OMIT_MEMORYDB
38837 if( flags & PAGER_MEMORY ){
38838 memDb = 1;
38839 zFilename = 0;
38840 }
38841 #endif
38842
38843 /* Compute and store the full pathname in an allocated buffer pointed
38844 ** to by zPathname, length nPathname. Or, if this is a temporary file,
38845 ** leave both nPathname and zPathname set to 0.
38846 */
@@ -38385,21 +38848,12 @@
38848 nPathname = pVfs->mxPathname+1;
38849 zPathname = sqlite3Malloc(nPathname*2);
38850 if( zPathname==0 ){
38851 return SQLITE_NOMEM;
38852 }
38853 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38854 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
 
 
 
 
 
 
 
 
 
38855 nPathname = sqlite3Strlen30(zPathname);
38856 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
38857 /* This branch is taken when the journal path required by
38858 ** the database being opened will be more than pVfs->mxPathname
38859 ** bytes in length. This means the database cannot be opened,
@@ -38450,34 +38904,31 @@
38904 pPager->zFilename = (char*)(pPtr += journalFileSize);
38905 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
38906
38907 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
38908 if( zPathname ){
38909 assert( nPathname>0 );
38910 pPager->zJournal = (char*)(pPtr += nPathname + 1);
38911 memcpy(pPager->zFilename, zPathname, nPathname);
38912 memcpy(pPager->zJournal, zPathname, nPathname);
38913 memcpy(&pPager->zJournal[nPathname], "-journal", 8);
 
 
 
38914 #ifndef SQLITE_OMIT_WAL
38915 pPager->zWal = &pPager->zJournal[nPathname+8+1];
38916 memcpy(pPager->zWal, zPathname, nPathname);
38917 memcpy(&pPager->zWal[nPathname], "-wal", 4);
 
 
38918 #endif
38919 sqlite3_free(zPathname);
38920 }
38921 pPager->pVfs = pVfs;
38922 pPager->vfsFlags = vfsFlags;
38923
38924 /* Open the pager file.
38925 */
38926 if( zFilename && zFilename[0] ){
38927 int fout = 0; /* VFS flags returned by xOpen() */
38928 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
38929 assert( !memDb );
38930 readOnly = (fout&SQLITE_OPEN_READONLY);
38931
38932 /* If the file was successfully opened for read/write access,
38933 ** choose a default page size in case we have to create the
38934 ** database file. The default page size is the maximum of:
@@ -38927,11 +39378,13 @@
39378
39379 /* If there is a WAL file in the file-system, open this database in WAL
39380 ** mode. Otherwise, the following function call is a no-op.
39381 */
39382 rc = pagerOpenWalIfPresent(pPager);
39383 #ifndef SQLITE_OMIT_WAL
39384 assert( pPager->pWal==0 || rc==SQLITE_OK );
39385 #endif
39386 }
39387
39388 if( pagerUseWal(pPager) ){
39389 assert( rc==SQLITE_OK );
39390 rc = pagerBeginReadTransaction(pPager);
@@ -43292,11 +43745,11 @@
43745 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43746 if( rc!=SQLITE_OK ){
43747 return rc;
43748 }
43749 }
43750 assert( (int)pWal->szPage==szPage );
43751
43752 /* Write the log file. */
43753 for(p=pList; p; p=p->pDirty){
43754 u32 nDbsize; /* Db-size field for frame header */
43755 i64 iOffset; /* Write offset in log file */
@@ -43952,10 +44405,11 @@
44405 MemPage *pPage1; /* First page of the database */
44406 u8 readOnly; /* True if the underlying file is readonly */
44407 u8 pageSizeFixed; /* True if the page size can no longer be changed */
44408 u8 secureDelete; /* True if secure_delete is enabled */
44409 u8 initiallyEmpty; /* Database is empty at start of transaction */
44410 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
44411 #ifndef SQLITE_OMIT_AUTOVACUUM
44412 u8 autoVacuum; /* True if auto-vacuum is enabled */
44413 u8 incrVacuum; /* True if incr-vacuum is enabled */
44414 #endif
44415 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
@@ -46202,15 +46656,24 @@
46656
46657 /*
46658 ** Open a database file.
46659 **
46660 ** zFilename is the name of the database file. If zFilename is NULL
46661 ** then an ephemeral database is created. The ephemeral database might
46662 ** be exclusively in memory, or it might use a disk-based memory cache.
46663 ** Either way, the ephemeral database will be automatically deleted
46664 ** when sqlite3BtreeClose() is called.
46665 **
46666 ** If zFilename is ":memory:" then an in-memory database is created
46667 ** that is automatically destroyed when it is closed.
46668 **
46669 ** The "flags" parameter is a bitmask that might contain bits
46670 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
46671 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
46672 ** These flags are passed through into sqlite3PagerOpen() and must
46673 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
46674 **
46675 ** If the database is already opened in the same database connection
46676 ** and we are in shared cache mode, then the open will fail with an
46677 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
46678 ** objects in the same database connection since doing so will lead
46679 ** to problems with locking.
@@ -46227,10 +46690,13 @@
46690 Btree *p; /* Handle to return */
46691 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
46692 int rc = SQLITE_OK; /* Result code from this function */
46693 u8 nReserve; /* Byte of unused space on each page */
46694 unsigned char zDbHeader[100]; /* Database header content */
46695
46696 /* True if opening an ephemeral, temporary database */
46697 const int isTempDb = zFilename==0 || zFilename[0]==0;
46698
46699 /* Set the variable isMemdb to true for an in-memory database, or
46700 ** false for a file-based database. This symbol is only required if
46701 ** either of the shared-data or autovacuum features are compiled
46702 ** into the library.
@@ -46237,17 +46703,34 @@
46703 */
46704 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
46705 #ifdef SQLITE_OMIT_MEMORYDB
46706 const int isMemdb = 0;
46707 #else
46708 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
46709 || (isTempDb && sqlite3TempInMemory(db));
46710 #endif
46711 #endif
46712
46713 assert( db!=0 );
46714 assert( sqlite3_mutex_held(db->mutex) );
46715 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
46716
46717 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
46718 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
46719
46720 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
46721 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
46722
46723 if( db->flags & SQLITE_NoReadlock ){
46724 flags |= BTREE_NO_READLOCK;
46725 }
46726 if( isMemdb ){
46727 flags |= BTREE_MEMORY;
46728 }
46729 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
46730 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
46731 }
46732 pVfs = db->pVfs;
46733 p = sqlite3MallocZero(sizeof(Btree));
46734 if( !p ){
46735 return SQLITE_NOMEM;
46736 }
@@ -46261,11 +46744,11 @@
46744 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46745 /*
46746 ** If this Btree is a candidate for shared cache, try to find an
46747 ** existing BtShared object that we can share with
46748 */
46749 if( isMemdb==0 && isTempDb==0 ){
46750 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
46751 int nFullPathname = pVfs->mxPathname+1;
46752 char *zFullPathname = sqlite3Malloc(nFullPathname);
46753 sqlite3_mutex *mutexShared;
46754 p->sharable = 1;
@@ -46336,10 +46819,11 @@
46819 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
46820 }
46821 if( rc!=SQLITE_OK ){
46822 goto btree_open_out;
46823 }
46824 pBt->openFlags = (u8)flags;
46825 pBt->db = db;
46826 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
46827 p->pBt = pBt;
46828
46829 pBt->pCursor = 0;
@@ -46440,10 +46924,18 @@
46924 sqlite3PagerClose(pBt->pPager);
46925 }
46926 sqlite3_free(pBt);
46927 sqlite3_free(p);
46928 *ppBtree = 0;
46929 }else{
46930 /* If the B-Tree was successfully opened, set the pager-cache size to the
46931 ** default value. Except, when opening on an existing shared pager-cache,
46932 ** do not change the pager-cache size.
46933 */
46934 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
46935 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
46936 }
46937 }
46938 if( mutexOpen ){
46939 assert( sqlite3_mutex_held(mutexOpen) );
46940 sqlite3_mutex_leave(mutexOpen);
46941 }
@@ -51390,15 +51882,16 @@
51882 ** flags might not work:
51883 **
51884 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
51885 ** BTREE_ZERODATA Used for SQL indices
51886 */
51887 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
51888 BtShared *pBt = p->pBt;
51889 MemPage *pRoot;
51890 Pgno pgnoRoot;
51891 int rc;
51892 int ptfFlags; /* Page-type flage for the root page of new table */
51893
51894 assert( sqlite3BtreeHoldsMutex(p) );
51895 assert( pBt->inTransaction==TRANS_WRITE );
51896 assert( !pBt->readOnly );
51897
@@ -51513,12 +52006,18 @@
52006 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
52007 if( rc ) return rc;
52008 }
52009 #endif
52010 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
52011 if( createTabFlags & BTREE_INTKEY ){
52012 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
52013 }else{
52014 ptfFlags = PTF_ZERODATA | PTF_LEAF;
52015 }
52016 zeroPage(pRoot, ptfFlags);
52017 sqlite3PagerUnref(pRoot->pDbPage);
52018 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
52019 *piTable = (int)pgnoRoot;
52020 return SQLITE_OK;
52021 }
52022 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
52023 int rc;
@@ -52774,11 +53273,14 @@
53273 sqlite3Error(
53274 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
53275 );
53276 p = 0;
53277 }else {
53278 /* Allocate space for a new sqlite3_backup object...
53279 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53280 ** call to sqlite3_backup_init() and is destroyed by a call to
53281 ** sqlite3_backup_finish(). */
53282 p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
53283 if( !p ){
53284 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
53285 }
53286 }
@@ -53157,10 +53659,13 @@
53659 if( p->pDestDb ){
53660 sqlite3_mutex_leave(p->pDestDb->mutex);
53661 }
53662 sqlite3BtreeLeave(p->pSrc);
53663 if( p->pDestDb ){
53664 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53665 ** call to sqlite3_backup_init() and is destroyed by a call to
53666 ** sqlite3_backup_finish(). */
53667 sqlite3_free(p);
53668 }
53669 sqlite3_mutex_leave(mutex);
53670 return rc;
53671 }
@@ -53408,10 +53913,13 @@
53913 return SQLITE_NOMEM;
53914 }
53915 pMem->z[pMem->n] = 0;
53916 pMem->z[pMem->n+1] = 0;
53917 pMem->flags |= MEM_Term;
53918 #ifdef SQLITE_DEBUG
53919 pMem->pScopyFrom = 0;
53920 #endif
53921 }
53922
53923 return SQLITE_OK;
53924 }
53925
@@ -53528,11 +54036,11 @@
54036 memset(&ctx, 0, sizeof(ctx));
54037 ctx.s.flags = MEM_Null;
54038 ctx.s.db = pMem->db;
54039 ctx.pMem = pMem;
54040 ctx.pFunc = pFunc;
54041 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
54042 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
54043 sqlite3DbFree(pMem->db, pMem->zMalloc);
54044 memcpy(pMem, &ctx.s, sizeof(ctx.s));
54045 rc = ctx.isError;
54046 }
@@ -53869,10 +54377,32 @@
54377 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
54378 }
54379 return 0;
54380 }
54381
54382 #ifdef SQLITE_DEBUG
54383 /*
54384 ** This routine prepares a memory cell for modication by breaking
54385 ** its link to a shallow copy and by marking any current shallow
54386 ** copies of this cell as invalid.
54387 **
54388 ** This is used for testing and debugging only - to make sure shallow
54389 ** copies are not misused.
54390 */
54391 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
54392 int i;
54393 Mem *pX;
54394 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
54395 if( pX->pScopyFrom==pMem ){
54396 pX->flags |= MEM_Invalid;
54397 pX->pScopyFrom = 0;
54398 }
54399 }
54400 pMem->pScopyFrom = 0;
54401 }
54402 #endif /* SQLITE_DEBUG */
54403
54404 /*
54405 ** Size of struct Mem not including the Mem.zMalloc member.
54406 */
54407 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
54408
@@ -54237,11 +54767,11 @@
54767 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
54768 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
54769 return 0;
54770 }
54771 }
54772 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
54773 }else{
54774 assert( (pVal->flags&MEM_Blob)==0 );
54775 sqlite3VdbeMemStringify(pVal, enc);
54776 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
54777 }
@@ -56152,13 +56682,14 @@
56682 */
56683 for(i=0; i<db->nDb; i++){
56684 Btree *pBt = db->aDb[i].pBt;
56685 if( sqlite3BtreeIsInTrans(pBt) ){
56686 char const *zFile = sqlite3BtreeGetJournalname(pBt);
56687 if( zFile==0 ){
56688 continue; /* Ignore TEMP and :memory: databases */
56689 }
56690 assert( zFile[0]!=0 );
56691 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
56692 needSync = 1;
56693 }
56694 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
56695 offset += sqlite3Strlen30(zFile)+1;
@@ -57618,10 +58149,12 @@
58149 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58150 */
58151 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
58152 int rc;
58153 if( pStmt==0 ){
58154 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
58155 ** pointer is a harmless no-op. */
58156 rc = SQLITE_OK;
58157 }else{
58158 Vdbe *v = (Vdbe*)pStmt;
58159 sqlite3 *db = v->db;
58160 #if SQLITE_THREADSAFE
@@ -57694,11 +58227,11 @@
58227 Mem *p = (Mem*)pVal;
58228 if( p->flags & (MEM_Blob|MEM_Str) ){
58229 sqlite3VdbeMemExpandBlob(p);
58230 p->flags &= ~MEM_Str;
58231 p->flags |= MEM_Blob;
58232 return p->n ? p->z : 0;
58233 }else{
58234 return sqlite3_value_text(pVal);
58235 }
58236 }
58237 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
@@ -58048,10 +58581,16 @@
58581 }
58582
58583 /*
58584 ** Extract the user data from a sqlite3_context structure and return a
58585 ** pointer to it.
58586 **
58587 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
58588 ** returns a copy of the pointer to the database connection (the 1st
58589 ** parameter) of the sqlite3_create_function() and
58590 ** sqlite3_create_function16() routines that originally registered the
58591 ** application defined function.
58592 */
58593 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
58594 assert( p && p->pFunc );
58595 return p->s.db;
58596 }
@@ -58257,12 +58796,11 @@
58796 ** sqlite3_column_text()
58797 ** sqlite3_column_text16()
58798 ** sqlite3_column_real()
58799 ** sqlite3_column_bytes()
58800 ** sqlite3_column_bytes16()
58801 ** sqiite3_column_blob()
 
58802 */
58803 static void columnMallocFailure(sqlite3_stmt *pStmt)
58804 {
58805 /* If malloc() failed during an encoding conversion within an
58806 ** sqlite3_column_XXX API, then set the return code of the statement to
@@ -58526,10 +59064,16 @@
59064 pVar->flags = MEM_Null;
59065 sqlite3Error(p->db, SQLITE_OK, 0);
59066
59067 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
59068 ** binding a new value to this variable invalidates the current query plan.
59069 **
59070 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
59071 ** parameter in the WHERE clause might influence the choice of query plan
59072 ** for a statement, then the statement will be automatically recompiled,
59073 ** as if there had been a schema change, on the first sqlite3_step() call
59074 ** following any change to the bindings of that parameter.
59075 */
59076 if( p->isPrepareV2 &&
59077 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
59078 ){
59079 p->expired = 1;
@@ -59023,10 +59567,21 @@
59567 ** of the code in this file is, therefore, important. See other comments
59568 ** in this file for details. If in doubt, do not deviate from existing
59569 ** commenting and indentation practices when changing or adding code.
59570 */
59571
59572 /*
59573 ** Invoke this macro on memory cells just prior to changing the
59574 ** value of the cell. This macro verifies that shallow copies are
59575 ** not misused.
59576 */
59577 #ifdef SQLITE_DEBUG
59578 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
59579 #else
59580 # define memAboutToChange(P,M)
59581 #endif
59582
59583 /*
59584 ** The following global variable is incremented every time a cursor
59585 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
59586 ** procedures use this information to make sure that indices are
59587 ** working correctly. This variable has no function other than to
@@ -60132,38 +60687,44 @@
60687 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
60688 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
60689 assert( pOp->p2>0 );
60690 assert( pOp->p2<=p->nMem );
60691 pOut = &aMem[pOp->p2];
60692 memAboutToChange(p, pOut);
60693 sqlite3VdbeMemReleaseExternal(pOut);
60694 pOut->flags = MEM_Int;
60695 }
60696
60697 /* Sanity checking on other operands */
60698 #ifdef SQLITE_DEBUG
60699 if( (pOp->opflags & OPFLG_IN1)!=0 ){
60700 assert( pOp->p1>0 );
60701 assert( pOp->p1<=p->nMem );
60702 assert( memIsValid(&aMem[pOp->p1]) );
60703 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
60704 }
60705 if( (pOp->opflags & OPFLG_IN2)!=0 ){
60706 assert( pOp->p2>0 );
60707 assert( pOp->p2<=p->nMem );
60708 assert( memIsValid(&aMem[pOp->p2]) );
60709 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
60710 }
60711 if( (pOp->opflags & OPFLG_IN3)!=0 ){
60712 assert( pOp->p3>0 );
60713 assert( pOp->p3<=p->nMem );
60714 assert( memIsValid(&aMem[pOp->p3]) );
60715 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
60716 }
60717 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
60718 assert( pOp->p2>0 );
60719 assert( pOp->p2<=p->nMem );
60720 memAboutToChange(p, &aMem[pOp->p2]);
60721 }
60722 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
60723 assert( pOp->p3>0 );
60724 assert( pOp->p3<=p->nMem );
60725 memAboutToChange(p, &aMem[pOp->p3]);
60726 }
60727 #endif
60728
60729 switch( pOp->opcode ){
60730
@@ -60221,10 +60782,11 @@
60782 ** and then jump to address P2.
60783 */
60784 case OP_Gosub: { /* jump, in1 */
60785 pIn1 = &aMem[pOp->p1];
60786 assert( (pIn1->flags & MEM_Dyn)==0 );
60787 memAboutToChange(p, pIn1);
60788 pIn1->flags = MEM_Int;
60789 pIn1->u.i = pc;
60790 REGISTER_TRACE(pOp->p1, pIn1);
60791 pc = pOp->p2 - 1;
60792 break;
@@ -60428,15 +60990,11 @@
60990
60991
60992 /* Opcode: Blob P1 P2 * P4
60993 **
60994 ** P4 points to a blob of data P1 bytes long. Store this
60995 ** blob in register P2.
 
 
 
 
60996 */
60997 case OP_Blob: { /* out2-prerelease */
60998 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
60999 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
61000 pOut->enc = encoding;
@@ -60490,10 +61048,12 @@
61048 pIn1 = &aMem[u.ac.p1];
61049 pOut = &aMem[u.ac.p2];
61050 while( u.ac.n-- ){
61051 assert( pOut<=&aMem[p->nMem] );
61052 assert( pIn1<=&aMem[p->nMem] );
61053 assert( memIsValid(pIn1) );
61054 memAboutToChange(p, pOut);
61055 u.ac.zMalloc = pOut->zMalloc;
61056 pOut->zMalloc = 0;
61057 sqlite3VdbeMemMove(pOut, pIn1);
61058 pIn1->zMalloc = u.ac.zMalloc;
61059 REGISTER_TRACE(u.ac.p2++, pOut);
@@ -60535,10 +61095,13 @@
61095 case OP_SCopy: { /* in1, out2 */
61096 pIn1 = &aMem[pOp->p1];
61097 pOut = &aMem[pOp->p2];
61098 assert( pOut!=pIn1 );
61099 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61100 #ifdef SQLITE_DEBUG
61101 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
61102 #endif
61103 REGISTER_TRACE(pOp->p2, pOut);
61104 break;
61105 }
61106
61107 /* Opcode: ResultRow P1 P2 * * *
@@ -60595,10 +61158,14 @@
61158 ** and have an assigned type. The results are de-ephemeralized as
61159 ** as side effect.
61160 */
61161 u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
61162 for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
61163 assert( memIsValid(&u.ad.pMem[u.ad.i]) );
61164 Deephemeralize(&u.ad.pMem[u.ad.i]);
61165 assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
61166 || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
61167 sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
61168 sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
61169 REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
61170 }
61171 if( db->mallocFailed ) goto no_mem;
@@ -60826,16 +61393,21 @@
61393 #endif /* local variables moved into u.ag */
61394
61395 u.ag.n = pOp->p5;
61396 u.ag.apVal = p->apArg;
61397 assert( u.ag.apVal || u.ag.n==0 );
61398 assert( pOp->p3>0 && pOp->p3<=p->nMem );
61399 pOut = &aMem[pOp->p3];
61400 memAboutToChange(p, pOut);
61401
61402 assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
61403 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
61404 u.ag.pArg = &aMem[pOp->p2];
61405 for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
61406 assert( memIsValid(u.ag.pArg) );
61407 u.ag.apVal[u.ag.i] = u.ag.pArg;
61408 Deephemeralize(u.ag.pArg);
61409 sqlite3VdbeMemStoreType(u.ag.pArg);
61410 REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
61411 }
61412
61413 assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
@@ -60845,12 +61417,10 @@
61417 }else{
61418 u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
61419 u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
61420 }
61421
 
 
61422 u.ag.ctx.s.flags = MEM_Null;
61423 u.ag.ctx.s.db = db;
61424 u.ag.ctx.s.xDel = 0;
61425 u.ag.ctx.s.zMalloc = 0;
61426
@@ -60866,11 +61436,11 @@
61436 assert( pOp>aOp );
61437 assert( pOp[-1].p4type==P4_COLLSEQ );
61438 assert( pOp[-1].opcode==OP_CollSeq );
61439 u.ag.ctx.pColl = pOp[-1].p4.pColl;
61440 }
61441 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
61442 if( db->mallocFailed ){
61443 /* Even though a malloc() has failed, the implementation of the
61444 ** user function may have called an sqlite3_result_XXX() function
61445 ** to return a value. The following call releases any resources
61446 ** associated with such a value.
@@ -60918,11 +61488,11 @@
61488 ** If either input is NULL, the result is NULL.
61489 */
61490 /* Opcode: ShiftLeft P1 P2 P3 * *
61491 **
61492 ** Shift the integer value in register P2 to the left by the
61493 ** number of bits specified by the integer in register P1.
61494 ** Store the result in register P3.
61495 ** If either input is NULL, the result is NULL.
61496 */
61497 /* Opcode: ShiftRight P1 P2 P3 * *
61498 **
@@ -60968,10 +61538,11 @@
61538 **
61539 ** To force any register to be an integer, just add 0.
61540 */
61541 case OP_AddImm: { /* in1 */
61542 pIn1 = &aMem[pOp->p1];
61543 memAboutToChange(p, pIn1);
61544 sqlite3VdbeMemIntegerify(pIn1);
61545 pIn1->u.i += pOp->p2;
61546 break;
61547 }
61548
@@ -60982,10 +61553,11 @@
61553 ** without data loss, then jump immediately to P2, or if P2==0
61554 ** raise an SQLITE_MISMATCH exception.
61555 */
61556 case OP_MustBeInt: { /* jump, in1 */
61557 pIn1 = &aMem[pOp->p1];
61558 memAboutToChange(p, pIn1);
61559 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
61560 if( (pIn1->flags & MEM_Int)==0 ){
61561 if( pOp->p2==0 ){
61562 rc = SQLITE_MISMATCH;
61563 goto abort_due_to_error;
@@ -61008,10 +61580,11 @@
61580 ** integers, for space efficiency, but after extraction we want them
61581 ** to have only a real value.
61582 */
61583 case OP_RealAffinity: { /* in1 */
61584 pIn1 = &aMem[pOp->p1];
61585 memAboutToChange(p, pIn1);
61586 if( pIn1->flags & MEM_Int ){
61587 sqlite3VdbeMemRealify(pIn1);
61588 }
61589 break;
61590 }
@@ -61027,10 +61600,11 @@
61600 **
61601 ** A NULL value is not changed by this routine. It remains NULL.
61602 */
61603 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
61604 pIn1 = &aMem[pOp->p1];
61605 memAboutToChange(p, pIn1);
61606 if( pIn1->flags & MEM_Null ) break;
61607 assert( MEM_Str==(MEM_Blob>>3) );
61608 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
61609 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61610 rc = ExpandBlob(pIn1);
@@ -61049,10 +61623,11 @@
61623 **
61624 ** A NULL value is not changed by this routine. It remains NULL.
61625 */
61626 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
61627 pIn1 = &aMem[pOp->p1];
61628 memAboutToChange(p, pIn1);
61629 if( pIn1->flags & MEM_Null ) break;
61630 if( (pIn1->flags & MEM_Blob)==0 ){
61631 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61632 assert( pIn1->flags & MEM_Str || db->mallocFailed );
61633 MemSetTypeFlag(pIn1, MEM_Blob);
@@ -61073,28 +61648,30 @@
61648 **
61649 ** A NULL value is not changed by this routine. It remains NULL.
61650 */
61651 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
61652 pIn1 = &aMem[pOp->p1];
61653 memAboutToChange(p, pIn1);
61654 if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
61655 sqlite3VdbeMemNumerify(pIn1);
61656 }
61657 break;
61658 }
61659 #endif /* SQLITE_OMIT_CAST */
61660
61661 /* Opcode: ToInt P1 * * * *
61662 **
61663 ** Force the value in register P1 to be an integer. If
61664 ** The value is currently a real number, drop its fractional part.
61665 ** If the value is text or blob, try to convert it to an integer using the
61666 ** equivalent of atoi() and store 0 if no such conversion is possible.
61667 **
61668 ** A NULL value is not changed by this routine. It remains NULL.
61669 */
61670 case OP_ToInt: { /* same as TK_TO_INT, in1 */
61671 pIn1 = &aMem[pOp->p1];
61672 memAboutToChange(p, pIn1);
61673 if( (pIn1->flags & MEM_Null)==0 ){
61674 sqlite3VdbeMemIntegerify(pIn1);
61675 }
61676 break;
61677 }
@@ -61109,10 +61686,11 @@
61686 **
61687 ** A NULL value is not changed by this routine. It remains NULL.
61688 */
61689 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
61690 pIn1 = &aMem[pOp->p1];
61691 memAboutToChange(p, pIn1);
61692 if( (pIn1->flags & MEM_Null)==0 ){
61693 sqlite3VdbeMemRealify(pIn1);
61694 }
61695 break;
61696 }
@@ -61123,11 +61701,11 @@
61701 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
61702 ** jump to address P2.
61703 **
61704 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
61705 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
61706 ** bit is clear then fall through if either operand is NULL.
61707 **
61708 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
61709 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
61710 ** to coerce both inputs according to this affinity before the
61711 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
@@ -61203,10 +61781,12 @@
61781 u16 flags3; /* Copy of initial value of pIn3->flags */
61782 #endif /* local variables moved into u.ai */
61783
61784 pIn1 = &aMem[pOp->p1];
61785 pIn3 = &aMem[pOp->p3];
61786 memAboutToChange(p, pIn1);
61787 memAboutToChange(p, pIn3);
61788 u.ai.flags1 = pIn1->flags;
61789 u.ai.flags3 = pIn3->flags;
61790 if( (pIn1->flags | pIn3->flags)&MEM_Null ){
61791 /* One or both operands are NULL */
61792 if( pOp->p5 & SQLITE_NULLEQ ){
@@ -61253,10 +61833,11 @@
61833 default: u.ai.res = u.ai.res>=0; break;
61834 }
61835
61836 if( pOp->p5 & SQLITE_STOREP2 ){
61837 pOut = &aMem[pOp->p2];
61838 memAboutToChange(p, pOut);
61839 MemSetTypeFlag(pOut, MEM_Int);
61840 pOut->u.i = u.ai.res;
61841 REGISTER_TRACE(pOp->p2, pOut);
61842 }else if( u.ai.res ){
61843 pc = pOp->p2-1;
@@ -61284,12 +61865,12 @@
61865 break;
61866 }
61867
61868 /* Opcode: Compare P1 P2 P3 P4 *
61869 **
61870 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
61871 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
61872 ** the comparison for use by the next OP_Jump instruct.
61873 **
61874 ** P4 is a KeyInfo structure that defines collating sequences and sort
61875 ** orders for the comparison. The permutation applies to registers
61876 ** only. The KeyInfo elements are used sequentially.
@@ -61327,10 +61908,12 @@
61908 assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
61909 }
61910 #endif /* SQLITE_DEBUG */
61911 for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
61912 u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
61913 assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
61914 assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
61915 REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
61916 REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
61917 assert( u.aj.i<u.aj.pKeyInfo->nField );
61918 u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
61919 u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
@@ -61558,10 +62141,11 @@
62141 u.am.pC = 0;
62142 memset(&u.am.sMem, 0, sizeof(u.am.sMem));
62143 assert( u.am.p1<p->nCursor );
62144 assert( pOp->p3>0 && pOp->p3<=p->nMem );
62145 u.am.pDest = &aMem[pOp->p3];
62146 memAboutToChange(p, u.am.pDest);
62147 MemSetTypeFlag(u.am.pDest, MEM_Null);
62148 u.am.zRec = 0;
62149
62150 /* This block sets the variable u.am.payloadSize to be the total number of
62151 ** bytes in the record.
@@ -61605,10 +62189,11 @@
62189 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
62190 }
62191 }else if( u.am.pC->pseudoTableReg>0 ){
62192 u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
62193 assert( u.am.pReg->flags & MEM_Blob );
62194 assert( memIsValid(u.am.pReg) );
62195 u.am.payloadSize = u.am.pReg->n;
62196 u.am.zRec = u.am.pReg->z;
62197 u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
62198 assert( u.am.payloadSize==0 || u.am.zRec!=0 );
62199 }else{
@@ -61829,25 +62414,24 @@
62414 assert( u.an.zAffinity!=0 );
62415 assert( u.an.zAffinity[pOp->p2]==0 );
62416 pIn1 = &aMem[pOp->p1];
62417 while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
62418 assert( pIn1 <= &p->aMem[p->nMem] );
62419 assert( memIsValid(pIn1) );
62420 memAboutToChange(p, pIn1);
62421 ExpandBlob(pIn1);
62422 applyAffinity(pIn1, u.an.cAff, encoding);
62423 pIn1++;
62424 }
62425 break;
62426 }
62427
62428 /* Opcode: MakeRecord P1 P2 P3 P4 *
62429 **
62430 ** Convert P2 registers beginning with P1 into the [record format]
62431 ** use as a data record in a database table or as a key
62432 ** in an index. The OP_Column opcode can decode the record later.
 
 
 
62433 **
62434 ** P4 may be a string that is P2 characters long. The nth character of the
62435 ** string indicates the column affinity that should be used for the nth
62436 ** field of the index key.
62437 **
@@ -61899,16 +62483,23 @@
62483 assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
62484 u.ao.pData0 = &aMem[u.ao.nField];
62485 u.ao.nField = pOp->p2;
62486 u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
62487 u.ao.file_format = p->minWriteFileFormat;
62488
62489 /* Identify the output register */
62490 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
62491 pOut = &aMem[pOp->p3];
62492 memAboutToChange(p, pOut);
62493
62494 /* Loop through the elements that will make up the record to figure
62495 ** out how much space is required for the new record.
62496 */
62497 for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62498 assert( memIsValid(u.ao.pRec) );
62499 if( u.ao.zAffinity ){
62500 memAboutToChange(p, u.ao.pRec);
62501 applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
62502 }
62503 if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
62504 sqlite3VdbeMemExpandBlob(u.ao.pRec);
62505 }
@@ -61938,12 +62529,10 @@
62529 /* Make sure the output register has a buffer large enough to store
62530 ** the new record. The output register (pOp->p3) is not allowed to
62531 ** be one of the input registers (because the following call to
62532 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
62533 */
 
 
62534 if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
62535 goto no_mem;
62536 }
62537 u.ao.zNewRecord = (u8 *)pOut->z;
62538
@@ -62112,10 +62701,11 @@
62701 }
62702 }
62703 if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
62704 sqlite3ExpirePreparedStatements(db);
62705 sqlite3ResetInternalSchema(db, 0);
62706 db->flags = (db->flags | SQLITE_InternChanges);
62707 }
62708 }
62709
62710 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
62711 ** savepoints nested inside of the savepoint being operated on. */
@@ -62502,10 +63092,12 @@
63092 }
63093 if( pOp->p5 ){
63094 assert( u.aw.p2>0 );
63095 assert( u.aw.p2<=p->nMem );
63096 pIn2 = &aMem[u.aw.p2];
63097 assert( memIsValid(pIn2) );
63098 assert( (pIn2->flags & MEM_Int)!=0 );
63099 sqlite3VdbeMemIntegerify(pIn2);
63100 u.aw.p2 = (int)pIn2->u.i;
63101 /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
63102 ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
63103 ** If there were a failure, the prepared statement would have halted
@@ -62524,10 +63116,11 @@
63116 }
63117 assert( pOp->p1>=0 );
63118 u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
63119 if( u.aw.pCur==0 ) goto no_mem;
63120 u.aw.pCur->nullRow = 1;
63121 u.aw.pCur->isOrdered = 1;
63122 rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
63123 u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
63124
63125 /* Since it performs no memory allocation or IO, the only values that
63126 ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
@@ -62576,11 +63169,11 @@
63169 case OP_OpenAutoindex:
63170 case OP_OpenEphemeral: {
63171 #if 0 /* local variables moved into u.ax */
63172 VdbeCursor *pCx;
63173 #endif /* local variables moved into u.ax */
63174 static const int vfsFlags =
63175 SQLITE_OPEN_READWRITE |
63176 SQLITE_OPEN_CREATE |
63177 SQLITE_OPEN_EXCLUSIVE |
63178 SQLITE_OPEN_DELETEONCLOSE |
63179 SQLITE_OPEN_TRANSIENT_DB;
@@ -62587,25 +63180,25 @@
63180
63181 assert( pOp->p1>=0 );
63182 u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
63183 if( u.ax.pCx==0 ) goto no_mem;
63184 u.ax.pCx->nullRow = 1;
63185 rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
63186 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
63187 if( rc==SQLITE_OK ){
63188 rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
63189 }
63190 if( rc==SQLITE_OK ){
63191 /* If a transient index is required, create it by calling
63192 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
63193 ** opening it. If a transient table is required, just use the
63194 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
63195 */
63196 if( pOp->p4.pKeyInfo ){
63197 int pgno;
63198 assert( pOp->p4type==P4_KEYINFO );
63199 rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
63200 if( rc==SQLITE_OK ){
63201 assert( pgno==MASTER_ROOT+1 );
63202 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
63203 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
63204 u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
@@ -62615,10 +63208,11 @@
63208 }else{
63209 rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
63210 u.ax.pCx->isTable = 1;
63211 }
63212 }
63213 u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
63214 u.ax.pCx->isIndex = !u.ax.pCx->isTable;
63215 break;
63216 }
63217
63218 /* Opcode: OpenPseudo P1 P2 P3 * *
@@ -62734,10 +63328,11 @@
63328 assert( u.az.pC!=0 );
63329 assert( u.az.pC->pseudoTableReg==0 );
63330 assert( OP_SeekLe == OP_SeekLt+1 );
63331 assert( OP_SeekGe == OP_SeekLt+2 );
63332 assert( OP_SeekGt == OP_SeekLt+3 );
63333 assert( u.az.pC->isOrdered );
63334 if( u.az.pC->pCursor!=0 ){
63335 u.az.oc = pOp->opcode;
63336 u.az.pC->nullRow = 0;
63337 if( u.az.pC->isTable ){
63338 /* The input value in P3 might be of any type: integer, real, string,
@@ -62816,10 +63411,13 @@
63411 assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
63412 assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
63413 assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
63414
63415 u.az.r.aMem = &aMem[pOp->p3];
63416 #ifdef SQLITE_DEBUG
63417 { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
63418 #endif
63419 ExpandBlob(u.az.r.aMem);
63420 rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
63421 if( rc!=SQLITE_OK ){
63422 goto abort_due_to_error;
63423 }
@@ -62944,15 +63542,18 @@
63542 assert( u.bb.pC->isTable==0 );
63543 if( pOp->p4.i>0 ){
63544 u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
63545 u.bb.r.nField = (u16)pOp->p4.i;
63546 u.bb.r.aMem = pIn3;
63547 #ifdef SQLITE_DEBUG
63548 { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
63549 #endif
63550 u.bb.r.flags = UNPACKED_PREFIX_MATCH;
63551 u.bb.pIdxKey = &u.bb.r;
63552 }else{
63553 assert( pIn3->flags & MEM_Blob );
63554 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
63555 u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
63556 u.bb.aTempRec, sizeof(u.bb.aTempRec));
63557 if( u.bb.pIdxKey==0 ){
63558 goto no_mem;
63559 }
@@ -63043,10 +63644,13 @@
63644 /* Populate the index search key. */
63645 u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
63646 u.bc.r.nField = u.bc.nField + 1;
63647 u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
63648 u.bc.r.aMem = u.bc.aMx;
63649 #ifdef SQLITE_DEBUG
63650 { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
63651 #endif
63652
63653 /* Extract the value of u.bc.R from register P3. */
63654 sqlite3VdbeMemIntegerify(pIn3);
63655 u.bc.R = pIn3->u.i;
63656
@@ -63065,11 +63669,11 @@
63669
63670 /* Opcode: NotExists P1 P2 P3 * *
63671 **
63672 ** Use the content of register P3 as a integer key. If a record
63673 ** with that key does not exist in table of P1, then jump to P2.
63674 ** If the record does exist, then fall through. The cursor is left
63675 ** pointing to the record if it exists.
63676 **
63677 ** The difference between this operation and NotFound is that this
63678 ** operation assumes the key is an integer and that P1 is a table whereas
63679 ** NotFound assumes key is a blob constructed from MakeRecord and
@@ -63223,11 +63827,13 @@
63827 u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
63828 }else{
63829 /* Assert that P3 is a valid memory cell. */
63830 assert( pOp->p3<=p->nMem );
63831 u.be.pMem = &aMem[pOp->p3];
63832 memAboutToChange(p, u.be.pMem);
63833 }
63834 assert( memIsValid(u.be.pMem) );
63835
63836 REGISTER_TRACE(pOp->p3, u.be.pMem);
63837 sqlite3VdbeMemIntegerify(u.be.pMem);
63838 assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
63839 if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
@@ -63242,33 +63848,40 @@
63848 #endif
63849
63850 sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
63851 }
63852 if( u.be.pC->useRandomRowid ){
63853 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
63854 ** largest possible integer (9223372036854775807) then the database
63855 ** engine starts picking positive candidate ROWIDs at random until
63856 ** it finds one that is not previously used. */
 
63857 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
63858 ** an AUTOINCREMENT table. */
63859 /* on the first attempt, simply do one more than previous */
63860 u.be.v = db->lastRowid;
63861 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
63862 u.be.v++; /* ensure non-zero */
63863 u.be.cnt = 0;
63864 while( ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
63865 0, &u.be.res))==SQLITE_OK)
63866 && (u.be.res==0)
63867 && (++u.be.cnt<100)){
63868 /* collision - try another random rowid */
63869 sqlite3_randomness(sizeof(u.be.v), &u.be.v);
63870 if( u.be.cnt<5 ){
63871 /* try "small" random rowids for the initial attempts */
63872 u.be.v &= 0xffffff;
63873 }else{
63874 u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
 
63875 }
63876 u.be.v++; /* ensure non-zero */
63877 }
 
63878 if( rc==SQLITE_OK && u.be.res==0 ){
63879 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
63880 goto abort_due_to_error;
63881 }
63882 assert( u.be.v>0 ); /* EV: R-40812-03570 */
63883 }
63884 u.be.pC->rowidIsValid = 0;
63885 u.be.pC->deferredMoveto = 0;
63886 u.be.pC->cacheStatus = CACHE_STALE;
63887 }
@@ -63334,10 +63947,11 @@
63947 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63948 #endif /* local variables moved into u.bf */
63949
63950 u.bf.pData = &aMem[pOp->p2];
63951 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63952 assert( memIsValid(u.bf.pData) );
63953 u.bf.pC = p->apCsr[pOp->p1];
63954 assert( u.bf.pC!=0 );
63955 assert( u.bf.pC->pCursor!=0 );
63956 assert( u.bf.pC->pseudoTableReg==0 );
63957 assert( u.bf.pC->isTable );
@@ -63344,10 +63958,11 @@
63958 REGISTER_TRACE(pOp->p2, u.bf.pData);
63959
63960 if( pOp->opcode==OP_Insert ){
63961 u.bf.pKey = &aMem[pOp->p3];
63962 assert( u.bf.pKey->flags & MEM_Int );
63963 assert( memIsValid(u.bf.pKey) );
63964 REGISTER_TRACE(pOp->p3, u.bf.pKey);
63965 u.bf.iKey = u.bf.pKey->u.i;
63966 }else{
63967 assert( pOp->opcode==OP_InsertInt );
63968 u.bf.iKey = pOp->p3;
@@ -63495,10 +64110,11 @@
64110 u32 n;
64111 i64 n64;
64112 #endif /* local variables moved into u.bh */
64113
64114 pOut = &aMem[pOp->p2];
64115 memAboutToChange(p, pOut);
64116
64117 /* Note that RowKey and RowData are really exactly the same instruction */
64118 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64119 u.bh.pC = p->apCsr[pOp->p1];
64120 assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
@@ -63837,10 +64453,13 @@
64453 if( ALWAYS(u.bo.pCrsr!=0) ){
64454 u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
64455 u.bo.r.nField = (u16)pOp->p3;
64456 u.bo.r.flags = 0;
64457 u.bo.r.aMem = &aMem[pOp->p2];
64458 #ifdef SQLITE_DEBUG
64459 { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
64460 #endif
64461 rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
64462 if( rc==SQLITE_OK && u.bo.res==0 ){
64463 rc = sqlite3BtreeDelete(u.bo.pCrsr);
64464 }
64465 assert( u.bo.pC->deferredMoveto==0 );
@@ -63921,10 +64540,11 @@
64540 #endif /* local variables moved into u.bq */
64541
64542 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64543 u.bq.pC = p->apCsr[pOp->p1];
64544 assert( u.bq.pC!=0 );
64545 assert( u.bq.pC->isOrdered );
64546 if( ALWAYS(u.bq.pC->pCursor!=0) ){
64547 assert( u.bq.pC->deferredMoveto==0 );
64548 assert( pOp->p5==0 || pOp->p5==1 );
64549 assert( pOp->p4type==P4_INT32 );
64550 u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
@@ -63933,10 +64553,13 @@
64553 u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
64554 }else{
64555 u.bq.r.flags = UNPACKED_IGNORE_ROWID;
64556 }
64557 u.bq.r.aMem = &aMem[pOp->p3];
64558 #ifdef SQLITE_DEBUG
64559 { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
64560 #endif
64561 rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
64562 if( pOp->opcode==OP_IdxLT ){
64563 u.bq.res = -u.bq.res;
64564 }else{
64565 assert( pOp->opcode==OP_IdxGE );
@@ -64036,10 +64659,12 @@
64659 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
64660 );
64661 if( pOp->p3 ){
64662 p->nChange += u.bs.nChange;
64663 if( pOp->p3>0 ){
64664 assert( memIsValid(&aMem[pOp->p3]) );
64665 memAboutToChange(p, &aMem[pOp->p3]);
64666 aMem[pOp->p3].u.i += u.bs.nChange;
64667 }
64668 }
64669 break;
64670 }
@@ -64079,13 +64704,13 @@
64704 assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64705 u.bt.pDb = &db->aDb[pOp->p1];
64706 assert( u.bt.pDb->pBt!=0 );
64707 if( pOp->opcode==OP_CreateTable ){
64708 /* u.bt.flags = BTREE_INTKEY; */
64709 u.bt.flags = BTREE_INTKEY;
64710 }else{
64711 u.bt.flags = BTREE_BLOBKEY;
64712 }
64713 rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
64714 pOut->u.i = u.bt.pgno;
64715 break;
64716 }
@@ -64410,10 +65035,11 @@
65035 void *t; /* Token identifying trigger */
65036 #endif /* local variables moved into u.by */
65037
65038 u.by.pProgram = pOp->p4.pProgram;
65039 u.by.pRt = &aMem[pOp->p3];
65040 assert( memIsValid(u.by.pRt) );
65041 assert( u.by.pProgram->nOp>0 );
65042
65043 /* If the p5 flag is clear, then recursive invocation of triggers is
65044 ** disabled for backwards compatibility (p5 is set if this sub-program
65045 ** is really a trigger, not a foreign key action, and the flag set
@@ -64583,10 +65209,11 @@
65209 for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
65210 u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
65211 }else{
65212 u.ca.pIn1 = &aMem[pOp->p1];
65213 }
65214 assert( memIsValid(u.ca.pIn1) );
65215 sqlite3VdbeMemIntegerify(u.ca.pIn1);
65216 pIn2 = &aMem[pOp->p2];
65217 sqlite3VdbeMemIntegerify(pIn2);
65218 if( u.ca.pIn1->u.i<pIn2->u.i){
65219 u.ca.pIn1->u.i = pIn2->u.i;
@@ -64669,11 +65296,13 @@
65296 assert( u.cb.n>=0 );
65297 u.cb.pRec = &aMem[pOp->p2];
65298 u.cb.apVal = p->apArg;
65299 assert( u.cb.apVal || u.cb.n==0 );
65300 for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
65301 assert( memIsValid(u.cb.pRec) );
65302 u.cb.apVal[u.cb.i] = u.cb.pRec;
65303 memAboutToChange(p, u.cb.pRec);
65304 sqlite3VdbeMemStoreType(u.cb.pRec);
65305 }
65306 u.cb.ctx.pFunc = pOp->p4.pFunc;
65307 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65308 u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
@@ -64689,11 +65318,11 @@
65318 assert( pOp>p->aOp );
65319 assert( pOp[-1].p4type==P4_COLLSEQ );
65320 assert( pOp[-1].opcode==OP_CollSeq );
65321 u.cb.ctx.pColl = pOp[-1].p4.pColl;
65322 }
65323 (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
65324 if( u.cb.ctx.isError ){
65325 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
65326 rc = u.cb.ctx.isError;
65327 }
65328 sqlite3VdbeMemRelease(&u.cb.ctx.s);
@@ -65076,10 +65705,11 @@
65705 #endif /* local variables moved into u.ch */
65706
65707 u.ch.pQuery = &aMem[pOp->p3];
65708 u.ch.pArgc = &u.ch.pQuery[1];
65709 u.ch.pCur = p->apCsr[pOp->p1];
65710 assert( memIsValid(u.ch.pQuery) );
65711 REGISTER_TRACE(pOp->p3, u.ch.pQuery);
65712 assert( u.ch.pCur->pVtabCursor );
65713 u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
65714 u.ch.pVtab = u.ch.pVtabCursor->pVtab;
65715 u.ch.pModule = u.ch.pVtab->pModule;
@@ -65133,10 +65763,11 @@
65763
65764 VdbeCursor *pCur = p->apCsr[pOp->p1];
65765 assert( pCur->pVtabCursor );
65766 assert( pOp->p3>0 && pOp->p3<=p->nMem );
65767 u.ci.pDest = &aMem[pOp->p3];
65768 memAboutToChange(p, u.ci.pDest);
65769 if( pCur->nullRow ){
65770 sqlite3VdbeMemSetNull(u.ci.pDest);
65771 break;
65772 }
65773 u.ci.pVtab = pCur->pVtabCursor->pVtab;
@@ -65235,14 +65866,16 @@
65866 #endif /* local variables moved into u.ck */
65867
65868 u.ck.pVtab = pOp->p4.pVtab->pVtab;
65869 u.ck.pName = &aMem[pOp->p1];
65870 assert( u.ck.pVtab->pModule->xRename );
65871 assert( memIsValid(u.ck.pName) );
65872 REGISTER_TRACE(pOp->p1, u.ck.pName);
65873 assert( u.ck.pName->flags & MEM_Str );
65874 rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
65875 importVtabErrMsg(p, u.ck.pVtab);
65876 p->expired = 0;
65877
65878 break;
65879 }
65880 #endif
65881
@@ -65287,10 +65920,12 @@
65920 assert( pOp->p4type==P4_VTAB );
65921 if( ALWAYS(u.cl.pModule->xUpdate) ){
65922 u.cl.apArg = p->apArg;
65923 u.cl.pX = &aMem[pOp->p3];
65924 for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
65925 assert( memIsValid(u.cl.pX) );
65926 memAboutToChange(p, u.cl.pX);
65927 sqlite3VdbeMemStoreType(u.cl.pX);
65928 u.cl.apArg[u.cl.i] = u.cl.pX;
65929 u.cl.pX++;
65930 }
65931 rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
@@ -66341,12 +66976,11 @@
66976 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
66977 return pJfd->pMethods==&MemJournalMethods;
66978 }
66979
66980 /*
66981 ** Return the number of bytes required to store a MemJournal file descriptor.
 
66982 */
66983 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
66984 return sizeof(MemJournal);
66985 }
66986
@@ -69226,12 +69860,12 @@
69860 return eType;
69861 }
69862 #endif
69863
69864 /*
69865 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
69866 ** or IN operators. Examples:
69867 **
69868 ** (SELECT a FROM b) -- subquery
69869 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
69870 ** x IN (4,5,11) -- IN operator with list on right-hand side
69871 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
@@ -69290,14 +69924,14 @@
69924 assert( testAddr>0 || pParse->db->mallocFailed );
69925 }
69926
69927 switch( pExpr->op ){
69928 case TK_IN: {
69929 char affinity; /* Affinity of the LHS of the IN */
69930 KeyInfo keyInfo; /* Keyinfo for the generated table */
69931 int addr; /* Address of OP_OpenEphemeral instruction */
69932 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
69933
69934 if( rMayHaveNull ){
69935 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
69936 }
69937
@@ -69316,10 +69950,11 @@
69950 ** 'x' nor the SELECT... statement are columns, then numeric affinity
69951 ** is used.
69952 */
69953 pExpr->iTable = pParse->nTab++;
69954 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
69955 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
69956 memset(&keyInfo, 0, sizeof(keyInfo));
69957 keyInfo.nField = 1;
69958
69959 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69960 /* Case 1: expr IN (SELECT ...)
@@ -69924,77 +70559,10 @@
70559 }
70560 return 0;
70561 }
70562 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
70563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70564 /*
70565 ** Generate code into the current Vdbe to evaluate the given
70566 ** expression. Attempt to store the results in register "target".
70567 ** Return the register where results are stored.
70568 **
@@ -70099,11 +70667,11 @@
70667 case TK_REGISTER: {
70668 inReg = pExpr->iTable;
70669 break;
70670 }
70671 case TK_AS: {
70672 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
70673 break;
70674 }
70675 #ifndef SQLITE_OMIT_CAST
70676 case TK_CAST: {
70677 /* Expressions of the form: CAST(pLeft AS token) */
@@ -70531,10 +71099,15 @@
71099 testcase( regFree1==0 );
71100 cacheX.op = TK_REGISTER;
71101 opCompare.op = TK_EQ;
71102 opCompare.pLeft = &cacheX;
71103 pTest = &opCompare;
71104 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
71105 ** The value in regFree1 might get SCopy-ed into the file result.
71106 ** So make sure that the regFree1 register is not reused for other
71107 ** purposes and possibly overwritten. */
71108 regFree1 = 0;
71109 }
71110 for(i=0; i<nExpr; i=i+2){
71111 sqlite3ExprCachePush(pParse);
71112 if( pX ){
71113 assert( pTest!=0 );
@@ -70624,14 +71197,18 @@
71197 */
71198 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
71199 int inReg;
71200
71201 assert( target>0 && target<=pParse->nMem );
71202 if( pExpr && pExpr->op==TK_REGISTER ){
71203 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
71204 }else{
71205 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
71206 assert( pParse->pVdbe || pParse->db->mallocFailed );
71207 if( inReg!=target && pParse->pVdbe ){
71208 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71209 }
71210 }
71211 return target;
71212 }
71213
71214 /*
@@ -70800,23 +71377,18 @@
71377 ){
71378 struct ExprList_item *pItem;
71379 int i, n;
71380 assert( pList!=0 );
71381 assert( target>0 );
71382 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
71383 n = pList->nExpr;
71384 for(pItem=pList->a, i=0; i<n; i++, pItem++){
71385 Expr *pExpr = pItem->pExpr;
71386 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
71387 if( inReg!=target+i ){
71388 sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
71389 inReg, target+i);
 
 
 
 
 
 
71390 }
71391 }
71392 return n;
71393 }
71394
@@ -71794,10 +72366,15 @@
72366 if( pTrig->pSchema==pTempSchema ){
72367 zWhere = whereOrName(db, zWhere, pTrig->zName);
72368 }
72369 }
72370 }
72371 if( zWhere ){
72372 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
72373 sqlite3DbFree(pParse->db, zWhere);
72374 zWhere = zNew;
72375 }
72376 return zWhere;
72377 }
72378
72379 /*
72380 ** Generate code to drop and reload the internal representation of table
@@ -72401,11 +72978,12 @@
72978 int iIdxCur; /* Cursor open on index being analyzed */
72979 Vdbe *v; /* The virtual machine being built up */
72980 int i; /* Loop counter */
72981 int topOfLoop; /* The top of the loop */
72982 int endOfLoop; /* The end of the loop */
72983 int addr = 0; /* The address of an instruction */
72984 int jZeroRows = 0; /* Jump from here if number of rows is zero */
72985 int iDb; /* Index of database containing pTab */
72986 int regTabname = iMem++; /* Register containing table name */
72987 int regIdxname = iMem++; /* Register containing index name */
72988 int regSampleno = iMem++; /* Register containing next sample number */
72989 int regCol = iMem++; /* Content of a column analyzed table */
@@ -72420,12 +72998,19 @@
72998 int regLast = iMem++; /* Index of last sample to record */
72999 int regFirst = iMem++; /* Index of first sample to record */
73000 #endif
73001
73002 v = sqlite3GetVdbe(pParse);
73003 if( v==0 || NEVER(pTab==0) ){
73004 return;
73005 }
73006 if( pTab->tnum==0 ){
73007 /* Do not gather statistics on views or virtual tables */
73008 return;
73009 }
73010 if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
73011 /* Do not gather statistics on system tables */
73012 return;
73013 }
73014 assert( sqlite3BtreeHoldsAllMutexes(db) );
73015 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73016 assert( iDb>=0 );
@@ -72438,10 +73023,11 @@
73023
73024 /* Establish a read-lock on the table at the shared-cache level. */
73025 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
73026
73027 iIdxCur = pParse->nTab++;
73028 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
73029 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
73030 int nCol = pIdx->nColumn;
73031 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
73032
73033 if( iMem+1+(nCol*2)>pParse->nMem ){
@@ -72452,14 +73038,11 @@
73038 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
73039 sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
73040 (char *)pKey, P4_KEYINFO_HANDOFF);
73041 VdbeComment((v, "%s", pIdx->zName));
73042
73043 /* Populate the register containing the index name. */
 
 
 
73044 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
73045
73046 #ifdef SQLITE_ENABLE_STAT2
73047
73048 /* If this iteration of the loop is generating code to analyze the
@@ -72590,12 +73173,14 @@
73173 **
73174 ** If K==0 then no entry is made into the sqlite_stat1 table.
73175 ** If K>0 then it is always the case the D>0 so division by zero
73176 ** is never possible.
73177 */
 
73178 sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
73179 if( jZeroRows==0 ){
73180 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
73181 }
73182 for(i=0; i<nCol; i++){
73183 sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
73184 sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73185 sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
73186 sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
@@ -72605,17 +73190,39 @@
73190 }
73191 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73192 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73193 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73194 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73195 }
73196
73197 /* If the table has no indices, create a single sqlite_stat1 entry
73198 ** containing NULL as the index name and the row count as the content.
73199 */
73200 if( pTab->pIndex==0 ){
73201 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
73202 VdbeComment((v, "%s", pTab->zName));
73203 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
73204 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73205 }else{
73206 assert( jZeroRows>0 );
73207 addr = sqlite3VdbeAddOp0(v, OP_Goto);
73208 sqlite3VdbeJumpHere(v, jZeroRows);
73209 }
73210 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
73211 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73212 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73213 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73214 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73215 if( pParse->nMem<regRec ) pParse->nMem = regRec;
73216 if( jZeroRows ){
73217 sqlite3VdbeJumpHere(v, addr);
73218 }
73219 }
73220
73221 /*
73222 ** Generate code that will cause the most recent index analysis to
73223 ** be loaded into internal hash tables where is can be used.
73224 */
73225 static void loadAnalysis(Parse *pParse, int iDb){
73226 Vdbe *v = sqlite3GetVdbe(pParse);
73227 if( v ){
73228 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
@@ -72741,37 +73348,50 @@
73348
73349 /*
73350 ** This callback is invoked once for each index when reading the
73351 ** sqlite_stat1 table.
73352 **
73353 ** argv[0] = name of the table
73354 ** argv[1] = name of the index (might be NULL)
73355 ** argv[2] = results of analysis - on integer for each column
73356 **
73357 ** Entries for which argv[1]==NULL simply record the number of rows in
73358 ** the table.
73359 */
73360 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
73361 analysisInfo *pInfo = (analysisInfo*)pData;
73362 Index *pIndex;
73363 Table *pTable;
73364 int i, c, n;
73365 unsigned int v;
73366 const char *z;
73367
73368 assert( argc==3 );
73369 UNUSED_PARAMETER2(NotUsed, argc);
73370
73371 if( argv==0 || argv[0]==0 || argv[2]==0 ){
73372 return 0;
73373 }
73374 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
73375 if( pTable==0 ){
73376 return 0;
73377 }
73378 if( argv[1] ){
73379 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
73380 }else{
73381 pIndex = 0;
73382 }
73383 n = pIndex ? pIndex->nColumn : 0;
73384 z = argv[2];
73385 for(i=0; *z && i<=n; i++){
73386 v = 0;
73387 while( (c=z[0])>='0' && c<='9' ){
73388 v = v*10 + c - '0';
73389 z++;
73390 }
73391 if( i==0 ) pTable->nRowEst = v;
73392 if( pIndex==0 ) break;
73393 pIndex->aiRowEst[i] = v;
73394 if( *z==' ' ) z++;
73395 }
73396 return 0;
73397 }
@@ -72843,11 +73463,11 @@
73463 return SQLITE_ERROR;
73464 }
73465
73466 /* Load new statistics out of the sqlite_stat1 table */
73467 zSql = sqlite3MPrintf(db,
73468 "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
73469 if( zSql==0 ){
73470 rc = SQLITE_NOMEM;
73471 }else{
73472 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
73473 sqlite3DbFree(db, zSql);
@@ -73060,13 +73680,12 @@
73680
73681 /* Open the database file. If the btree is successfully opened, use
73682 ** it to obtain the database schema. At this point the schema may
73683 ** or may not be initialised.
73684 */
73685 rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
73686 db->openFlags | SQLITE_OPEN_MAIN_DB);
 
73687 db->nDb++;
73688 if( rc==SQLITE_CONSTRAINT ){
73689 rc = SQLITE_ERROR;
73690 zErrDyn = sqlite3MPrintf(db, "database is already attached");
73691 }else if( rc==SQLITE_OK ){
@@ -73303,11 +73922,12 @@
73922 0, /* pNext */
73923 detachFunc, /* xFunc */
73924 0, /* xStep */
73925 0, /* xFinalize */
73926 "sqlite_detach", /* zName */
73927 0, /* pHash */
73928 0 /* pDestructor */
73929 };
73930 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
73931 }
73932
73933 /*
@@ -73324,11 +73944,12 @@
73944 0, /* pNext */
73945 attachFunc, /* xFunc */
73946 0, /* xStep */
73947 0, /* xFinalize */
73948 "sqlite_attach", /* zName */
73949 0, /* pHash */
73950 0 /* pDestructor */
73951 };
73952 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
73953 }
73954 #endif /* SQLITE_OMIT_ATTACH */
73955
@@ -74453,12 +75074,13 @@
75074 ** set to the index of the database that the table or view is to be
75075 ** created in.
75076 */
75077 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75078 if( iDb<0 ) return;
75079 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
75080 /* If creating a temp table, the name may not be qualified. Unless
75081 ** the database name is "temp" anyway. */
75082 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
75083 return;
75084 }
75085 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
75086
@@ -74502,21 +75124,22 @@
75124 ** to an sqlite3_declare_vtab() call. In that case only the column names
75125 ** and types will be used, so there is no need to test for namespace
75126 ** collisions.
75127 */
75128 if( !IN_DECLARE_VTAB ){
75129 char *zDb = db->aDb[iDb].zName;
75130 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75131 goto begin_table_error;
75132 }
75133 pTable = sqlite3FindTable(db, zName, zDb);
75134 if( pTable ){
75135 if( !noErr ){
75136 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
75137 }
75138 goto begin_table_error;
75139 }
75140 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
75141 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
75142 goto begin_table_error;
75143 }
75144 }
75145
@@ -74529,10 +75152,11 @@
75152 }
75153 pTable->zName = zName;
75154 pTable->iPKey = -1;
75155 pTable->pSchema = db->aDb[iDb].pSchema;
75156 pTable->nRef = 1;
75157 pTable->nRowEst = 1000000;
75158 assert( pParse->pNewTable==0 );
75159 pParse->pNewTable = pTable;
75160
75161 /* If this is the magic sqlite_sequence table used by autoincrement,
75162 ** then record a pointer to this table in the main database structure
@@ -75375,16 +75999,14 @@
75999 sqlite3SelectDelete(db, pSelect);
76000 return;
76001 }
76002 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
76003 p = pParse->pNewTable;
76004 if( p==0 || pParse->nErr ){
76005 sqlite3SelectDelete(db, pSelect);
76006 return;
76007 }
 
 
76008 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76009 iDb = sqlite3SchemaToIndex(db, p->pSchema);
76010 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
76011 && sqlite3FixSelect(&sFix, pSelect)
76012 ){
@@ -76498,11 +77120,12 @@
77120 */
77121 if( pTblName ){
77122 sqlite3RefillIndex(pParse, pIndex, iMem);
77123 sqlite3ChangeCookie(pParse, iDb);
77124 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
77125 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
77126 P4_DYNAMIC);
77127 sqlite3VdbeAddOp1(v, OP_Expire, 0);
77128 }
77129 }
77130
77131 /* When adding an index to the list of indices for a table, make
@@ -76559,18 +77182,18 @@
77182 ** are based on typical values found in actual indices.
77183 */
77184 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
77185 unsigned *a = pIdx->aiRowEst;
77186 int i;
77187 unsigned n;
77188 assert( a!=0 );
77189 a[0] = pIdx->pTable->nRowEst;
77190 if( a[0]<10 ) a[0] = 10;
77191 n = 10;
77192 for(i=1; i<=pIdx->nColumn; i++){
77193 a[i] = n;
77194 if( n>5 ) n--;
 
77195 }
77196 if( pIdx->onError!=OE_None ){
77197 a[pIdx->nColumn] = 1;
77198 }
77199 }
@@ -76626,11 +77249,11 @@
77249 /* Generate code to remove the index and from the master table */
77250 v = sqlite3GetVdbe(pParse);
77251 if( v ){
77252 sqlite3BeginWriteOperation(pParse, 1, iDb);
77253 sqlite3NestedParse(pParse,
77254 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
77255 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77256 pIndex->zName
77257 );
77258 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
77259 sqlite3NestedParse(pParse,
@@ -77118,11 +77741,11 @@
77741 SQLITE_OPEN_CREATE |
77742 SQLITE_OPEN_EXCLUSIVE |
77743 SQLITE_OPEN_DELETEONCLOSE |
77744 SQLITE_OPEN_TEMP_DB;
77745
77746 rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
77747 if( rc!=SQLITE_OK ){
77748 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
77749 "file for storing temporary tables");
77750 pParse->rc = rc;
77751 return 1;
@@ -77775,11 +78398,11 @@
78398 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
78399 ** functions even if a prior app-defined function was found. And give
78400 ** priority to built-in functions.
78401 **
78402 ** Except, if createFlag is true, that means that we are trying to
78403 ** install a new function. Whatever FuncDef structure is returned it will
78404 ** have fields overwritten with new information appropriate for the
78405 ** new function. But the FuncDefs for built-in functions are read-only.
78406 ** So we must not search for built-ins when creating a new function.
78407 */
78408 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
@@ -79956,14 +80579,14 @@
80579 if( caseSensitive ){
80580 pInfo = (struct compareInfo*)&likeInfoAlt;
80581 }else{
80582 pInfo = (struct compareInfo*)&likeInfoNorm;
80583 }
80584 sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80585 sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80586 sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
80587 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
80588 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
80589 setLikeOptFlag(db, "like",
80590 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
80591 }
80592
@@ -80043,14 +80666,14 @@
80666 FUNCTION(upper, 1, 0, 0, upperFunc ),
80667 FUNCTION(lower, 1, 0, 0, lowerFunc ),
80668 FUNCTION(coalesce, 1, 0, 0, 0 ),
80669 FUNCTION(coalesce, 0, 0, 0, 0 ),
80670 /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
80671 {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
80672 FUNCTION(hex, 1, 0, 0, hexFunc ),
80673 /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
80674 {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
80675 FUNCTION(random, 0, 0, 0, randomFunc ),
80676 FUNCTION(randomblob, 1, 0, 0, randomBlob ),
80677 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
80678 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
80679 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
@@ -80073,11 +80696,11 @@
80696 #endif
80697 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
80698 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
80699 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
80700 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
80701 {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
80702 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
80703 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
80704 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
80705
80706 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
@@ -80484,11 +81107,11 @@
81107 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81108
81109 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
81110 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
81111 for(i=0; i<nCol; i++){
81112 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
81113 }
81114
81115 /* If the parent table is the same as the child table, and we are about
81116 ** to increment the constraint-counter (i.e. this is an INSERT operation),
81117 ** then check if the row being inserted matches itself. If so, do not
@@ -87131,15 +87754,17 @@
87754 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
87755 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
87756 sqlite3ReleaseTempReg(pParse, r1);
87757 }
87758
87759 #ifndef SQLITE_OMIT_SUBQUERY
87760 /*
87761 ** Generate an error message when a SELECT is used within a subexpression
87762 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
87763 ** column. We do this in a subroutine because the error used to occur
87764 ** in multiple places. (The error only occurs in one place now, but we
87765 ** retain the subroutine to minimize code disruption.)
87766 */
87767 static int checkForMultiColumnSelectError(
87768 Parse *pParse, /* Parse context. */
87769 SelectDest *pDest, /* Destination of SELECT results */
87770 int nExpr /* Number of result columns returned by SELECT */
@@ -87151,10 +87776,11 @@
87776 return 1;
87777 }else{
87778 return 0;
87779 }
87780 }
87781 #endif
87782
87783 /*
87784 ** This routine generates the code for the inside of the inner loop
87785 ** of a SELECT.
87786 **
@@ -87230,14 +87856,10 @@
87856 if( pOrderBy==0 ){
87857 codeOffset(v, p, iContinue);
87858 }
87859 }
87860
 
 
 
 
87861 switch( eDest ){
87862 /* In this mode, write each query result to the key of the temporary
87863 ** table iParm.
87864 */
87865 #ifndef SQLITE_OMIT_COMPOUND_SELECT
@@ -88143,10 +88765,11 @@
88765 /* Create the destination temporary table if necessary
88766 */
88767 if( dest.eDest==SRT_EphemTab ){
88768 assert( p->pEList );
88769 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
88770 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
88771 dest.eDest = SRT_Table;
88772 }
88773
88774 /* Make sure all SELECTs in the statement have the same number of elements
88775 ** in their result sets.
@@ -90105,11 +90728,11 @@
90728 ExprList *pList = pF->pExpr->x.pList;
90729 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
90730 if( pList ){
90731 nArg = pList->nExpr;
90732 regAgg = sqlite3GetTempRange(pParse, nArg);
90733 sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
90734 }else{
90735 nArg = 0;
90736 regAgg = 0;
90737 }
90738 if( pF->iDistinct>=0 ){
@@ -90264,10 +90887,19 @@
90887
90888 /* Begin generating code.
90889 */
90890 v = sqlite3GetVdbe(pParse);
90891 if( v==0 ) goto select_end;
90892
90893 /* If writing to memory or generating a set
90894 ** only a single column may be output.
90895 */
90896 #ifndef SQLITE_OMIT_SUBQUERY
90897 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
90898 goto select_end;
90899 }
90900 #endif
90901
90902 /* Generate code for all sub-queries in the FROM clause
90903 */
90904 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90905 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
@@ -90338,19 +90970,10 @@
90970 }
90971 return multiSelect(pParse, p, pDest);
90972 }
90973 #endif
90974
 
 
 
 
 
 
 
 
 
90975 /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
90976 ** GROUP BY might use an index, DISTINCT never does.
90977 */
90978 assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
90979 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
@@ -90409,10 +91032,11 @@
91032 assert( isAgg || pGroupBy );
91033 distinct = pParse->nTab++;
91034 pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
91035 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
91036 (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91037 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91038 }else{
91039 distinct = -1;
91040 }
91041
91042 /* Aggregate and non-aggregate queries are handled differently */
@@ -92884,10 +93508,11 @@
93508 ** be stored.
93509 */
93510 assert( v );
93511 ephemTab = pParse->nTab++;
93512 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
93513 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93514
93515 /* fill the ephemeral table
93516 */
93517 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
93518 sqlite3Select(pParse, pSelect, &dest);
@@ -93022,10 +93647,14 @@
93647 int nDb; /* Number of attached databases */
93648
93649 if( !db->autoCommit ){
93650 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
93651 return SQLITE_ERROR;
93652 }
93653 if( db->activeVdbeCnt>1 ){
93654 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
93655 return SQLITE_ERROR;
93656 }
93657
93658 /* Save the current value of the database flags so that it can be
93659 ** restored before returning. Then set the writable-schema flag, and
93660 ** disable CHECK and foreign key constraints. */
@@ -93624,11 +94253,11 @@
94253 sqlite3DbFree(db, zStmt);
94254 v = sqlite3GetVdbe(pParse);
94255 sqlite3ChangeCookie(pParse, iDb);
94256
94257 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
94258 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
94259 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
94260 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
94261 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
94262 }
94263
@@ -94864,15 +95493,16 @@
95493 if( op==TK_REGISTER ){
95494 op = pRight->op2;
95495 }
95496 if( op==TK_VARIABLE ){
95497 Vdbe *pReprepare = pParse->pReprepare;
95498 int iCol = pRight->iColumn;
95499 pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
95500 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
95501 z = (char *)sqlite3_value_text(pVal);
95502 }
95503 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
95504 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
95505 }else if( op==TK_STRING ){
95506 z = pRight->u.zToken;
95507 }
95508 if( z ){
@@ -94886,11 +95516,11 @@
95516 pPrefix = sqlite3Expr(db, TK_STRING, z);
95517 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
95518 *ppPrefix = pPrefix;
95519 if( op==TK_VARIABLE ){
95520 Vdbe *v = pParse->pVdbe;
95521 sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
95522 if( *pisComplete && pRight->u.zToken[1] ){
95523 /* If the rhs of the LIKE expression is a variable, and the current
95524 ** value of the variable means there is no need to invoke the LIKE
95525 ** function, then no OP_Variable will be added to the program.
95526 ** This causes problems for the sqlite3_bind_parameter_name()
@@ -95900,11 +96530,11 @@
96530 return;
96531 }
96532
96533 assert( pParse->nQueryLoop >= (double)1 );
96534 pTable = pSrc->pTab;
96535 nTableRow = pTable->nRowEst;
96536 logN = estLog(nTableRow);
96537 costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
96538 if( costTempIdx>=pCost->rCost ){
96539 /* The cost of creating the transient table would be greater than
96540 ** doing the full table scan */
@@ -96510,11 +97140,11 @@
97140 /* The evalConstExpr() function will have already converted any TK_VARIABLE
97141 ** expression involved in an comparison into a TK_REGISTER. */
97142 assert( pExpr->op!=TK_VARIABLE );
97143 if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
97144 int iVar = pExpr->iColumn;
97145 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
97146 *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
97147 return SQLITE_OK;
97148 }
97149 return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
97150 }
@@ -96707,27 +97337,18 @@
97337 Index *pFirst; /* Any other index on the table */
97338 memset(&sPk, 0, sizeof(Index));
97339 sPk.nColumn = 1;
97340 sPk.aiColumn = &aiColumnPk;
97341 sPk.aiRowEst = aiRowEstPk;
 
97342 sPk.onError = OE_Replace;
97343 sPk.pTable = pSrc->pTab;
97344 aiRowEstPk[0] = pSrc->pTab->nRowEst;
97345 aiRowEstPk[1] = 1;
97346 pFirst = pSrc->pTab->pIndex;
97347 if( pSrc->notIndexed==0 ){
97348 sPk.pNext = pFirst;
97349 }
 
 
 
 
 
 
 
 
 
 
97350 pProbe = &sPk;
97351 wsFlagMask = ~(
97352 WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
97353 );
97354 eqTermMask = WO_EQ|WO_IN;
@@ -98297,11 +98918,11 @@
98918 ** CREATE TABLE t2(c, d);
98919 ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
98920 **
98921 ** The best strategy is to iterate through table t1 first. However it
98922 ** is not possible to determine this with a simple greedy algorithm.
98923 ** Since the cost of a linear scan through table t2 is the same
98924 ** as the cost of a linear scan through table t1, a simple greedy
98925 ** algorithm may choose to use t2 for the outer loop, which is a much
98926 ** costlier approach.
98927 */
98928 nUnconstrained = 0;
@@ -103366,19 +103987,37 @@
103987
103988 /************** End of sqliteicu.h *******************************************/
103989 /************** Continuing where we left off in main.c ***********************/
103990 #endif
103991
 
 
 
103992 #ifndef SQLITE_AMALGAMATION
103993 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
103994 ** contains the text of SQLITE_VERSION macro.
103995 */
103996 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
103997 #endif
103998
103999 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
104000 ** a pointer to the to the sqlite3_version[] string constant.
104001 */
104002 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
104003
104004 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
104005 ** pointer to a string constant whose value is the same as the
104006 ** SQLITE_SOURCE_ID C preprocessor macro.
104007 */
104008 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
104009
104010 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
104011 ** returns an integer equal to SQLITE_VERSION_NUMBER.
104012 */
104013 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
104014
104015 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
104016 ** zero if and only if SQLite was compiled mutexing code omitted due to
104017 ** the SQLITE_THREADSAFE compile-time option being set to 0.
104018 */
104019 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
104020
104021 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
104022 /*
104023 ** If the following function pointer is not NULL and if
@@ -103495,10 +104134,17 @@
104134 /* Do the rest of the initialization under the recursive mutex so
104135 ** that we will be able to handle recursive calls into
104136 ** sqlite3_initialize(). The recursive calls normally come through
104137 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
104138 ** recursive calls might also be possible.
104139 **
104140 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
104141 ** to the xInit method, so the xInit method need not be threadsafe.
104142 **
104143 ** The following mutex is what serializes access to the appdef pcache xInit
104144 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
104145 ** call to sqlite3PcacheInitialize().
104146 */
104147 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
104148 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
104149 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
104150 sqlite3GlobalConfig.inProgress = 1;
@@ -103775,16 +104421,16 @@
104421 if( cnt<0 ) cnt = 0;
104422 if( sz==0 || cnt==0 ){
104423 sz = 0;
104424 pStart = 0;
104425 }else if( pBuf==0 ){
104426 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
104427 sqlite3BeginBenignMalloc();
104428 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
104429 sqlite3EndBenignMalloc();
104430 }else{
104431 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
104432 pStart = pBuf;
104433 }
104434 db->lookaside.pStart = pStart;
104435 db->lookaside.pFree = 0;
104436 db->lookaside.sz = (u16)sz;
@@ -103823,18 +104469,18 @@
104469 va_list ap;
104470 int rc;
104471 va_start(ap, op);
104472 switch( op ){
104473 case SQLITE_DBCONFIG_LOOKASIDE: {
104474 void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
104475 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
104476 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
104477 rc = setupLookaside(db, pBuf, sz, cnt);
104478 break;
104479 }
104480 default: {
104481 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
104482 break;
104483 }
104484 }
104485 va_end(ap);
104486 return rc;
@@ -103934,16 +104580,33 @@
104580 }
104581 db->nSavepoint = 0;
104582 db->nStatement = 0;
104583 db->isTransactionSavepoint = 0;
104584 }
104585
104586 /*
104587 ** Invoke the destructor function associated with FuncDef p, if any. Except,
104588 ** if this is not the last copy of the function, do not invoke it. Multiple
104589 ** copies of a single function are created when create_function() is called
104590 ** with SQLITE_ANY as the encoding.
104591 */
104592 static void functionDestroy(sqlite3 *db, FuncDef *p){
104593 FuncDestructor *pDestructor = p->pDestructor;
104594 if( pDestructor ){
104595 pDestructor->nRef--;
104596 if( pDestructor->nRef==0 ){
104597 pDestructor->xDestroy(pDestructor->pUserData);
104598 sqlite3DbFree(db, pDestructor);
104599 }
104600 }
104601 }
104602
104603 /*
104604 ** Close an existing SQLite database
104605 */
104606 SQLITE_API int sqlite3_close(sqlite3 *db){
104607 HashElem *i; /* Hash table iterator */
104608 int j;
104609
104610 if( !db ){
104611 return SQLITE_OK;
104612 }
@@ -104007,10 +104670,11 @@
104670 for(j=0; j<ArraySize(db->aFunc.a); j++){
104671 FuncDef *pNext, *pHash, *p;
104672 for(p=db->aFunc.a[j]; p; p=pHash){
104673 pHash = p->pHash;
104674 while( p ){
104675 functionDestroy(db, p);
104676 pNext = p->pNext;
104677 sqlite3DbFree(db, p);
104678 p = pNext;
104679 }
104680 }
@@ -104281,11 +104945,12 @@
104945 int nArg,
104946 int enc,
104947 void *pUserData,
104948 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
104949 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
104950 void (*xFinal)(sqlite3_context*),
104951 FuncDestructor *pDestructor
104952 ){
104953 FuncDef *p;
104954 int nName;
104955
104956 assert( sqlite3_mutex_held(db->mutex) );
@@ -104309,14 +104974,14 @@
104974 if( enc==SQLITE_UTF16 ){
104975 enc = SQLITE_UTF16NATIVE;
104976 }else if( enc==SQLITE_ANY ){
104977 int rc;
104978 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
104979 pUserData, xFunc, xStep, xFinal, pDestructor);
104980 if( rc==SQLITE_OK ){
104981 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
104982 pUserData, xFunc, xStep, xFinal, pDestructor);
104983 }
104984 if( rc!=SQLITE_OK ){
104985 return rc;
104986 }
104987 enc = SQLITE_UTF16BE;
@@ -104345,10 +105010,19 @@
105010 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
105011 assert(p || db->mallocFailed);
105012 if( !p ){
105013 return SQLITE_NOMEM;
105014 }
105015
105016 /* If an older version of the function with a configured destructor is
105017 ** being replaced invoke the destructor function here. */
105018 functionDestroy(db, p);
105019
105020 if( pDestructor ){
105021 pDestructor->nRef++;
105022 }
105023 p->pDestructor = pDestructor;
105024 p->flags = 0;
105025 p->xFunc = xFunc;
105026 p->xStep = xStep;
105027 p->xFinalize = xFinal;
105028 p->pUserData = pUserData;
@@ -104359,21 +105033,53 @@
105033 /*
105034 ** Create new user functions.
105035 */
105036 SQLITE_API int sqlite3_create_function(
105037 sqlite3 *db,
105038 const char *zFunc,
105039 int nArg,
105040 int enc,
105041 void *p,
105042 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105043 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105044 void (*xFinal)(sqlite3_context*)
105045 ){
105046 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
105047 xFinal, 0);
105048 }
105049
105050 SQLITE_API int sqlite3_create_function_v2(
105051 sqlite3 *db,
105052 const char *zFunc,
105053 int nArg,
105054 int enc,
105055 void *p,
105056 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105057 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105058 void (*xFinal)(sqlite3_context*),
105059 void (*xDestroy)(void *)
105060 ){
105061 int rc = SQLITE_ERROR;
105062 FuncDestructor *pArg = 0;
105063 sqlite3_mutex_enter(db->mutex);
105064 if( xDestroy ){
105065 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
105066 if( !pArg ){
105067 xDestroy(p);
105068 goto out;
105069 }
105070 pArg->xDestroy = xDestroy;
105071 pArg->pUserData = p;
105072 }
105073 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
105074 if( pArg && pArg->nRef==0 ){
105075 assert( rc!=SQLITE_OK );
105076 xDestroy(p);
105077 sqlite3DbFree(db, pArg);
105078 }
105079
105080 out:
105081 rc = sqlite3ApiExit(db, rc);
105082 sqlite3_mutex_leave(db->mutex);
105083 return rc;
105084 }
105085
@@ -104391,11 +105097,11 @@
105097 int rc;
105098 char *zFunc8;
105099 sqlite3_mutex_enter(db->mutex);
105100 assert( !db->mallocFailed );
105101 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
105102 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
105103 sqlite3DbFree(db, zFunc8);
105104 rc = sqlite3ApiExit(db, rc);
105105 sqlite3_mutex_leave(db->mutex);
105106 return rc;
105107 }
@@ -104422,11 +105128,11 @@
105128 int nName = sqlite3Strlen30(zName);
105129 int rc;
105130 sqlite3_mutex_enter(db->mutex);
105131 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
105132 sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
105133 0, sqlite3InvalidFunction, 0, 0, 0);
105134 }
105135 rc = sqlite3ApiExit(db, SQLITE_OK);
105136 sqlite3_mutex_leave(db->mutex);
105137 return rc;
105138 }
@@ -104560,11 +105266,14 @@
105266 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
105267 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
105268 ** configured by this function.
105269 */
105270 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
105271 #ifdef SQLITE_OMIT_WAL
105272 UNUSED_PARAMETER(db);
105273 UNUSED_PARAMETER(nFrame);
105274 #else
105275 if( nFrame>0 ){
105276 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
105277 }else{
105278 sqlite3_wal_hook(db, 0, 0);
105279 }
@@ -104690,64 +105399,10 @@
105399 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
105400 return 0;
105401 #endif
105402 }
105403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105404 /*
105405 ** Return UTF-8 encoded English language explanation of the most recent
105406 ** error.
105407 */
105408 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
@@ -104986,21 +105641,43 @@
105641 ** It merely prevents new constructs that exceed the limit
105642 ** from forming.
105643 */
105644 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
105645 int oldLimit;
105646
105647
105648 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
105649 ** there is a hard upper bound set at compile-time by a C preprocessor
105650 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
105651 ** "_MAX_".)
105652 */
105653 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
105654 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
105655 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
105656 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
105657 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
105658 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
105659 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
105660 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
105661 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
105662 SQLITE_MAX_LIKE_PATTERN_LENGTH );
105663 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
105664 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
105665 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
105666
105667
105668 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
105669 return -1;
105670 }
105671 oldLimit = db->aLimit[limitId];
105672 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
105673 if( newLimit>aHardLimit[limitId] ){
105674 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
105675 }
105676 db->aLimit[limitId] = newLimit;
105677 }
105678 return oldLimit; /* IMP: R-53341-35419 */
105679 }
105680
105681 /*
105682 ** This routine does the work of opening a database on behalf of
105683 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
@@ -105019,10 +105696,28 @@
105696 *ppDb = 0;
105697 #ifndef SQLITE_OMIT_AUTOINIT
105698 rc = sqlite3_initialize();
105699 if( rc ) return rc;
105700 #endif
105701
105702 /* Only allow sensible combinations of bits in the flags argument.
105703 ** Throw an error if any non-sense combination is used. If we
105704 ** do not block illegal combinations here, it could trigger
105705 ** assert() statements in deeper layers. Sensible combinations
105706 ** are:
105707 **
105708 ** 1: SQLITE_OPEN_READONLY
105709 ** 2: SQLITE_OPEN_READWRITE
105710 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
105711 */
105712 assert( SQLITE_OPEN_READONLY == 0x01 );
105713 assert( SQLITE_OPEN_READWRITE == 0x02 );
105714 assert( SQLITE_OPEN_CREATE == 0x04 );
105715 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
105716 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
105717 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
105718 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
105719
105720 if( sqlite3GlobalConfig.bCoreMutex==0 ){
105721 isThreadsafe = 0;
105722 }else if( flags & SQLITE_OPEN_NOMUTEX ){
105723 isThreadsafe = 0;
@@ -105053,11 +105748,12 @@
105748 SQLITE_OPEN_MAIN_JOURNAL |
105749 SQLITE_OPEN_TEMP_JOURNAL |
105750 SQLITE_OPEN_SUBJOURNAL |
105751 SQLITE_OPEN_MASTER_JOURNAL |
105752 SQLITE_OPEN_NOMUTEX |
105753 SQLITE_OPEN_FULLMUTEX |
105754 SQLITE_OPEN_WAL
105755 );
105756
105757 /* Allocate the sqlite data structure */
105758 db = sqlite3MallocZero( sizeof(sqlite3) );
105759 if( db==0 ) goto opendb_out;
@@ -105125,13 +105821,12 @@
105821 createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
105822 nocaseCollatingFunc, 0);
105823
105824 /* Open the backend database driver */
105825 db->openFlags = flags;
105826 rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
105827 flags | SQLITE_OPEN_MAIN_DB);
 
105828 if( rc!=SQLITE_OK ){
105829 if( rc==SQLITE_IOERR_NOMEM ){
105830 rc = SQLITE_NOMEM;
105831 }
105832 sqlite3Error(db, rc, 0);
@@ -105833,10 +106528,26 @@
106528 */
106529 case SQLITE_TESTCTRL_PGHDRSZ: {
106530 rc = sizeof(PgHdr);
106531 break;
106532 }
106533
106534 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
106535 **
106536 ** Pass pFree into sqlite3ScratchFree().
106537 ** If sz>0 then allocate a scratch buffer into pNew.
106538 */
106539 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
106540 void *pFree, **ppNew;
106541 int sz;
106542 sz = va_arg(ap, int);
106543 ppNew = va_arg(ap, void**);
106544 pFree = va_arg(ap, void*);
106545 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
106546 sqlite3ScratchFree(pFree);
106547 break;
106548 }
106549
106550 }
106551 va_end(ap);
106552 #endif /* SQLITE_OMIT_BUILTIN_TEST */
106553 return rc;
@@ -107022,10 +107733,11 @@
107733 );
107734 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
107735 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
107736 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
107737 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
107738 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
107739
107740 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
107741 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
107742 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
107743 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
@@ -108971,10 +109683,13 @@
109683 zQuery);
109684 }
109685 return rc;
109686 }
109687
109688 rc = sqlite3Fts3ReadLock(p);
109689 if( rc!=SQLITE_OK ) return rc;
109690
109691 rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
109692 pCsr->pNextId = pCsr->aDoclist;
109693 pCsr->iPrevId = 0;
109694 }
109695
@@ -109349,15 +110064,18 @@
110064 static int fts3RenameMethod(
110065 sqlite3_vtab *pVtab, /* Virtual table handle */
110066 const char *zName /* New name of table */
110067 ){
110068 Fts3Table *p = (Fts3Table *)pVtab;
110069 sqlite3 *db = p->db; /* Database connection */
110070 int rc; /* Return Code */
110071
110072 rc = sqlite3Fts3PendingTermsFlush(p);
110073 if( rc!=SQLITE_OK ){
110074 return rc;
110075 }
110076
110077 fts3DbExec(&rc, db,
110078 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
110079 p->zDb, p->zName, zName
110080 );
110081 if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
@@ -112512,10 +113230,40 @@
113230 return SQLITE_CORRUPT;
113231 }
113232 }
113233 return SQLITE_OK;
113234 }
113235
113236 /*
113237 ** This function ensures that the caller has obtained a shared-cache
113238 ** table-lock on the %_content table. This is required before reading
113239 ** data from the fts3 table. If this lock is not acquired first, then
113240 ** the caller may end up holding read-locks on the %_segments and %_segdir
113241 ** tables, but no read-lock on the %_content table. If this happens
113242 ** a second connection will be able to write to the fts3 table, but
113243 ** attempting to commit those writes might return SQLITE_LOCKED or
113244 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
113245 ** write-locks on the %_segments and %_segdir ** tables).
113246 **
113247 ** We try to avoid this because if FTS3 returns any error when committing
113248 ** a transaction, the whole transaction will be rolled back. And this is
113249 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
113250 ** still happen if the user reads data directly from the %_segments or
113251 ** %_segdir tables instead of going through FTS3 though.
113252 */
113253 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
113254 int rc; /* Return code */
113255 sqlite3_stmt *pStmt; /* Statement used to obtain lock */
113256
113257 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
113258 if( rc==SQLITE_OK ){
113259 sqlite3_bind_null(pStmt, 1);
113260 sqlite3_step(pStmt);
113261 rc = sqlite3_reset(pStmt);
113262 }
113263 return rc;
113264 }
113265
113266 /*
113267 ** Set *ppStmt to a statement handle that may be used to iterate through
113268 ** all rows in the %_segdir table, from oldest to newest. If successful,
113269 ** return SQLITE_OK. If an error occurs while preparing the statement,
@@ -116003,10 +116751,49 @@
116751 **
116752 *************************************************************************
116753 ** This file contains code for implementations of the r-tree and r*-tree
116754 ** algorithms packaged as an SQLite virtual table module.
116755 */
116756
116757 /*
116758 ** Database Format of R-Tree Tables
116759 ** --------------------------------
116760 **
116761 ** The data structure for a single virtual r-tree table is stored in three
116762 ** native SQLite tables declared as follows. In each case, the '%' character
116763 ** in the table name is replaced with the user-supplied name of the r-tree
116764 ** table.
116765 **
116766 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
116767 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
116768 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
116769 **
116770 ** The data for each node of the r-tree structure is stored in the %_node
116771 ** table. For each node that is not the root node of the r-tree, there is
116772 ** an entry in the %_parent table associating the node with its parent.
116773 ** And for each row of data in the table, there is an entry in the %_rowid
116774 ** table that maps from the entries rowid to the id of the node that it
116775 ** is stored on.
116776 **
116777 ** The root node of an r-tree always exists, even if the r-tree table is
116778 ** empty. The nodeno of the root node is always 1. All other nodes in the
116779 ** table must be the same size as the root node. The content of each node
116780 ** is formatted as follows:
116781 **
116782 ** 1. If the node is the root node (node 1), then the first 2 bytes
116783 ** of the node contain the tree depth as a big-endian integer.
116784 ** For non-root nodes, the first 2 bytes are left unused.
116785 **
116786 ** 2. The next 2 bytes contain the number of entries currently
116787 ** stored in the node.
116788 **
116789 ** 3. The remainder of the node contains the node entries. Each entry
116790 ** consists of a single 8-byte integer followed by an even number
116791 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
116792 ** of a record. For internal nodes it is the node number of a
116793 ** child page.
116794 */
116795
116796 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
116797
116798 /*
116799 ** This file contains an implementation of a couple of different variants
@@ -116044,18 +116831,22 @@
116831 #endif
116832 #if VARIANT_RSTARTREE_SPLIT
116833 #define AssignCells splitNodeStartree
116834 #endif
116835
116836 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116837 # define NDEBUG 1
116838 #endif
116839
116840 #ifndef SQLITE_CORE
116841 SQLITE_EXTENSION_INIT1
116842 #else
116843 #endif
116844
116845
116846 #ifndef SQLITE_AMALGAMATION
116847 #include "sqlite3rtree.h"
116848 typedef sqlite3_int64 i64;
116849 typedef unsigned char u8;
116850 typedef unsigned int u32;
116851 #endif
116852
@@ -116062,10 +116853,12 @@
116853 typedef struct Rtree Rtree;
116854 typedef struct RtreeCursor RtreeCursor;
116855 typedef struct RtreeNode RtreeNode;
116856 typedef struct RtreeCell RtreeCell;
116857 typedef struct RtreeConstraint RtreeConstraint;
116858 typedef struct RtreeMatchArg RtreeMatchArg;
116859 typedef struct RtreeGeomCallback RtreeGeomCallback;
116860 typedef union RtreeCoord RtreeCoord;
116861
116862 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
116863 #define RTREE_MAX_DIMENSIONS 5
116864
@@ -116131,10 +116924,19 @@
116924 */
116925 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
116926 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
116927 #define RTREE_MAXCELLS 51
116928
116929 /*
116930 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
116931 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
116932 ** Therefore all non-root nodes must contain at least 3 entries. Since
116933 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
116934 ** 40 or less.
116935 */
116936 #define RTREE_MAX_DEPTH 40
116937
116938 /*
116939 ** An rtree cursor object.
116940 */
116941 struct RtreeCursor {
116942 sqlite3_vtab_cursor base;
@@ -116163,39 +116965,27 @@
116965
116966 /*
116967 ** A search constraint.
116968 */
116969 struct RtreeConstraint {
116970 int iCoord; /* Index of constrained coordinate */
116971 int op; /* Constraining operation */
116972 double rValue; /* Constraint value. */
116973 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
116974 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
116975 };
116976
116977 /* Possible values for RtreeConstraint.op */
116978 #define RTREE_EQ 0x41
116979 #define RTREE_LE 0x42
116980 #define RTREE_LT 0x43
116981 #define RTREE_GE 0x44
116982 #define RTREE_GT 0x45
116983 #define RTREE_MATCH 0x46
116984
116985 /*
116986 ** An rtree structure node.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116987 */
116988 struct RtreeNode {
116989 RtreeNode *pParent; /* Parent node */
116990 i64 iNode;
116991 int nRef;
@@ -116211,10 +117001,44 @@
117001 struct RtreeCell {
117002 i64 iRowid;
117003 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
117004 };
117005
117006
117007 /*
117008 ** Value for the first field of every RtreeMatchArg object. The MATCH
117009 ** operator tests that the first field of a blob operand matches this
117010 ** value to avoid operating on invalid blobs (which could cause a segfault).
117011 */
117012 #define RTREE_GEOMETRY_MAGIC 0x891245AB
117013
117014 /*
117015 ** An instance of this structure must be supplied as a blob argument to
117016 ** the right-hand-side of an SQL MATCH operator used to constrain an
117017 ** r-tree query.
117018 */
117019 struct RtreeMatchArg {
117020 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
117021 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
117022 void *pContext;
117023 int nParam;
117024 double aParam[1];
117025 };
117026
117027 /*
117028 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
117029 ** a single instance of the following structure is allocated. It is used
117030 ** as the context for the user-function created by by s_r_g_c(). The object
117031 ** is eventually deleted by the destructor mechanism provided by
117032 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
117033 ** the geometry callback function).
117034 */
117035 struct RtreeGeomCallback {
117036 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
117037 void *pContext;
117038 };
117039
117040 #ifndef MAX
117041 # define MAX(x,y) ((x) < (y) ? (y) : (x))
117042 #endif
117043 #ifndef MIN
117044 # define MIN(x,y) ((x) > (y) ? (y) : (x))
@@ -116293,14 +117117,12 @@
117117
117118 /*
117119 ** Clear the content of node p (set all bytes to 0x00).
117120 */
117121 static void nodeZero(Rtree *pRtree, RtreeNode *p){
117122 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
117123 p->isDirty = 1;
 
 
117124 }
117125
117126 /*
117127 ** Given a node number iNode, return the corresponding key to use
117128 ** in the Rtree.aHash table.
@@ -116316,26 +117138,23 @@
117138 ** Search the node hash table for node iNode. If found, return a pointer
117139 ** to it. Otherwise, return 0.
117140 */
117141 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
117142 RtreeNode *p;
 
117143 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
117144 return p;
117145 }
117146
117147 /*
117148 ** Add node pNode to the node hash table.
117149 */
117150 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
117151 int iHash;
117152 assert( pNode->pNext==0 );
117153 iHash = nodeHash(pNode->iNode);
117154 pNode->pNext = pRtree->aHash[iHash];
117155 pRtree->aHash[iHash] = pNode;
 
 
117156 }
117157
117158 /*
117159 ** Remove node pNode from the node hash table.
117160 */
@@ -116353,15 +117172,15 @@
117172 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
117173 ** indicating that node has not yet been assigned a node number. It is
117174 ** assigned a node number when nodeWrite() is called to write the
117175 ** node contents out to the database.
117176 */
117177 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
117178 RtreeNode *pNode;
117179 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
117180 if( pNode ){
117181 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
117182 pNode->zData = (u8 *)&pNode[1];
117183 pNode->nRef = 1;
117184 pNode->pParent = pParent;
117185 pNode->isDirty = 1;
117186 nodeReference(pParent);
@@ -116378,10 +117197,11 @@
117197 i64 iNode, /* Node number to load */
117198 RtreeNode *pParent, /* Either the parent node or NULL */
117199 RtreeNode **ppNode /* OUT: Acquired node */
117200 ){
117201 int rc;
117202 int rc2 = SQLITE_OK;
117203 RtreeNode *pNode;
117204
117205 /* Check if the requested node is already in the hash table. If so,
117206 ** increase its reference count and return it.
117207 */
@@ -116394,43 +117214,67 @@
117214 pNode->nRef++;
117215 *ppNode = pNode;
117216 return SQLITE_OK;
117217 }
117218
 
 
 
 
 
 
 
 
 
 
 
 
117219 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
117220 rc = sqlite3_step(pRtree->pReadNode);
117221 if( rc==SQLITE_ROW ){
117222 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
117223 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
117224 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
117225 if( !pNode ){
117226 rc2 = SQLITE_NOMEM;
117227 }else{
117228 pNode->pParent = pParent;
117229 pNode->zData = (u8 *)&pNode[1];
117230 pNode->nRef = 1;
117231 pNode->iNode = iNode;
117232 pNode->isDirty = 0;
117233 pNode->pNext = 0;
117234 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
117235 nodeReference(pParent);
117236 }
117237 }
117238 }
117239 rc = sqlite3_reset(pRtree->pReadNode);
117240 if( rc==SQLITE_OK ) rc = rc2;
117241
117242 /* If the root node was just loaded, set pRtree->iDepth to the height
117243 ** of the r-tree structure. A height of zero means all data is stored on
117244 ** the root node. A height of one means the children of the root node
117245 ** are the leaves, and so on. If the depth as specified on the root node
117246 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
117247 */
117248 if( pNode && iNode==1 ){
117249 pRtree->iDepth = readInt16(pNode->zData);
117250 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
117251 rc = SQLITE_CORRUPT;
117252 }
117253 }
117254
117255 /* If no error has occurred so far, check if the "number of entries"
117256 ** field on the node is too large. If so, set the return code to
117257 ** SQLITE_CORRUPT.
117258 */
117259 if( pNode && rc==SQLITE_OK ){
117260 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
117261 rc = SQLITE_CORRUPT;
117262 }
117263 }
117264
117265 if( rc==SQLITE_OK ){
117266 if( pNode!=0 ){
117267 nodeHashInsert(pRtree, pNode);
117268 }else{
117269 rc = SQLITE_CORRUPT;
117270 }
117271 *ppNode = pNode;
117272 }else{
117273 sqlite3_free(pNode);
117274 *ppNode = 0;
117275 }
 
 
 
 
 
 
 
 
 
 
117276
117277 return rc;
117278 }
117279
117280 /*
@@ -116479,12 +117323,11 @@
117323 int nMaxCell; /* Maximum number of cells for pNode */
117324
117325 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
117326 nCell = NCELL(pNode);
117327
117328 assert( nCell<=nMaxCell );
 
117329 if( nCell<nMaxCell ){
117330 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
117331 writeInt16(&pNode->zData[2], nCell+1);
117332 pNode->isDirty = 1;
117333 }
@@ -116700,18 +117543,37 @@
117543 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
117544
117545 return rc;
117546 }
117547
117548
117549 /*
117550 ** Free the RtreeCursor.aConstraint[] array and its contents.
117551 */
117552 static void freeCursorConstraints(RtreeCursor *pCsr){
117553 if( pCsr->aConstraint ){
117554 int i; /* Used to iterate through constraint array */
117555 for(i=0; i<pCsr->nConstraint; i++){
117556 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
117557 if( pGeom ){
117558 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
117559 sqlite3_free(pGeom);
117560 }
117561 }
117562 sqlite3_free(pCsr->aConstraint);
117563 pCsr->aConstraint = 0;
117564 }
117565 }
117566
117567 /*
117568 ** Rtree virtual table module xClose method.
117569 */
117570 static int rtreeClose(sqlite3_vtab_cursor *cur){
117571 Rtree *pRtree = (Rtree *)(cur->pVtab);
117572 int rc;
117573 RtreeCursor *pCsr = (RtreeCursor *)cur;
117574 freeCursorConstraints(pCsr);
117575 rc = nodeRelease(pRtree, pCsr->pNode);
117576 sqlite3_free(pCsr);
117577 return rc;
117578 }
117579
@@ -116723,18 +117585,44 @@
117585 */
117586 static int rtreeEof(sqlite3_vtab_cursor *cur){
117587 RtreeCursor *pCsr = (RtreeCursor *)cur;
117588 return (pCsr->pNode==0);
117589 }
117590
117591 /*
117592 ** The r-tree constraint passed as the second argument to this function is
117593 ** guaranteed to be a MATCH constraint.
117594 */
117595 static int testRtreeGeom(
117596 Rtree *pRtree, /* R-Tree object */
117597 RtreeConstraint *pConstraint, /* MATCH constraint to test */
117598 RtreeCell *pCell, /* Cell to test */
117599 int *pbRes /* OUT: Test result */
117600 ){
117601 int i;
117602 double aCoord[RTREE_MAX_DIMENSIONS*2];
117603 int nCoord = pRtree->nDim*2;
117604
117605 assert( pConstraint->op==RTREE_MATCH );
117606 assert( pConstraint->pGeom );
117607
117608 for(i=0; i<nCoord; i++){
117609 aCoord[i] = DCOORD(pCell->aCoord[i]);
117610 }
117611 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
117612 }
117613
117614 /*
117615 ** Cursor pCursor currently points to a cell in a non-leaf page.
117616 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
117617 ** (excluded) by the constraints in the pCursor->aConstraint[]
117618 ** array, or false otherwise.
117619 **
117620 ** Return SQLITE_OK if successful or an SQLite error code if an error
117621 ** occurs within a geometry callback.
117622 */
117623 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
117624 RtreeCell cell;
117625 int ii;
117626 int bRes = 0;
117627
117628 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
@@ -116742,56 +117630,92 @@
117630 RtreeConstraint *p = &pCursor->aConstraint[ii];
117631 double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
117632 double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
117633
117634 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
117635 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
117636 );
117637
117638 switch( p->op ){
117639 case RTREE_LE: case RTREE_LT:
117640 bRes = p->rValue<cell_min;
117641 break;
117642
117643 case RTREE_GE: case RTREE_GT:
117644 bRes = p->rValue>cell_max;
117645 break;
117646
117647 case RTREE_EQ:
117648 bRes = (p->rValue>cell_max || p->rValue<cell_min);
117649 break;
117650
117651 default: {
117652 int rc;
117653 assert( p->op==RTREE_MATCH );
117654 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
117655 if( rc!=SQLITE_OK ){
117656 return rc;
117657 }
117658 bRes = !bRes;
117659 break;
117660 }
117661 }
117662 }
117663
117664 *pbEof = bRes;
117665 return SQLITE_OK;
117666 }
117667
117668 /*
117669 ** Test if the cell that cursor pCursor currently points to
117670 ** would be filtered (excluded) by the constraints in the
117671 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
117672 ** returning. If the cell is not filtered (excluded) by the constraints,
117673 ** set pbEof to zero.
117674 **
117675 ** Return SQLITE_OK if successful or an SQLite error code if an error
117676 ** occurs within a geometry callback.
117677 **
117678 ** This function assumes that the cell is part of a leaf node.
117679 */
117680 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
117681 RtreeCell cell;
117682 int ii;
117683 *pbEof = 0;
117684
117685 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
117686 for(ii=0; ii<pCursor->nConstraint; ii++){
117687 RtreeConstraint *p = &pCursor->aConstraint[ii];
117688 double coord = DCOORD(cell.aCoord[p->iCoord]);
117689 int res;
117690 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
117691 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
117692 );
117693 switch( p->op ){
117694 case RTREE_LE: res = (coord<=p->rValue); break;
117695 case RTREE_LT: res = (coord<p->rValue); break;
117696 case RTREE_GE: res = (coord>=p->rValue); break;
117697 case RTREE_GT: res = (coord>p->rValue); break;
117698 case RTREE_EQ: res = (coord==p->rValue); break;
117699 default: {
117700 int rc;
117701 assert( p->op==RTREE_MATCH );
117702 rc = testRtreeGeom(pRtree, p, &cell, &res);
117703 if( rc!=SQLITE_OK ){
117704 return rc;
117705 }
117706 break;
117707 }
117708 }
117709
117710 if( !res ){
117711 *pbEof = 1;
117712 return SQLITE_OK;
117713 }
117714 }
117715
117716 return SQLITE_OK;
117717 }
117718
117719 /*
117720 ** Cursor pCursor currently points at a node that heads a sub-tree of
117721 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
@@ -116814,17 +117738,17 @@
117738 int iSavedCell = pCursor->iCell;
117739
117740 assert( iHeight>=0 );
117741
117742 if( iHeight==0 ){
117743 rc = testRtreeEntry(pRtree, pCursor, &isEof);
117744 }else{
117745 rc = testRtreeCell(pRtree, pCursor, &isEof);
117746 }
117747 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
117748 *pEof = isEof;
117749 return rc;
117750 }
117751
117752 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
117753 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
117754 if( rc!=SQLITE_OK ){
@@ -116856,45 +117780,59 @@
117780
117781 /*
117782 ** One of the cells in node pNode is guaranteed to have a 64-bit
117783 ** integer value equal to iRowid. Return the index of this cell.
117784 */
117785 static int nodeRowidIndex(
117786 Rtree *pRtree,
117787 RtreeNode *pNode,
117788 i64 iRowid,
117789 int *piIndex
117790 ){
117791 int ii;
117792 int nCell = NCELL(pNode);
117793 for(ii=0; ii<nCell; ii++){
117794 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
117795 *piIndex = ii;
117796 return SQLITE_OK;
117797 }
117798 }
117799 return SQLITE_CORRUPT;
117800 }
117801
117802 /*
117803 ** Return the index of the cell containing a pointer to node pNode
117804 ** in its parent. If pNode is the root node, return -1.
117805 */
117806 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
117807 RtreeNode *pParent = pNode->pParent;
117808 if( pParent ){
117809 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
117810 }
117811 *piIndex = -1;
117812 return SQLITE_OK;
117813 }
117814
117815 /*
117816 ** Rtree virtual table module xNext method.
117817 */
117818 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
117819 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
117820 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
117821 int rc = SQLITE_OK;
117822
117823 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
117824 ** already at EOF. It is against the rules to call the xNext() method of
117825 ** a cursor that has already reached EOF.
117826 */
117827 assert( pCsr->pNode );
117828
117829 if( pCsr->iStrategy==1 ){
117830 /* This "scan" is a direct lookup by rowid. There is no next entry. */
117831 nodeRelease(pRtree, pCsr->pNode);
117832 pCsr->pNode = 0;
117833 }else{
 
 
117834 /* Move to the next entry that matches the configured constraints. */
117835 int iHeight = 0;
117836 while( pCsr->pNode ){
117837 RtreeNode *pNode = pCsr->pNode;
117838 int nCell = NCELL(pNode);
@@ -116904,11 +117842,14 @@
117842 if( rc!=SQLITE_OK || !isEof ){
117843 return rc;
117844 }
117845 }
117846 pCsr->pNode = pNode->pParent;
117847 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
117848 if( rc!=SQLITE_OK ){
117849 return rc;
117850 }
117851 nodeReference(pCsr->pNode);
117852 nodeRelease(pRtree, pNode);
117853 iHeight++;
117854 }
117855 }
@@ -116972,10 +117913,55 @@
117913 rc = sqlite3_reset(pRtree->pReadRowid);
117914 }
117915 return rc;
117916 }
117917
117918 /*
117919 ** This function is called to configure the RtreeConstraint object passed
117920 ** as the second argument for a MATCH constraint. The value passed as the
117921 ** first argument to this function is the right-hand operand to the MATCH
117922 ** operator.
117923 */
117924 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
117925 RtreeMatchArg *p;
117926 sqlite3_rtree_geometry *pGeom;
117927 int nBlob;
117928
117929 /* Check that value is actually a blob. */
117930 if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
117931
117932 /* Check that the blob is roughly the right size. */
117933 nBlob = sqlite3_value_bytes(pValue);
117934 if( nBlob<sizeof(RtreeMatchArg)
117935 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
117936 ){
117937 return SQLITE_ERROR;
117938 }
117939
117940 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
117941 sizeof(sqlite3_rtree_geometry) + nBlob
117942 );
117943 if( !pGeom ) return SQLITE_NOMEM;
117944 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
117945 p = (RtreeMatchArg *)&pGeom[1];
117946
117947 memcpy(p, sqlite3_value_blob(pValue), nBlob);
117948 if( p->magic!=RTREE_GEOMETRY_MAGIC
117949 || nBlob!=(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
117950 ){
117951 sqlite3_free(pGeom);
117952 return SQLITE_ERROR;
117953 }
117954
117955 pGeom->pContext = p->pContext;
117956 pGeom->nParam = p->nParam;
117957 pGeom->aParam = p->aParam;
117958
117959 pCons->xGeom = p->xGeom;
117960 pCons->pGeom = pGeom;
117961 return SQLITE_OK;
117962 }
117963
117964 /*
117965 ** Rtree virtual table module xFilter method.
117966 */
117967 static int rtreeFilter(
@@ -116990,22 +117976,22 @@
117976 int ii;
117977 int rc = SQLITE_OK;
117978
117979 rtreeReference(pRtree);
117980
117981 freeCursorConstraints(pCsr);
 
117982 pCsr->iStrategy = idxNum;
117983
117984 if( idxNum==1 ){
117985 /* Special case - lookup by rowid. */
117986 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
117987 i64 iRowid = sqlite3_value_int64(argv[0]);
117988 rc = findLeafNode(pRtree, iRowid, &pLeaf);
117989 pCsr->pNode = pLeaf;
117990 if( pLeaf ){
117991 assert( rc==SQLITE_OK );
117992 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
117993 }
117994 }else{
117995 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
117996 ** with the configured constraints.
117997 */
@@ -117013,16 +117999,28 @@
117999 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
118000 pCsr->nConstraint = argc;
118001 if( !pCsr->aConstraint ){
118002 rc = SQLITE_NOMEM;
118003 }else{
118004 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
118005 assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
118006 for(ii=0; ii<argc; ii++){
118007 RtreeConstraint *p = &pCsr->aConstraint[ii];
118008 p->op = idxStr[ii*2];
118009 p->iCoord = idxStr[ii*2+1]-'a';
118010 if( p->op==RTREE_MATCH ){
118011 /* A MATCH operator. The right-hand-side must be a blob that
118012 ** can be cast into an RtreeMatchArg object. One created using
118013 ** an sqlite3_rtree_geometry_callback() SQL user function.
118014 */
118015 rc = deserializeGeometry(argv[ii], p);
118016 if( rc!=SQLITE_OK ){
118017 break;
118018 }
118019 }else{
118020 p->rValue = sqlite3_value_double(argv[ii]);
118021 }
118022 }
118023 }
118024 }
118025
118026 if( rc==SQLITE_OK ){
@@ -117078,10 +118076,11 @@
118076 ** = 0x41 ('A')
118077 ** <= 0x42 ('B')
118078 ** < 0x43 ('C')
118079 ** >= 0x44 ('D')
118080 ** > 0x45 ('E')
118081 ** MATCH 0x46 ('F')
118082 ** ----------------------
118083 **
118084 ** The second of each pair of bytes identifies the coordinate column
118085 ** to which the constraint applies. The leftmost coordinate column
118086 ** is 'a', the second from the left 'b' etc.
@@ -117116,43 +118115,47 @@
118115 */
118116 pIdxInfo->estimatedCost = 10.0;
118117 return SQLITE_OK;
118118 }
118119
118120 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
118121 int j, opmsk;
118122 static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
118123 u8 op = 0;
118124 switch( p->op ){
118125 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
118126 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
118127 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
118128 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
118129 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
118130 default:
118131 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
118132 op = RTREE_MATCH;
118133 break;
118134 }
118135 assert( op!=0 );
118136
118137 /* Make sure this particular constraint has not been used before.
118138 ** If it has been used before, ignore it.
118139 **
118140 ** A <= or < can be used if there is a prior >= or >.
118141 ** A >= or > can be used if there is a prior < or <=.
118142 ** A <= or < is disqualified if there is a prior <=, <, or ==.
118143 ** A >= or > is disqualified if there is a prior >=, >, or ==.
118144 ** A == is disqualifed if there is any prior constraint.
118145 */
118146 assert( compatible[RTREE_EQ & 7]==0 );
118147 assert( compatible[RTREE_LT & 7]==1 );
118148 assert( compatible[RTREE_LE & 7]==1 );
118149 assert( compatible[RTREE_GT & 7]==2 );
118150 assert( compatible[RTREE_GE & 7]==2 );
118151 cCol = p->iColumn - 1 + 'a';
118152 opmsk = compatible[op & 7];
118153 for(j=0; j<iIdx; j+=2){
118154 if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
118155 op = 0;
118156 break;
118157 }
118158 }
118159 if( op ){
118160 assert( iIdx<sizeof(zIdxStr)-1 );
118161 zIdxStr[iIdx++] = op;
@@ -117256,11 +118259,16 @@
118259 int iExclude
118260 ){
118261 int ii;
118262 float overlap = 0.0;
118263 for(ii=0; ii<nCell; ii++){
118264 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118265 if( ii!=iExclude )
118266 #else
118267 assert( iExclude==-1 );
118268 #endif
118269 {
118270 int jj;
118271 float o = 1.0;
118272 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
118273 double x1;
118274 double x2;
@@ -117349,26 +118357,35 @@
118357 /* Select the child node which will be enlarged the least if pCell
118358 ** is inserted into it. Resolve ties by choosing the entry with
118359 ** the smallest area.
118360 */
118361 for(iCell=0; iCell<nCell; iCell++){
118362 int bBest = 0;
118363 float growth;
118364 float area;
118365 float overlap = 0.0;
118366 nodeGetCell(pRtree, pNode, iCell, &cell);
118367 growth = cellGrowth(pRtree, &cell, pCell);
118368 area = cellArea(pRtree, &cell);
118369
118370 #if VARIANT_RSTARTREE_CHOOSESUBTREE
118371 if( ii==(pRtree->iDepth-1) ){
118372 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
118373 }
 
118374 if( (iCell==0)
118375 || (overlap<fMinOverlap)
118376 || (overlap==fMinOverlap && growth<fMinGrowth)
118377 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
118378 ){
118379 bBest = 1;
118380 }
118381 #else
118382 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
118383 bBest = 1;
118384 }
118385 #endif
118386 if( bBest ){
118387 fMinOverlap = overlap;
118388 fMinGrowth = growth;
118389 fMinArea = area;
118390 iBest = cell.iRowid;
118391 }
@@ -117387,29 +118404,34 @@
118404 /*
118405 ** A cell with the same content as pCell has just been inserted into
118406 ** the node pNode. This function updates the bounding box cells in
118407 ** all ancestor elements.
118408 */
118409 static int AdjustTree(
118410 Rtree *pRtree, /* Rtree table */
118411 RtreeNode *pNode, /* Adjust ancestry of this node. */
118412 RtreeCell *pCell /* This cell was just inserted */
118413 ){
118414 RtreeNode *p = pNode;
118415 while( p->pParent ){
 
118416 RtreeNode *pParent = p->pParent;
118417 RtreeCell cell;
118418 int iCell;
118419
118420 if( nodeParentIndex(pRtree, p, &iCell) ){
118421 return SQLITE_CORRUPT;
118422 }
118423
118424 nodeGetCell(pRtree, pParent, iCell, &cell);
118425 if( !cellContains(pRtree, &cell, pCell) ){
118426 cellUnion(pRtree, &cell, pCell);
118427 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
118428 }
118429
118430 p = pParent;
118431 }
118432 return SQLITE_OK;
118433 }
118434
118435 /*
118436 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
118437 */
@@ -117934,18 +118956,18 @@
118956 nodeZero(pRtree, pNode);
118957 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
118958 nCell++;
118959
118960 if( pNode->iNode==1 ){
118961 pRight = nodeNew(pRtree, pNode);
118962 pLeft = nodeNew(pRtree, pNode);
118963 pRtree->iDepth++;
118964 pNode->isDirty = 1;
118965 writeInt16(pNode->zData, pRtree->iDepth);
118966 }else{
118967 pLeft = pNode;
118968 pRight = nodeNew(pRtree, pLeft->pParent);
118969 nodeReference(pLeft);
118970 }
118971
118972 if( !pLeft || !pRight ){
118973 rc = SQLITE_NOMEM;
@@ -117958,12 +118980,16 @@
118980 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
118981 if( rc!=SQLITE_OK ){
118982 goto splitnode_out;
118983 }
118984
118985 /* Ensure both child nodes have node numbers assigned to them by calling
118986 ** nodeWrite(). Node pRight always needs a node number, as it was created
118987 ** by nodeNew() above. But node pLeft sometimes already has a node number.
118988 ** In this case avoid the all to nodeWrite().
118989 */
118990 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
118991 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
118992 ){
118993 goto splitnode_out;
118994 }
118995
@@ -117975,13 +119001,19 @@
119001 if( rc!=SQLITE_OK ){
119002 goto splitnode_out;
119003 }
119004 }else{
119005 RtreeNode *pParent = pLeft->pParent;
119006 int iCell;
119007 rc = nodeParentIndex(pRtree, pLeft, &iCell);
119008 if( rc==SQLITE_OK ){
119009 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
119010 rc = AdjustTree(pRtree, pParent, &leftbbox);
119011 }
119012 if( rc!=SQLITE_OK ){
119013 goto splitnode_out;
119014 }
119015 }
119016 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
119017 goto splitnode_out;
119018 }
119019
@@ -118021,44 +119053,73 @@
119053 nodeRelease(pRtree, pLeft);
119054 sqlite3_free(aCell);
119055 return rc;
119056 }
119057
119058 /*
119059 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
119060 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
119061 ** the pLeaf->pParent chain all the way up to the root node.
119062 **
119063 ** This operation is required when a row is deleted (or updated - an update
119064 ** is implemented as a delete followed by an insert). SQLite provides the
119065 ** rowid of the row to delete, which can be used to find the leaf on which
119066 ** the entry resides (argument pLeaf). Once the leaf is located, this
119067 ** function is called to determine its ancestry.
119068 */
119069 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
119070 int rc = SQLITE_OK;
119071 RtreeNode *pChild = pLeaf;
119072 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
119073 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
119074 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
119075 rc = sqlite3_step(pRtree->pReadParent);
119076 if( rc==SQLITE_ROW ){
119077 RtreeNode *pTest; /* Used to test for reference loops */
119078 i64 iNode; /* Node number of parent node */
119079
119080 /* Before setting pChild->pParent, test that we are not creating a
119081 ** loop of references (as we would if, say, pChild==pParent). We don't
119082 ** want to do this as it leads to a memory leak when trying to delete
119083 ** the referenced counted node structures.
119084 */
119085 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
119086 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
119087 if( !pTest ){
119088 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
119089 }
119090 }
119091 rc = sqlite3_reset(pRtree->pReadParent);
119092 if( rc==SQLITE_OK ) rc = rc2;
119093 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
119094 pChild = pChild->pParent;
119095 }
119096 return rc;
119097 }
119098
119099 static int deleteCell(Rtree *, RtreeNode *, int, int);
119100
119101 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
119102 int rc;
119103 int rc2;
119104 RtreeNode *pParent;
119105 int iCell;
119106
119107 assert( pNode->nRef==1 );
119108
119109 /* Remove the entry in the parent cell. */
119110 rc = nodeParentIndex(pRtree, pNode, &iCell);
119111 if( rc==SQLITE_OK ){
119112 pParent = pNode->pParent;
119113 pNode->pParent = 0;
119114 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
119115 }
119116 rc2 = nodeRelease(pRtree, pParent);
119117 if( rc==SQLITE_OK ){
119118 rc = rc2;
119119 }
119120 if( rc!=SQLITE_OK ){
119121 return rc;
119122 }
119123
119124 /* Remove the xxx_node entry. */
119125 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
@@ -118084,12 +119145,13 @@
119145 pRtree->pDeleted = pNode;
119146
119147 return SQLITE_OK;
119148 }
119149
119150 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
119151 RtreeNode *pParent = pNode->pParent;
119152 int rc = SQLITE_OK;
119153 if( pParent ){
119154 int ii;
119155 int nCell = NCELL(pNode);
119156 RtreeCell box; /* Bounding box for pNode */
119157 nodeGetCell(pRtree, pNode, 0, &box);
@@ -118097,21 +119159,25 @@
119159 RtreeCell cell;
119160 nodeGetCell(pRtree, pNode, ii, &cell);
119161 cellUnion(pRtree, &box, &cell);
119162 }
119163 box.iRowid = pNode->iNode;
119164 rc = nodeParentIndex(pRtree, pNode, &ii);
119165 if( rc==SQLITE_OK ){
119166 nodeOverwriteCell(pRtree, pParent, &box, ii);
119167 rc = fixBoundingBox(pRtree, pParent);
119168 }
119169 }
119170 return rc;
119171 }
119172
119173 /*
119174 ** Delete the cell at index iCell of node pNode. After removing the
119175 ** cell, adjust the r-tree data structure if required.
119176 */
119177 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
119178 RtreeNode *pParent;
119179 int rc;
119180
119181 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
119182 return rc;
119183 }
@@ -118124,18 +119190,17 @@
119190 /* If the node is not the tree root and now has less than the minimum
119191 ** number of cells, remove it from the tree. Otherwise, update the
119192 ** cell in the parent node so that it tightly contains the updated
119193 ** node.
119194 */
119195 pParent = pNode->pParent;
119196 assert( pParent || pNode->iNode==1 );
119197 if( pParent ){
119198 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
 
119199 rc = removeNode(pRtree, pNode, iHeight);
119200 }else{
119201 rc = fixBoundingBox(pRtree, pNode);
119202 }
119203 }
119204
119205 return rc;
119206 }
@@ -118214,11 +119279,11 @@
119279 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
119280 }
119281 }
119282 }
119283 if( rc==SQLITE_OK ){
119284 rc = fixBoundingBox(pRtree, pNode);
119285 }
119286 for(; rc==SQLITE_OK && ii<nCell; ii++){
119287 /* Find a node to store this cell in. pNode->iNode currently contains
119288 ** the height of the sub-tree headed by the cell.
119289 */
@@ -118268,15 +119333,17 @@
119333 }
119334 #else
119335 rc = SplitNode(pRtree, pNode, pCell, iHeight);
119336 #endif
119337 }else{
119338 rc = AdjustTree(pRtree, pNode, pCell);
119339 if( rc==SQLITE_OK ){
119340 if( iHeight==0 ){
119341 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
119342 }else{
119343 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
119344 }
119345 }
119346 }
119347 return rc;
119348 }
119349
@@ -118342,11 +119409,10 @@
119409 int rc = SQLITE_OK;
119410
119411 rtreeReference(pRtree);
119412
119413 assert(nData>=1);
 
119414
119415 /* If azData[0] is not an SQL NULL value, it is the rowid of a
119416 ** record to delete from the r-tree table. The following block does
119417 ** just that.
119418 */
@@ -118368,12 +119434,14 @@
119434 }
119435
119436 /* Delete the cell in question from the leaf node. */
119437 if( rc==SQLITE_OK ){
119438 int rc2;
119439 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
119440 if( rc==SQLITE_OK ){
119441 rc = deleteCell(pRtree, pLeaf, iCell, 0);
119442 }
119443 rc2 = nodeRelease(pRtree, pLeaf);
119444 if( rc==SQLITE_OK ){
119445 rc = rc2;
119446 }
119447 }
@@ -118391,23 +119459,24 @@
119459 **
119460 ** This is equivalent to copying the contents of the child into
119461 ** the root node (the operation that Gutman's paper says to perform
119462 ** in this scenario).
119463 */
119464 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
119465 int rc2;
119466 RtreeNode *pChild;
119467 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
119468 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
119469 if( rc==SQLITE_OK ){
119470 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
119471 }
119472 rc2 = nodeRelease(pRtree, pChild);
119473 if( rc==SQLITE_OK ) rc = rc2;
119474 if( rc==SQLITE_OK ){
119475 pRtree->iDepth--;
119476 writeInt16(pRoot->zData, pRtree->iDepth);
119477 pRoot->isDirty = 1;
119478 }
119479 }
119480
119481 /* Re-insert the contents of any underfull nodes removed from the tree. */
119482 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
@@ -118693,11 +119762,11 @@
119762 ){
119763 int rc = SQLITE_OK;
119764 Rtree *pRtree;
119765 int nDb; /* Length of string argv[1] */
119766 int nName; /* Length of string argv[2] */
119767 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
119768
119769 const char *aErrMsg[] = {
119770 0, /* 0 */
119771 "Wrong number of columns for an rtree table", /* 1 */
119772 "Too few columns for an rtree table", /* 2 */
@@ -118839,16 +119908,14 @@
119908 ** Register the r-tree module with database handle db. This creates the
119909 ** virtual table module "rtree" and the debugging/analysis scalar
119910 ** function "rtreenode".
119911 */
119912 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
119913 const int utf8 = SQLITE_UTF8;
119914 int rc;
119915
119916 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
 
 
 
119917 if( rc==SQLITE_OK ){
119918 int utf8 = SQLITE_UTF8;
119919 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
119920 }
119921 if( rc==SQLITE_OK ){
@@ -118860,10 +119927,74 @@
119927 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
119928 }
119929
119930 return rc;
119931 }
119932
119933 /*
119934 ** A version of sqlite3_free() that can be used as a callback. This is used
119935 ** in two places - as the destructor for the blob value returned by the
119936 ** invocation of a geometry function, and as the destructor for the geometry
119937 ** functions themselves.
119938 */
119939 static void doSqlite3Free(void *p){
119940 sqlite3_free(p);
119941 }
119942
119943 /*
119944 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
119945 ** scalar user function. This C function is the callback used for all such
119946 ** registered SQL functions.
119947 **
119948 ** The scalar user functions return a blob that is interpreted by r-tree
119949 ** table MATCH operators.
119950 */
119951 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
119952 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
119953 RtreeMatchArg *pBlob;
119954 int nBlob;
119955
119956 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
119957 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
119958 if( !pBlob ){
119959 sqlite3_result_error_nomem(ctx);
119960 }else{
119961 int i;
119962 pBlob->magic = RTREE_GEOMETRY_MAGIC;
119963 pBlob->xGeom = pGeomCtx->xGeom;
119964 pBlob->pContext = pGeomCtx->pContext;
119965 pBlob->nParam = nArg;
119966 for(i=0; i<nArg; i++){
119967 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
119968 }
119969 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
119970 }
119971 }
119972
119973 /*
119974 ** Register a new geometry function for use with the r-tree MATCH operator.
119975 */
119976 SQLITE_API int sqlite3_rtree_geometry_callback(
119977 sqlite3 *db,
119978 const char *zGeom,
119979 int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
119980 void *pContext
119981 ){
119982 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
119983
119984 /* Allocate and populate the context object. */
119985 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
119986 if( !pGeomCtx ) return SQLITE_NOMEM;
119987 pGeomCtx->xGeom = xGeom;
119988 pGeomCtx->pContext = pContext;
119989
119990 /* Create the new user-function. Register a destructor function to delete
119991 ** the context object when it is no longer required. */
119992 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
119993 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
119994 );
119995 }
119996
119997 #if !SQLITE_CORE
119998 SQLITE_API int sqlite3_extension_init(
119999 sqlite3 *db,
120000 char **pzErrMsg,
120001
+469 -251
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -105,13 +105,13 @@
105105
**
106106
** See also: [sqlite3_libversion()],
107107
** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108108
** [sqlite_version()] and [sqlite_source_id()].
109109
*/
110
-#define SQLITE_VERSION "3.7.2"
111
-#define SQLITE_VERSION_NUMBER 3007002
112
-#define SQLITE_SOURCE_ID "2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3"
110
+#define SQLITE_VERSION "3.7.3"
111
+#define SQLITE_VERSION_NUMBER 3007003
112
+#define SQLITE_SOURCE_ID "2010-09-29 23:09:23 1ef0dc9328f47506cb2dcd142150e96cb4755216"
113113
114114
/*
115115
** CAPI3REF: Run-Time Library Version Numbers
116116
** KEYWORDS: sqlite3_version, sqlite3_sourceid
117117
**
@@ -755,19 +755,23 @@
755755
** object once the object has been registered.
756756
**
757757
** The zName field holds the name of the VFS module. The name must
758758
** be unique across all VFS modules.
759759
**
760
-** SQLite will guarantee that the zFilename parameter to xOpen
760
+** ^SQLite guarantees that the zFilename parameter to xOpen
761761
** is either a NULL pointer or string obtained
762
-** from xFullPathname(). SQLite further guarantees that
762
+** from xFullPathname() with an optional suffix added.
763
+** ^If a suffix is added to the zFilename parameter, it will
764
+** consist of a single "-" character followed by no more than
765
+** 10 alphanumeric and/or "-" characters.
766
+** ^SQLite further guarantees that
763767
** the string will be valid and unchanged until xClose() is
764768
** called. Because of the previous sentence,
765769
** the [sqlite3_file] can safely store a pointer to the
766770
** filename if it needs to remember the filename for some reason.
767
-** If the zFilename parameter is xOpen is a NULL pointer then xOpen
768
-** must invent its own temporary name for the file. Whenever the
771
+** If the zFilename parameter to xOpen is a NULL pointer then xOpen
772
+** must invent its own temporary name for the file. ^Whenever the
769773
** xFilename parameter is NULL it will also be the case that the
770774
** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
771775
**
772776
** The flags argument to xOpen() includes all bits set in
773777
** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -774,11 +778,11 @@
774778
** or [sqlite3_open16()] is used, then flags includes at least
775779
** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
776780
** If xOpen() opens a file read-only then it sets *pOutFlags to
777781
** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
778782
**
779
-** SQLite will also add one of the following flags to the xOpen()
783
+** ^(SQLite will also add one of the following flags to the xOpen()
780784
** call, depending on the object being opened:
781785
**
782786
** <ul>
783787
** <li> [SQLITE_OPEN_MAIN_DB]
784788
** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -785,11 +789,12 @@
785789
** <li> [SQLITE_OPEN_TEMP_DB]
786790
** <li> [SQLITE_OPEN_TEMP_JOURNAL]
787791
** <li> [SQLITE_OPEN_TRANSIENT_DB]
788792
** <li> [SQLITE_OPEN_SUBJOURNAL]
789793
** <li> [SQLITE_OPEN_MASTER_JOURNAL]
790
-** </ul>
794
+** <li> [SQLITE_OPEN_WAL]
795
+** </ul>)^
791796
**
792797
** The file I/O implementation can use the object type flags to
793798
** change the way it deals with files. For example, an application
794799
** that does not care about crash recovery or rollback might make
795800
** the open of a journal file a no-op. Writes to this journal would
@@ -804,39 +809,40 @@
804809
** <li> [SQLITE_OPEN_DELETEONCLOSE]
805810
** <li> [SQLITE_OPEN_EXCLUSIVE]
806811
** </ul>
807812
**
808813
** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
809
-** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
810
-** will be set for TEMP databases, journals and for subjournals.
814
+** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
815
+** will be set for TEMP databases and their journals, transient
816
+** databases, and subjournals.
811817
**
812
-** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
818
+** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
813819
** with the [SQLITE_OPEN_CREATE] flag, which are both directly
814820
** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
815821
** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
816822
** SQLITE_OPEN_CREATE, is used to indicate that file should always
817823
** be created, and that it is an error if it already exists.
818824
** It is <i>not</i> used to indicate the file should be opened
819825
** for exclusive access.
820826
**
821
-** At least szOsFile bytes of memory are allocated by SQLite
827
+** ^At least szOsFile bytes of memory are allocated by SQLite
822828
** to hold the [sqlite3_file] structure passed as the third
823829
** argument to xOpen. The xOpen method does not have to
824830
** allocate the structure; it should just fill it in. Note that
825831
** the xOpen method must set the sqlite3_file.pMethods to either
826832
** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
827833
** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
828834
** element will be valid after xOpen returns regardless of the success
829835
** or failure of the xOpen call.
830836
**
831
-** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
837
+** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
832838
** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
833839
** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
834840
** to test whether a file is at least readable. The file can be a
835841
** directory.
836842
**
837
-** SQLite will always allocate at least mxPathname+1 bytes for the
843
+** ^SQLite will always allocate at least mxPathname+1 bytes for the
838844
** output buffer xFullPathname. The exact size of the output buffer
839845
** is also passed as a parameter to both methods. If the output buffer
840846
** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
841847
** handled as a fatal error by SQLite, vfs implementations should endeavor
842848
** to prevent this by setting mxPathname to a sufficiently large value.
@@ -846,14 +852,14 @@
846852
** included in the VFS structure for completeness.
847853
** The xRandomness() function attempts to return nBytes bytes
848854
** of good-quality randomness into zOut. The return value is
849855
** the actual number of bytes of randomness obtained.
850856
** The xSleep() method causes the calling thread to sleep for at
851
-** least the number of microseconds given. The xCurrentTime()
857
+** least the number of microseconds given. ^The xCurrentTime()
852858
** method returns a Julian Day Number for the current date and time as
853859
** a floating point value.
854
-** The xCurrentTimeInt64() method returns, as an integer, the Julian
860
+** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
855861
** Day Number multipled by 86400000 (the number of milliseconds in
856862
** a 24-hour day).
857863
** ^SQLite will use the xCurrentTimeInt64() method to get the current
858864
** date and time if that method is available (if iVersion is 2 or
859865
** greater and the function pointer is not NULL) and will fall back
@@ -1246,11 +1252,11 @@
12461252
** statistics. ^(When memory allocation statistics are disabled, the
12471253
** following SQLite interfaces become non-operational:
12481254
** <ul>
12491255
** <li> [sqlite3_memory_used()]
12501256
** <li> [sqlite3_memory_highwater()]
1251
-** <li> [sqlite3_soft_heap_limit()]
1257
+** <li> [sqlite3_soft_heap_limit64()]
12521258
** <li> [sqlite3_status()]
12531259
** </ul>)^
12541260
** ^Memory allocation statistics are enabled by default unless SQLite is
12551261
** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
12561262
** allocation statistics are disabled by default.
@@ -1260,19 +1266,18 @@
12601266
** <dd> ^This option specifies a static memory buffer that SQLite can use for
12611267
** scratch memory. There are three arguments: A pointer an 8-byte
12621268
** aligned memory buffer from which the scrach allocations will be
12631269
** drawn, the size of each scratch allocation (sz),
12641270
** and the maximum number of scratch allocations (N). The sz
1265
-** argument must be a multiple of 16. The sz parameter should be a few bytes
1266
-** larger than the actual scratch space required due to internal overhead.
1271
+** argument must be a multiple of 16.
12671272
** The first argument must be a pointer to an 8-byte aligned buffer
12681273
** of at least sz*N bytes of memory.
1269
-** ^SQLite will use no more than one scratch buffer per thread. So
1270
-** N should be set to the expected maximum number of threads. ^SQLite will
1271
-** never require a scratch buffer that is more than 6 times the database
1272
-** page size. ^If SQLite needs needs additional scratch memory beyond
1273
-** what is provided by this configuration option, then
1274
+** ^SQLite will use no more than two scratch buffers per thread. So
1275
+** N should be set to twice the expected maximum number of threads.
1276
+** ^SQLite will never require a scratch buffer that is more than 6
1277
+** times the database page size. ^If SQLite needs needs additional
1278
+** scratch memory beyond what is provided by this configuration option, then
12741279
** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
12751280
**
12761281
** <dt>SQLITE_CONFIG_PAGECACHE</dt>
12771282
** <dd> ^This option specifies a static memory buffer that SQLite can use for
12781283
** the database page cache with the default page cache implemenation.
@@ -1288,12 +1293,11 @@
12881293
** argument should point to an allocation of at least sz*N bytes of memory.
12891294
** ^SQLite will use the memory provided by the first argument to satisfy its
12901295
** memory needs for the first N pages that it adds to cache. ^If additional
12911296
** page cache memory is needed beyond what is provided by this option, then
12921297
** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1293
-** ^The implementation might use one or more of the N buffers to hold
1294
-** memory accounting information. The pointer in the first argument must
1298
+** The pointer in the first argument must
12951299
** be aligned to an 8-byte boundary or subsequent behavior of SQLite
12961300
** will be undefined.</dd>
12971301
**
12981302
** <dt>SQLITE_CONFIG_HEAP</dt>
12991303
** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1418,12 +1422,18 @@
14181422
** size of each lookaside buffer slot. ^The third argument is the number of
14191423
** slots. The size of the buffer in the first argument must be greater than
14201424
** or equal to the product of the second and third arguments. The buffer
14211425
** must be aligned to an 8-byte boundary. ^If the second argument to
14221426
** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1423
-** rounded down to the next smaller
1424
-** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1427
+** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1428
+** configuration for a database connection can only be changed when that
1429
+** connection is not currently using lookaside memory, or in other words
1430
+** when the "current value" returned by
1431
+** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1432
+** Any attempt to change the lookaside memory configuration when lookaside
1433
+** memory is in use leaves the configuration unchanged and returns
1434
+** [SQLITE_BUSY].)^</dd>
14251435
**
14261436
** </dl>
14271437
*/
14281438
#define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
14291439
@@ -1723,10 +1733,13 @@
17231733
*/
17241734
SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
17251735
17261736
/*
17271737
** CAPI3REF: Convenience Routines For Running Queries
1738
+**
1739
+** This is a legacy interface that is preserved for backwards compatibility.
1740
+** Use of this interface is not recommended.
17281741
**
17291742
** Definition: A <b>result table</b> is memory data structure created by the
17301743
** [sqlite3_get_table()] interface. A result table records the
17311744
** complete query results from one or more queries.
17321745
**
@@ -1744,11 +1757,11 @@
17441757
**
17451758
** A result table might consist of one or more memory allocations.
17461759
** It is not safe to pass a result table directly to [sqlite3_free()].
17471760
** A result table should be deallocated using [sqlite3_free_table()].
17481761
**
1749
-** As an example of the result table format, suppose a query result
1762
+** ^(As an example of the result table format, suppose a query result
17501763
** is as follows:
17511764
**
17521765
** <blockquote><pre>
17531766
** Name | Age
17541767
** -----------------------
@@ -1768,31 +1781,31 @@
17681781
** azResult&#91;3] = "43";
17691782
** azResult&#91;4] = "Bob";
17701783
** azResult&#91;5] = "28";
17711784
** azResult&#91;6] = "Cindy";
17721785
** azResult&#91;7] = "21";
1773
-** </pre></blockquote>
1786
+** </pre></blockquote>)^
17741787
**
17751788
** ^The sqlite3_get_table() function evaluates one or more
17761789
** semicolon-separated SQL statements in the zero-terminated UTF-8
17771790
** string of its 2nd parameter and returns a result table to the
17781791
** pointer given in its 3rd parameter.
17791792
**
17801793
** After the application has finished with the result from sqlite3_get_table(),
1781
-** it should pass the result table pointer to sqlite3_free_table() in order to
1794
+** it must pass the result table pointer to sqlite3_free_table() in order to
17821795
** release the memory that was malloced. Because of the way the
17831796
** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
17841797
** function must not try to call [sqlite3_free()] directly. Only
17851798
** [sqlite3_free_table()] is able to release the memory properly and safely.
17861799
**
1787
-** ^(The sqlite3_get_table() interface is implemented as a wrapper around
1800
+** The sqlite3_get_table() interface is implemented as a wrapper around
17881801
** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
17891802
** to any internal data structures of SQLite. It uses only the public
17901803
** interface defined here. As a consequence, errors that occur in the
17911804
** wrapper layer outside of the internal [sqlite3_exec()] call are not
17921805
** reflected in subsequent calls to [sqlite3_errcode()] or
1793
-** [sqlite3_errmsg()].)^
1806
+** [sqlite3_errmsg()].
17941807
*/
17951808
SQLITE_API int sqlite3_get_table(
17961809
sqlite3 *db, /* An open database */
17971810
const char *zSql, /* SQL to be evaluated */
17981811
char ***pazResult, /* Results of the query */
@@ -1940,11 +1953,13 @@
19401953
** by sqlite3_realloc() and the prior allocation is freed.
19411954
** ^If sqlite3_realloc() returns NULL, then the prior allocation
19421955
** is not freed.
19431956
**
19441957
** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
1945
-** is always aligned to at least an 8 byte boundary.
1958
+** is always aligned to at least an 8 byte boundary, or to a
1959
+** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
1960
+** option is used.
19461961
**
19471962
** In SQLite version 3.5.0 and 3.5.1, it was possible to define
19481963
** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
19491964
** implementation of these routines to be omitted. That capability
19501965
** is no longer provided. Only built-in memory allocators can be used.
@@ -2198,21 +2213,32 @@
21982213
void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
21992214
22002215
/*
22012216
** CAPI3REF: Query Progress Callbacks
22022217
**
2203
-** ^This routine configures a callback function - the
2204
-** progress callback - that is invoked periodically during long
2205
-** running calls to [sqlite3_exec()], [sqlite3_step()] and
2206
-** [sqlite3_get_table()]. An example use for this
2218
+** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2219
+** function X to be invoked periodically during long running calls to
2220
+** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2221
+** database connection D. An example use for this
22072222
** interface is to keep a GUI updated during a large query.
2223
+**
2224
+** ^The parameter P is passed through as the only parameter to the
2225
+** callback function X. ^The parameter N is the number of
2226
+** [virtual machine instructions] that are evaluated between successive
2227
+** invocations of the callback X.
2228
+**
2229
+** ^Only a single progress handler may be defined at one time per
2230
+** [database connection]; setting a new progress handler cancels the
2231
+** old one. ^Setting parameter X to NULL disables the progress handler.
2232
+** ^The progress handler is also disabled by setting N to a value less
2233
+** than 1.
22082234
**
22092235
** ^If the progress callback returns non-zero, the operation is
22102236
** interrupted. This feature can be used to implement a
22112237
** "Cancel" button on a GUI progress dialog box.
22122238
**
2213
-** The progress handler must not do anything that will modify
2239
+** The progress handler callback must not do anything that will modify
22142240
** the database connection that invoked the progress handler.
22152241
** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
22162242
** database connections for the meaning of "modify" in this paragraph.
22172243
**
22182244
*/
@@ -2267,11 +2293,11 @@
22672293
** </dl>
22682294
**
22692295
** If the 3rd parameter to sqlite3_open_v2() is not one of the
22702296
** combinations shown above or one of the combinations shown above combined
22712297
** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2272
-** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2298
+** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
22732299
** then the behavior is undefined.
22742300
**
22752301
** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
22762302
** opens in the multi-thread [threading mode] as long as the single-thread
22772303
** mode has not been set at compile-time or start-time. ^If the
@@ -2392,21 +2418,26 @@
23922418
** ^(This interface allows the size of various constructs to be limited
23932419
** on a connection by connection basis. The first parameter is the
23942420
** [database connection] whose limit is to be set or queried. The
23952421
** second parameter is one of the [limit categories] that define a
23962422
** class of constructs to be size limited. The third parameter is the
2397
-** new limit for that construct. The function returns the old limit.)^
2423
+** new limit for that construct.)^
23982424
**
23992425
** ^If the new limit is a negative number, the limit is unchanged.
2400
-** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2426
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
24012427
** [limits | hard upper bound]
2402
-** set by a compile-time C preprocessor macro named
2403
-** [limits | SQLITE_MAX_XYZ].
2428
+** set at compile-time by a C preprocessor macro called
2429
+** [limits | SQLITE_MAX_<i>NAME</i>].
24042430
** (The "_LIMIT_" in the name is changed to "_MAX_".))^
24052431
** ^Attempts to increase a limit above its hard upper bound are
24062432
** silently truncated to the hard upper bound.
24072433
**
2434
+** ^Regardless of whether or not the limit was changed, the
2435
+** [sqlite3_limit()] interface returns the prior value of the limit.
2436
+** ^Hence, to find the current value of a limit without changing it,
2437
+** simply invoke this interface with the third parameter set to -1.
2438
+**
24082439
** Run-time limits are intended for use in applications that manage
24092440
** both their own internal database and also databases that are controlled
24102441
** by untrusted external sources. An example application might be a
24112442
** web browser that has its own databases for storing history and
24122443
** separate databases controlled by JavaScript applications downloaded
@@ -2431,11 +2462,11 @@
24312462
** The synopsis of the meanings of the various limits is shown below.
24322463
** Additional information is available at [limits | Limits in SQLite].
24332464
**
24342465
** <dl>
24352466
** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2436
-** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2467
+** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
24372468
**
24382469
** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
24392470
** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
24402471
**
24412472
** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2449,11 +2480,13 @@
24492480
** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
24502481
** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
24512482
**
24522483
** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
24532484
** <dd>The maximum number of instructions in a virtual machine program
2454
-** used to implement an SQL statement.</dd>)^
2485
+** used to implement an SQL statement. This limit is not currently
2486
+** enforced, though that might be added in some future release of
2487
+** SQLite.</dd>)^
24552488
**
24562489
** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
24572490
** <dd>The maximum number of arguments on a function.</dd>)^
24582491
**
24592492
** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2462,12 +2495,11 @@
24622495
** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
24632496
** <dd>The maximum length of the pattern argument to the [LIKE] or
24642497
** [GLOB] operators.</dd>)^
24652498
**
24662499
** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2467
-** <dd>The maximum number of variables in an SQL statement that can
2468
-** be bound.</dd>)^
2500
+** <dd>The maximum index number of any [parameter] in an SQL statement.)^
24692501
**
24702502
** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
24712503
** <dd>The maximum depth of recursion for triggers.</dd>)^
24722504
** </dl>
24732505
*/
@@ -2535,16 +2567,11 @@
25352567
**
25362568
** <ol>
25372569
** <li>
25382570
** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
25392571
** always used to do, [sqlite3_step()] will automatically recompile the SQL
2540
-** statement and try to run it again. ^If the schema has changed in
2541
-** a way that makes the statement no longer valid, [sqlite3_step()] will still
2542
-** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
2543
-** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
2544
-** error go away. Note: use [sqlite3_errmsg()] to find the text
2545
-** of the parsing error that results in an [SQLITE_SCHEMA] return.
2572
+** statement and try to run it again.
25462573
** </li>
25472574
**
25482575
** <li>
25492576
** ^When an error occurs, [sqlite3_step()] will return one of the detailed
25502577
** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -2553,15 +2580,20 @@
25532580
** in order to find the underlying cause of the problem. With the "v2" prepare
25542581
** interfaces, the underlying reason for the error is returned immediately.
25552582
** </li>
25562583
**
25572584
** <li>
2558
-** ^If the value of a [parameter | host parameter] in the WHERE clause might
2559
-** change the query plan for a statement, then the statement may be
2560
-** automatically recompiled (as if there had been a schema change) on the first
2561
-** [sqlite3_step()] call following any change to the
2562
-** [sqlite3_bind_text | bindings] of the [parameter].
2585
+** ^If the specific value bound to [parameter | host parameter] in the
2586
+** WHERE clause might influence the choice of query plan for a statement,
2587
+** then the statement will be automatically recompiled, as if there had been
2588
+** a schema change, on the first [sqlite3_step()] call following any change
2589
+** to the [sqlite3_bind_text | bindings] of that [parameter].
2590
+** ^The specific value of WHERE-clause [parameter] might influence the
2591
+** choice of query plan if the parameter is the left-hand side of a [LIKE]
2592
+** or [GLOB] operator or if the parameter is compared to an indexed column
2593
+** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
2594
+** the
25632595
** </li>
25642596
** </ol>
25652597
*/
25662598
SQLITE_API int sqlite3_prepare(
25672599
sqlite3 *db, /* Database handle */
@@ -2624,11 +2656,11 @@
26242656
** or if SQLite is run in one of reduced mutex modes
26252657
** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
26262658
** then there is no distinction between protected and unprotected
26272659
** sqlite3_value objects and they can be used interchangeably. However,
26282660
** for maximum code portability it is recommended that applications
2629
-** still make the distinction between between protected and unprotected
2661
+** still make the distinction between protected and unprotected
26302662
** sqlite3_value objects even when not strictly required.
26312663
**
26322664
** ^The sqlite3_value objects that are passed as parameters into the
26332665
** implementation of [application-defined SQL functions] are protected.
26342666
** ^The sqlite3_value object returned by
@@ -2819,10 +2851,12 @@
28192851
** CAPI3REF: Number Of Columns In A Result Set
28202852
**
28212853
** ^Return the number of columns in the result set returned by the
28222854
** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
28232855
** statement that does not return data (for example an [UPDATE]).
2856
+**
2857
+** See also: [sqlite3_data_count()]
28242858
*/
28252859
SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
28262860
28272861
/*
28282862
** CAPI3REF: Column Names In A Result Set
@@ -3009,12 +3043,18 @@
30093043
SQLITE_API int sqlite3_step(sqlite3_stmt*);
30103044
30113045
/*
30123046
** CAPI3REF: Number of columns in a result set
30133047
**
3014
-** ^The sqlite3_data_count(P) the number of columns in the
3015
-** of the result set of [prepared statement] P.
3048
+** ^The sqlite3_data_count(P) interface returns the number of columns in the
3049
+** current row of the result set of [prepared statement] P.
3050
+** ^If prepared statement P does not have results ready to return
3051
+** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3052
+** interfaces) then sqlite3_data_count(P) returns 0.
3053
+** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3054
+**
3055
+** See also: [sqlite3_column_count()]
30163056
*/
30173057
SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
30183058
30193059
/*
30203060
** CAPI3REF: Fundamental Datatypes
@@ -3090,22 +3130,30 @@
30903130
** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
30913131
** the string to UTF-8 and then returns the number of bytes.
30923132
** ^If the result is a numeric value then sqlite3_column_bytes() uses
30933133
** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
30943134
** the number of bytes in that string.
3095
-** ^The value returned does not include the zero terminator at the end
3096
-** of the string. ^For clarity: the value returned is the number of
3135
+** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3136
+**
3137
+** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3138
+** routine returns the number of bytes in that BLOB or string.
3139
+** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3140
+** the string to UTF-16 and then returns the number of bytes.
3141
+** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3142
+** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3143
+** the number of bytes in that string.
3144
+** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3145
+**
3146
+** ^The values returned by [sqlite3_column_bytes()] and
3147
+** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3148
+** of the string. ^For clarity: the values returned by
3149
+** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
30973150
** bytes in the string, not the number of characters.
30983151
**
30993152
** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
31003153
** even empty strings, are always zero terminated. ^The return
3101
-** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3102
-** pointer, possibly even a NULL pointer.
3103
-**
3104
-** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3105
-** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3106
-** ^The zero terminator is not included in this count.
3154
+** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
31073155
**
31083156
** ^The object returned by [sqlite3_column_value()] is an
31093157
** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
31103158
** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
31113159
** If the [unprotected sqlite3_value] object returned by
@@ -3146,14 +3194,14 @@
31463194
** and atof(). SQLite does not really use these functions. It has its
31473195
** own equivalent internal routines. The atoi() and atof() names are
31483196
** used in the table for brevity and because they are familiar to most
31493197
** C programmers.
31503198
**
3151
-** ^Note that when type conversions occur, pointers returned by prior
3199
+** Note that when type conversions occur, pointers returned by prior
31523200
** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
31533201
** sqlite3_column_text16() may be invalidated.
3154
-** ^(Type conversions and pointer invalidations might occur
3202
+** Type conversions and pointer invalidations might occur
31553203
** in the following cases:
31563204
**
31573205
** <ul>
31583206
** <li> The initial content is a BLOB and sqlite3_column_text() or
31593207
** sqlite3_column_text16() is called. A zero-terminator might
@@ -3162,26 +3210,26 @@
31623210
** sqlite3_column_text16() is called. The content must be converted
31633211
** to UTF-16.</li>
31643212
** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
31653213
** sqlite3_column_text() is called. The content must be converted
31663214
** to UTF-8.</li>
3167
-** </ul>)^
3215
+** </ul>
31683216
**
31693217
** ^Conversions between UTF-16be and UTF-16le are always done in place and do
31703218
** not invalidate a prior pointer, though of course the content of the buffer
3171
-** that the prior pointer points to will have been modified. Other kinds
3219
+** that the prior pointer references will have been modified. Other kinds
31723220
** of conversion are done in place when it is possible, but sometimes they
31733221
** are not possible and in those cases prior pointers are invalidated.
31743222
**
3175
-** ^(The safest and easiest to remember policy is to invoke these routines
3223
+** The safest and easiest to remember policy is to invoke these routines
31763224
** in one of the following ways:
31773225
**
31783226
** <ul>
31793227
** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
31803228
** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
31813229
** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3182
-** </ul>)^
3230
+** </ul>
31833231
**
31843232
** In other words, you should call sqlite3_column_text(),
31853233
** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
31863234
** into the desired format, then invoke sqlite3_column_bytes() or
31873235
** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3215,21 +3263,30 @@
32153263
32163264
/*
32173265
** CAPI3REF: Destroy A Prepared Statement Object
32183266
**
32193267
** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3220
-** ^If the statement was executed successfully or not executed at all, then
3221
-** SQLITE_OK is returned. ^If execution of the statement failed then an
3222
-** [error code] or [extended error code] is returned.
3268
+** ^If the most recent evaluation of the statement encountered no errors or
3269
+** or if the statement is never been evaluated, then sqlite3_finalize() returns
3270
+** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3271
+** sqlite3_finalize(S) returns the appropriate [error code] or
3272
+** [extended error code].
32233273
**
3224
-** ^This routine can be called at any point during the execution of the
3225
-** [prepared statement]. ^If the virtual machine has not
3226
-** completed execution when this routine is called, that is like
3227
-** encountering an error or an [sqlite3_interrupt | interrupt].
3228
-** ^Incomplete updates may be rolled back and transactions canceled,
3229
-** depending on the circumstances, and the
3230
-** [error code] returned will be [SQLITE_ABORT].
3274
+** ^The sqlite3_finalize(S) routine can be called at any point during
3275
+** the life cycle of [prepared statement] S:
3276
+** before statement S is ever evaluated, after
3277
+** one or more calls to [sqlite3_reset()], or after any call
3278
+** to [sqlite3_step()] regardless of whether or not the statement has
3279
+** completed execution.
3280
+**
3281
+** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3282
+**
3283
+** The application must finalize every [prepared statement] in order to avoid
3284
+** resource leaks. It is a grievous error for the application to try to use
3285
+** a prepared statement after it has been finalized. Any use of a prepared
3286
+** statement after it has been finalized can result in undefined and
3287
+** undesirable behavior such as segfaults and heap corruption.
32313288
*/
32323289
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
32333290
32343291
/*
32353292
** CAPI3REF: Reset A Prepared Statement Object
@@ -3261,40 +3318,42 @@
32613318
** CAPI3REF: Create Or Redefine SQL Functions
32623319
** KEYWORDS: {function creation routines}
32633320
** KEYWORDS: {application-defined SQL function}
32643321
** KEYWORDS: {application-defined SQL functions}
32653322
**
3266
-** ^These two functions (collectively known as "function creation routines")
3323
+** ^These functions (collectively known as "function creation routines")
32673324
** are used to add SQL functions or aggregates or to redefine the behavior
3268
-** of existing SQL functions or aggregates. The only difference between the
3269
-** two is that the second parameter, the name of the (scalar) function or
3270
-** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3271
-** for sqlite3_create_function16().
3325
+** of existing SQL functions or aggregates. The only differences between
3326
+** these routines are the text encoding expected for
3327
+** the the second parameter (the name of the function being created)
3328
+** and the presence or absence of a destructor callback for
3329
+** the application data pointer.
32723330
**
32733331
** ^The first parameter is the [database connection] to which the SQL
32743332
** function is to be added. ^If an application uses more than one database
32753333
** connection then application-defined SQL functions must be added
32763334
** to each database connection separately.
32773335
**
3278
-** The second parameter is the name of the SQL function to be created or
3279
-** redefined. ^The length of the name is limited to 255 bytes, exclusive of
3280
-** the zero-terminator. Note that the name length limit is in bytes, not
3281
-** characters. ^Any attempt to create a function with a longer name
3282
-** will result in [SQLITE_ERROR] being returned.
3336
+** ^The second parameter is the name of the SQL function to be created or
3337
+** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
3338
+** representation, exclusive of the zero-terminator. ^Note that the name
3339
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
3340
+** ^Any attempt to create a function with a longer name
3341
+** will result in [SQLITE_MISUSE] being returned.
32833342
**
32843343
** ^The third parameter (nArg)
32853344
** is the number of arguments that the SQL function or
32863345
** aggregate takes. ^If this parameter is -1, then the SQL function or
32873346
** aggregate may take any number of arguments between 0 and the limit
32883347
** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
32893348
** parameter is less than -1 or greater than 127 then the behavior is
32903349
** undefined.
32913350
**
3292
-** The fourth parameter, eTextRep, specifies what
3351
+** ^The fourth parameter, eTextRep, specifies what
32933352
** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3294
-** its parameters. Any SQL function implementation should be able to work
3295
-** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3353
+** its parameters. Every SQL function implementation must be able to work
3354
+** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
32963355
** more efficient with one encoding than another. ^An application may
32973356
** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
32983357
** times with the same function but with different values of eTextRep.
32993358
** ^When multiple implementations of the same function are available, SQLite
33003359
** will pick the one that involves the least amount of data conversion.
@@ -3302,17 +3361,25 @@
33023361
** encoding is used, then the fourth argument should be [SQLITE_ANY].
33033362
**
33043363
** ^(The fifth parameter is an arbitrary pointer. The implementation of the
33053364
** function can gain access to this pointer using [sqlite3_user_data()].)^
33063365
**
3307
-** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3366
+** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
33083367
** pointers to C-language functions that implement the SQL function or
33093368
** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3310
-** callback only; NULL pointers should be passed as the xStep and xFinal
3369
+** callback only; NULL pointers must be passed as the xStep and xFinal
33113370
** parameters. ^An aggregate SQL function requires an implementation of xStep
3312
-** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3313
-** SQL function or aggregate, pass NULL for all three function callbacks.
3371
+** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3372
+** SQL function or aggregate, pass NULL poiners for all three function
3373
+** callbacks.
3374
+**
3375
+** ^If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3376
+** then it is invoked when the function is deleted, either by being
3377
+** overloaded or when the database connection closes.
3378
+** ^When the destructure callback of the tenth parameter is invoked, it
3379
+** is passed a single argument which is a copy of the pointer which was
3380
+** the fifth parameter to sqlite3_create_function_v2().
33143381
**
33153382
** ^It is permitted to register multiple implementations of the same
33163383
** functions with the same name but with either differing numbers of
33173384
** arguments or differing preferred text encodings. ^SQLite will use
33183385
** the implementation that most closely matches the way in which the
@@ -3324,15 +3391,10 @@
33243391
** ^A function where the encoding difference is between UTF16le and UTF16be
33253392
** is a closer match than a function where the encoding difference is
33263393
** between UTF8 and UTF16.
33273394
**
33283395
** ^Built-in functions may be overloaded by new application-defined functions.
3329
-** ^The first application-defined function with a given name overrides all
3330
-** built-in functions in the same [database connection] with the same name.
3331
-** ^Subsequent application-defined functions of the same name only override
3332
-** prior application-defined functions that are an exact match for the
3333
-** number of parameters and preferred encoding.
33343396
**
33353397
** ^An application-defined function is permitted to call other
33363398
** SQLite interfaces. However, such calls must not
33373399
** close the database connection nor finalize or reset the prepared
33383400
** statement in which the function is running.
@@ -3354,10 +3416,21 @@
33543416
int eTextRep,
33553417
void *pApp,
33563418
void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
33573419
void (*xStep)(sqlite3_context*,int,sqlite3_value**),
33583420
void (*xFinal)(sqlite3_context*)
3421
+);
3422
+SQLITE_API int sqlite3_create_function_v2(
3423
+ sqlite3 *db,
3424
+ const char *zFunctionName,
3425
+ int nArg,
3426
+ int eTextRep,
3427
+ void *pApp,
3428
+ void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3429
+ void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3430
+ void (*xFinal)(sqlite3_context*),
3431
+ void(*xDestroy)(void*)
33593432
);
33603433
33613434
/*
33623435
** CAPI3REF: Text Encodings
33633436
**
@@ -3701,73 +3774,97 @@
37013774
SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
37023775
37033776
/*
37043777
** CAPI3REF: Define New Collating Sequences
37053778
**
3706
-** These functions are used to add new collation sequences to the
3707
-** [database connection] specified as the first argument.
3779
+** ^These functions add, remove, or modify a [collation] associated
3780
+** with the [database connection] specified as the first argument.
37083781
**
3709
-** ^The name of the new collation sequence is specified as a UTF-8 string
3782
+** ^The name of the collation is a UTF-8 string
37103783
** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3711
-** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
3712
-** the name is passed as the second function argument.
3713
-**
3714
-** ^The third argument may be one of the constants [SQLITE_UTF8],
3715
-** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
3716
-** routine expects to be passed pointers to strings encoded using UTF-8,
3717
-** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
3718
-** third argument might also be [SQLITE_UTF16] to indicate that the routine
3719
-** expects pointers to be UTF-16 strings in the native byte order, or the
3720
-** argument can be [SQLITE_UTF16_ALIGNED] if the
3721
-** the routine expects pointers to 16-bit word aligned strings
3722
-** of UTF-16 in the native byte order.
3723
-**
3724
-** A pointer to the user supplied routine must be passed as the fifth
3725
-** argument. ^If it is NULL, this is the same as deleting the collation
3726
-** sequence (so that SQLite cannot call it any more).
3727
-** ^Each time the application supplied function is invoked, it is passed
3728
-** as its first parameter a copy of the void* passed as the fourth argument
3729
-** to sqlite3_create_collation() or sqlite3_create_collation16().
3730
-**
3731
-** ^The remaining arguments to the application-supplied routine are two strings,
3732
-** each represented by a (length, data) pair and encoded in the encoding
3733
-** that was passed as the third argument when the collation sequence was
3734
-** registered. The application defined collation routine should
3735
-** return negative, zero or positive if the first string is less than,
3736
-** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
3784
+** and a UTF-16 string in native byte order for sqlite3_create_collation16().
3785
+** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
3786
+** considered to be the same name.
3787
+**
3788
+** ^(The third argument (eTextRep) must be one of the constants:
3789
+** <ul>
3790
+** <li> [SQLITE_UTF8],
3791
+** <li> [SQLITE_UTF16LE],
3792
+** <li> [SQLITE_UTF16BE],
3793
+** <li> [SQLITE_UTF16], or
3794
+** <li> [SQLITE_UTF16_ALIGNED].
3795
+** </ul>)^
3796
+** ^The eTextRep argument determines the encoding of strings passed
3797
+** to the collating function callback, xCallback.
3798
+** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
3799
+** force strings to be UTF16 with native byte order.
3800
+** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
3801
+** on an even byte address.
3802
+**
3803
+** ^The fourth argument, pArg, is a application data pointer that is passed
3804
+** through as the first argument to the collating function callback.
3805
+**
3806
+** ^The fifth argument, xCallback, is a pointer to the collating function.
3807
+** ^Multiple collating functions can be registered using the same name but
3808
+** with different eTextRep parameters and SQLite will use whichever
3809
+** function requires the least amount of data transformation.
3810
+** ^If the xCallback argument is NULL then the collating function is
3811
+** deleted. ^When all collating functions having the same name are deleted,
3812
+** that collation is no longer usable.
3813
+**
3814
+** ^The collating function callback is invoked with a copy of the pArg
3815
+** application data pointer and with two strings in the encoding specified
3816
+** by the eTextRep argument. The collating function must return an
3817
+** integer that is negative, zero, or positive
3818
+** if the first string is less than, equal to, or greater than the second,
3819
+** respectively. A collating function must alway return the same answer
3820
+** given the same inputs. If two or more collating functions are registered
3821
+** to the same collation name (using different eTextRep values) then all
3822
+** must give an equivalent answer when invoked with equivalent strings.
3823
+** The collating function must obey the following properties for all
3824
+** strings A, B, and C:
3825
+**
3826
+** <ol>
3827
+** <li> If A==B then B==A.
3828
+** <li> If A==B and B==C then A==C.
3829
+** <li> If A&lt;B THEN B&gt;A.
3830
+** <li> If A&lt;B and B&lt;C then A&lt;C.
3831
+** </ol>
3832
+**
3833
+** If a collating function fails any of the above constraints and that
3834
+** collating function is registered and used, then the behavior of SQLite
3835
+** is undefined.
37373836
**
37383837
** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
3739
-** except that it takes an extra argument which is a destructor for
3740
-** the collation. ^The destructor is called when the collation is
3741
-** destroyed and is passed a copy of the fourth parameter void* pointer
3742
-** of the sqlite3_create_collation_v2().
3743
-** ^Collations are destroyed when they are overridden by later calls to the
3744
-** collation creation functions or when the [database connection] is closed
3745
-** using [sqlite3_close()].
3838
+** with the addition that the xDestroy callback is invoked on pArg when
3839
+** the collating function is deleted.
3840
+** ^Collating functions are deleted when they are overridden by later
3841
+** calls to the collation creation functions or when the
3842
+** [database connection] is closed using [sqlite3_close()].
37463843
**
37473844
** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
37483845
*/
37493846
SQLITE_API int sqlite3_create_collation(
37503847
sqlite3*,
37513848
const char *zName,
37523849
int eTextRep,
3753
- void*,
3850
+ void *pArg,
37543851
int(*xCompare)(void*,int,const void*,int,const void*)
37553852
);
37563853
SQLITE_API int sqlite3_create_collation_v2(
37573854
sqlite3*,
37583855
const char *zName,
37593856
int eTextRep,
3760
- void*,
3857
+ void *pArg,
37613858
int(*xCompare)(void*,int,const void*,int,const void*),
37623859
void(*xDestroy)(void*)
37633860
);
37643861
SQLITE_API int sqlite3_create_collation16(
37653862
sqlite3*,
37663863
const void *zName,
37673864
int eTextRep,
3768
- void*,
3865
+ void *pArg,
37693866
int(*xCompare)(void*,int,const void*,int,const void*)
37703867
);
37713868
37723869
/*
37733870
** CAPI3REF: Collation Needed Callbacks
@@ -3852,20 +3949,23 @@
38523949
#endif
38533950
38543951
/*
38553952
** CAPI3REF: Suspend Execution For A Short Time
38563953
**
3857
-** ^The sqlite3_sleep() function causes the current thread to suspend execution
3954
+** The sqlite3_sleep() function causes the current thread to suspend execution
38583955
** for at least a number of milliseconds specified in its parameter.
38593956
**
3860
-** ^If the operating system does not support sleep requests with
3957
+** If the operating system does not support sleep requests with
38613958
** millisecond time resolution, then the time will be rounded up to
3862
-** the nearest second. ^The number of milliseconds of sleep actually
3959
+** the nearest second. The number of milliseconds of sleep actually
38633960
** requested from the operating system is returned.
38643961
**
38653962
** ^SQLite implements this interface by calling the xSleep()
3866
-** method of the default [sqlite3_vfs] object.
3963
+** method of the default [sqlite3_vfs] object. If the xSleep() method
3964
+** of the default VFS is not implemented correctly, or not implemented at
3965
+** all, then the behavior of sqlite3_sleep() may deviate from the description
3966
+** in the previous paragraphs.
38673967
*/
38683968
SQLITE_API int sqlite3_sleep(int);
38693969
38703970
/*
38713971
** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4083,44 +4183,77 @@
40834183
** of heap memory by deallocating non-essential memory allocations
40844184
** held by the database library. Memory used to cache database
40854185
** pages to improve performance is an example of non-essential memory.
40864186
** ^sqlite3_release_memory() returns the number of bytes actually freed,
40874187
** which might be more or less than the amount requested.
4188
+** ^The sqlite3_release_memory() routine is a no-op returning zero
4189
+** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
40884190
*/
40894191
SQLITE_API int sqlite3_release_memory(int);
40904192
40914193
/*
40924194
** CAPI3REF: Impose A Limit On Heap Size
40934195
**
4094
-** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4095
-** on the amount of heap memory that may be allocated by SQLite.
4096
-** ^If an internal allocation is requested that would exceed the
4097
-** soft heap limit, [sqlite3_release_memory()] is invoked one or
4098
-** more times to free up some space before the allocation is performed.
4099
-**
4100
-** ^The limit is called "soft" because if [sqlite3_release_memory()]
4101
-** cannot free sufficient memory to prevent the limit from being exceeded,
4102
-** the memory is allocated anyway and the current operation proceeds.
4103
-**
4104
-** ^A negative or zero value for N means that there is no soft heap limit and
4105
-** [sqlite3_release_memory()] will only be called when memory is exhausted.
4106
-** ^The default value for the soft heap limit is zero.
4107
-**
4108
-** ^(SQLite makes a best effort to honor the soft heap limit.
4109
-** But if the soft heap limit cannot be honored, execution will
4110
-** continue without error or notification.)^ This is why the limit is
4111
-** called a "soft" limit. It is advisory only.
4112
-**
4113
-** Prior to SQLite version 3.5.0, this routine only constrained the memory
4114
-** allocated by a single thread - the same thread in which this routine
4115
-** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
4116
-** applied to all threads. The value specified for the soft heap limit
4117
-** is an upper bound on the total memory allocation for all threads. In
4118
-** version 3.5.0 there is no mechanism for limiting the heap usage for
4119
-** individual threads.
4196
+** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4197
+** soft limit on the amount of heap memory that may be allocated by SQLite.
4198
+** ^SQLite strives to keep heap memory utilization below the soft heap
4199
+** limit by reducing the number of pages held in the page cache
4200
+** as heap memory usages approaches the limit.
4201
+** ^The soft heap limit is "soft" because even though SQLite strives to stay
4202
+** below the limit, it will exceed the limit rather than generate
4203
+** an [SQLITE_NOMEM] error. In other words, the soft heap limit
4204
+** is advisory only.
4205
+**
4206
+** ^The return value from sqlite3_soft_heap_limit64() is the size of
4207
+** the soft heap limit prior to the call. ^If the argument N is negative
4208
+** then no change is made to the soft heap limit. Hence, the current
4209
+** size of the soft heap limit can be determined by invoking
4210
+** sqlite3_soft_heap_limit64() with a negative argument.
4211
+**
4212
+** ^If the argument N is zero then the soft heap limit is disabled.
4213
+**
4214
+** ^(The soft heap limit is not enforced in the current implementation
4215
+** if one or more of following conditions are true:
4216
+**
4217
+** <ul>
4218
+** <li> The soft heap limit is set to zero.
4219
+** <li> Memory accounting is disabled using a combination of the
4220
+** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4221
+** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4222
+** <li> An alternative page cache implementation is specifed using
4223
+** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4224
+** <li> The page cache allocates from its own memory pool supplied
4225
+** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4226
+** from the heap.
4227
+** </ul>)^
4228
+**
4229
+** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4230
+** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4231
+** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4232
+** the soft heap limit is enforced on every memory allocation. Without
4233
+** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4234
+** when memory is allocated by the page cache. Testing suggests that because
4235
+** the page cache is the predominate memory user in SQLite, most
4236
+** applications will achieve adequate soft heap limit enforcement without
4237
+** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4238
+**
4239
+** The circumstances under which SQLite will enforce the soft heap limit may
4240
+** changes in future releases of SQLite.
4241
+*/
4242
+SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4243
+
4244
+/*
4245
+** CAPI3REF: Deprecated Soft Heap Limit Interface
4246
+** DEPRECATED
4247
+**
4248
+** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4249
+** interface. This routine is provided for historical compatibility
4250
+** only. All new applications should use the
4251
+** [sqlite3_soft_heap_limit64()] interface rather than this one.
41204252
*/
4121
-SQLITE_API void sqlite3_soft_heap_limit(int);
4253
+SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4254
+
41224255
41234256
/*
41244257
** CAPI3REF: Extract Metadata About A Column Of A Table
41254258
**
41264259
** ^This routine returns metadata about a specific column of a specific
@@ -4240,38 +4373,51 @@
42404373
** it back off again.
42414374
*/
42424375
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
42434376
42444377
/*
4245
-** CAPI3REF: Automatically Load An Extensions
4246
-**
4247
-** ^This API can be invoked at program startup in order to register
4248
-** one or more statically linked extensions that will be available
4249
-** to all new [database connections].
4250
-**
4251
-** ^(This routine stores a pointer to the extension entry point
4252
-** in an array that is obtained from [sqlite3_malloc()]. That memory
4253
-** is deallocated by [sqlite3_reset_auto_extension()].)^
4254
-**
4255
-** ^This function registers an extension entry point that is
4256
-** automatically invoked whenever a new [database connection]
4257
-** is opened using [sqlite3_open()], [sqlite3_open16()],
4258
-** or [sqlite3_open_v2()].
4259
-** ^Duplicate extensions are detected so calling this routine
4260
-** multiple times with the same extension is harmless.
4261
-** ^Automatic extensions apply across all threads.
4378
+** CAPI3REF: Automatically Load Statically Linked Extensions
4379
+**
4380
+** ^This interface causes the xEntryPoint() function to be invoked for
4381
+** each new [database connection] that is created. The idea here is that
4382
+** xEntryPoint() is the entry point for a statically linked SQLite extension
4383
+** that is to be automatically loaded into all new database connections.
4384
+**
4385
+** ^(Even though the function prototype shows that xEntryPoint() takes
4386
+** no arguments and returns void, SQLite invokes xEntryPoint() with three
4387
+** arguments and expects and integer result as if the signature of the
4388
+** entry point where as follows:
4389
+**
4390
+** <blockquote><pre>
4391
+** &nbsp; int xEntryPoint(
4392
+** &nbsp; sqlite3 *db,
4393
+** &nbsp; const char **pzErrMsg,
4394
+** &nbsp; const struct sqlite3_api_routines *pThunk
4395
+** &nbsp; );
4396
+** </pre></blockquote>)^
4397
+**
4398
+** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4399
+** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4400
+** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
4401
+** is NULL before calling the xEntryPoint(). ^SQLite will invoke
4402
+** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
4403
+** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4404
+** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4405
+**
4406
+** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4407
+** on the list of automatic extensions is a harmless no-op. ^No entry point
4408
+** will be called more than once for each database connection that is opened.
4409
+**
4410
+** See also: [sqlite3_reset_auto_extension()].
42624411
*/
42634412
SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
42644413
42654414
/*
42664415
** CAPI3REF: Reset Automatic Extension Loading
42674416
**
4268
-** ^(This function disables all previously registered automatic
4269
-** extensions. It undoes the effect of all prior
4270
-** [sqlite3_auto_extension()] calls.)^
4271
-**
4272
-** ^This function disables automatic extensions in all threads.
4417
+** ^This interface disables all automatic extensions previously
4418
+** registered using [sqlite3_auto_extension()].
42734419
*/
42744420
SQLITE_API void sqlite3_reset_auto_extension(void);
42754421
42764422
/*
42774423
** The interface to the virtual-table mechanism is currently considered
@@ -4906,11 +5052,11 @@
49065052
** output variable when querying the system for the current mutex
49075053
** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
49085054
**
49095055
** ^The xMutexInit method defined by this structure is invoked as
49105056
** part of system initialization by the sqlite3_initialize() function.
4911
-** ^The xMutexInit routine is calle by SQLite exactly once for each
5057
+** ^The xMutexInit routine is called by SQLite exactly once for each
49125058
** effective call to [sqlite3_initialize()].
49135059
**
49145060
** ^The xMutexEnd method defined by this structure is invoked as
49155061
** part of system shutdown by the sqlite3_shutdown() function. The
49165062
** implementation of this method is expected to release all outstanding
@@ -5103,11 +5249,12 @@
51035249
#define SQLITE_TESTCTRL_ALWAYS 13
51045250
#define SQLITE_TESTCTRL_RESERVE 14
51055251
#define SQLITE_TESTCTRL_OPTIMIZATIONS 15
51065252
#define SQLITE_TESTCTRL_ISKEYWORD 16
51075253
#define SQLITE_TESTCTRL_PGHDRSZ 17
5108
-#define SQLITE_TESTCTRL_LAST 17
5254
+#define SQLITE_TESTCTRL_SCRATCHMALLOC 18
5255
+#define SQLITE_TESTCTRL_LAST 18
51095256
51105257
/*
51115258
** CAPI3REF: SQLite Runtime Status
51125259
**
51135260
** ^This interface is used to retrieve runtime status information
@@ -5122,11 +5269,11 @@
51225269
** value. For those parameters
51235270
** nothing is written into *pHighwater and the resetFlag is ignored.)^
51245271
** ^(Other parameters record only the highwater mark and not the current
51255272
** value. For these latter parameters nothing is written into *pCurrent.)^
51265273
**
5127
-** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5274
+** ^The sqlite3_status() routine returns SQLITE_OK on success and a
51285275
** non-zero [error code] on failure.
51295276
**
51305277
** This routine is threadsafe but is not atomic. This routine can be
51315278
** called while other threads are running the same or different SQLite
51325279
** interfaces. However the values returned in *pCurrent and
@@ -5172,11 +5319,11 @@
51725319
** [SQLITE_CONFIG_PAGECACHE]. The
51735320
** value returned is in pages, not in bytes.</dd>)^
51745321
**
51755322
** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
51765323
** <dd>This parameter returns the number of bytes of page cache
5177
-** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5324
+** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
51785325
** buffer and where forced to overflow to [sqlite3_malloc()]. The
51795326
** returned value includes allocations that overflowed because they
51805327
** where too large (they were larger than the "sz" parameter to
51815328
** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
51825329
** no space was left in the page cache.</dd>)^
@@ -5195,11 +5342,11 @@
51955342
** outstanding at time, this parameter also reports the number of threads
51965343
** using scratch memory at the same time.</dd>)^
51975344
**
51985345
** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
51995346
** <dd>This parameter returns the number of bytes of scratch memory
5200
-** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5347
+** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
52015348
** buffer and where forced to overflow to [sqlite3_malloc()]. The values
52025349
** returned include overflows because the requested allocation was too
52035350
** larger (that is, because the requested allocation was larger than the
52045351
** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
52055352
** slots were available.
@@ -5243,10 +5390,13 @@
52435390
**
52445391
** ^The current value of the requested parameter is written into *pCur
52455392
** and the highest instantaneous value is written into *pHiwtr. ^If
52465393
** the resetFlg is true, then the highest instantaneous value is
52475394
** reset back down to the current value.
5395
+**
5396
+** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5397
+** non-zero [error code] on failure.
52485398
**
52495399
** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
52505400
*/
52515401
SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
52525402
@@ -5370,122 +5520,134 @@
53705520
** CAPI3REF: Application Defined Page Cache.
53715521
** KEYWORDS: {page cache}
53725522
**
53735523
** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
53745524
** register an alternative page cache implementation by passing in an
5375
-** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5376
-** heap memory used by SQLite is used by the page cache to cache data read
5377
-** from, or ready to be written to, the database file. By implementing a
5378
-** custom page cache using this API, an application can control more
5379
-** precisely the amount of memory consumed by SQLite, the way in which
5525
+** instance of the sqlite3_pcache_methods structure.)^
5526
+** In many applications, most of the heap memory allocated by
5527
+** SQLite is used for the page cache.
5528
+** By implementing a
5529
+** custom page cache using this API, an application can better control
5530
+** the amount of memory consumed by SQLite, the way in which
53805531
** that memory is allocated and released, and the policies used to
53815532
** determine exactly which parts of a database file are cached and for
53825533
** how long.
53835534
**
5535
+** The alternative page cache mechanism is an
5536
+** extreme measure that is only needed by the most demanding applications.
5537
+** The built-in page cache is recommended for most uses.
5538
+**
53845539
** ^(The contents of the sqlite3_pcache_methods structure are copied to an
53855540
** internal buffer by SQLite within the call to [sqlite3_config]. Hence
53865541
** the application may discard the parameter after the call to
53875542
** [sqlite3_config()] returns.)^
53885543
**
5389
-** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5544
+** ^(The xInit() method is called once for each effective
5545
+** call to [sqlite3_initialize()])^
53905546
** (usually only once during the lifetime of the process). ^(The xInit()
53915547
** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5392
-** ^The xInit() method can set up up global structures and/or any mutexes
5548
+** The intent of the xInit() method is to set up global data structures
53935549
** required by the custom page cache implementation.
5550
+** ^(If the xInit() method is NULL, then the
5551
+** built-in default page cache is used instead of the application defined
5552
+** page cache.)^
53945553
**
5395
-** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5396
-** if the application invokes this API. It can be used to clean up
5554
+** ^The xShutdown() method is called by [sqlite3_shutdown()].
5555
+** It can be used to clean up
53975556
** any outstanding resources before process shutdown, if required.
5557
+** ^The xShutdown() method may be NULL.
53985558
**
5399
-** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5400
-** the xInit method, so the xInit method need not be threadsafe. ^The
5559
+** ^SQLite automatically serializes calls to the xInit method,
5560
+** so the xInit method need not be threadsafe. ^The
54015561
** xShutdown method is only called from [sqlite3_shutdown()] so it does
54025562
** not need to be threadsafe either. All other methods must be threadsafe
54035563
** in multithreaded applications.
54045564
**
54055565
** ^SQLite will never invoke xInit() more than once without an intervening
54065566
** call to xShutdown().
54075567
**
5408
-** ^The xCreate() method is used to construct a new cache instance. SQLite
5409
-** will typically create one cache instance for each open database file,
5568
+** ^SQLite invokes the xCreate() method to construct a new cache instance.
5569
+** SQLite will typically create one cache instance for each open database file,
54105570
** though this is not guaranteed. ^The
54115571
** first parameter, szPage, is the size in bytes of the pages that must
54125572
** be allocated by the cache. ^szPage will not be a power of two. ^szPage
54135573
** will the page size of the database file that is to be cached plus an
5414
-** increment (here called "R") of about 100 or 200. ^SQLite will use the
5574
+** increment (here called "R") of about 100 or 200. SQLite will use the
54155575
** extra R bytes on each page to store metadata about the underlying
54165576
** database page on disk. The value of R depends
54175577
** on the SQLite version, the target platform, and how SQLite was compiled.
54185578
** ^R is constant for a particular build of SQLite. ^The second argument to
54195579
** xCreate(), bPurgeable, is true if the cache being created will
54205580
** be used to cache database pages of a file stored on disk, or
5421
-** false if it is used for an in-memory database. ^The cache implementation
5581
+** false if it is used for an in-memory database. The cache implementation
54225582
** does not have to do anything special based with the value of bPurgeable;
54235583
** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
54245584
** never invoke xUnpin() except to deliberately delete a page.
5425
-** ^In other words, a cache created with bPurgeable set to false will
5585
+** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
5586
+** false will always have the "discard" flag set to true.
5587
+** ^Hence, a cache created with bPurgeable false will
54265588
** never contain any unpinned pages.
54275589
**
54285590
** ^(The xCachesize() method may be called at any time by SQLite to set the
54295591
** suggested maximum cache-size (number of pages stored by) the cache
54305592
** instance passed as the first argument. This is the value configured using
5431
-** the SQLite "[PRAGMA cache_size]" command.)^ ^As with the bPurgeable
5593
+** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
54325594
** parameter, the implementation is not required to do anything with this
54335595
** value; it is advisory only.
54345596
**
5435
-** ^The xPagecount() method should return the number of pages currently
5436
-** stored in the cache.
5597
+** The xPagecount() method must return the number of pages currently
5598
+** stored in the cache, both pinned and unpinned.
54375599
**
5438
-** ^The xFetch() method is used to fetch a page and return a pointer to it.
5439
-** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5440
-** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5441
-** mimimum key value is 1. After it has been retrieved using xFetch, the page
5600
+** The xFetch() method locates a page in the cache and returns a pointer to
5601
+** the page, or a NULL pointer.
5602
+** A "page", in this context, means a buffer of szPage bytes aligned at an
5603
+** 8-byte boundary. The page to be fetched is determined by the key. ^The
5604
+** mimimum key value is 1. After it has been retrieved using xFetch, the page
54425605
** is considered to be "pinned".
54435606
**
5444
-** ^If the requested page is already in the page cache, then the page cache
5607
+** If the requested page is already in the page cache, then the page cache
54455608
** implementation must return a pointer to the page buffer with its content
5446
-** intact. ^(If the requested page is not already in the cache, then the
5447
-** behavior of the cache implementation is determined by the value of the
5448
-** createFlag parameter passed to xFetch, according to the following table:
5609
+** intact. If the requested page is not already in the cache, then the
5610
+** behavior of the cache implementation should use the value of the createFlag
5611
+** parameter to help it determined what action to take:
54495612
**
54505613
** <table border=1 width=85% align=center>
54515614
** <tr><th> createFlag <th> Behaviour when page is not already in cache
54525615
** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
54535616
** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
54545617
** Otherwise return NULL.
54555618
** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
54565619
** NULL if allocating a new page is effectively impossible.
5457
-** </table>)^
5620
+** </table>
54585621
**
5459
-** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If
5460
-** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5622
+** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
5623
+** will only use a createFlag of 2 after a prior call with a createFlag of 1
5624
+** failed.)^ In between the to xFetch() calls, SQLite may
54615625
** attempt to unpin one or more cache pages by spilling the content of
5462
-** pinned pages to disk and synching the operating system disk cache. After
5463
-** attempting to unpin pages, the xFetch() method will be invoked again with
5464
-** a createFlag of 2.
5626
+** pinned pages to disk and synching the operating system disk cache.
54655627
**
54665628
** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5467
-** as its second argument. ^(If the third parameter, discard, is non-zero,
5468
-** then the page should be evicted from the cache. In this case SQLite
5469
-** assumes that the next time the page is retrieved from the cache using
5470
-** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5471
-** zero, then the page is considered to be unpinned. ^The cache implementation
5629
+** as its second argument. If the third parameter, discard, is non-zero,
5630
+** then the page must be evicted from the cache.
5631
+** ^If the discard parameter is
5632
+** zero, then the page may be discarded or retained at the discretion of
5633
+** page cache implementation. ^The page cache implementation
54725634
** may choose to evict unpinned pages at any time.
54735635
**
5474
-** ^(The cache is not required to perform any reference counting. A single
5636
+** The cache must not perform any reference counting. A single
54755637
** call to xUnpin() unpins the page regardless of the number of prior calls
5476
-** to xFetch().)^
5638
+** to xFetch().
54775639
**
5478
-** ^The xRekey() method is used to change the key value associated with the
5479
-** page passed as the second argument from oldKey to newKey. ^If the cache
5480
-** previously contains an entry associated with newKey, it should be
5640
+** The xRekey() method is used to change the key value associated with the
5641
+** page passed as the second argument. If the cache
5642
+** previously contains an entry associated with newKey, it must be
54815643
** discarded. ^Any prior cache entry associated with newKey is guaranteed not
54825644
** to be pinned.
54835645
**
5484
-** ^When SQLite calls the xTruncate() method, the cache must discard all
5646
+** When SQLite calls the xTruncate() method, the cache must discard all
54855647
** existing cache entries with page numbers (keys) greater than or equal
5486
-** to the value of the iLimit parameter passed to xTruncate(). ^If any
5648
+** to the value of the iLimit parameter passed to xTruncate(). If any
54875649
** of these pages are pinned, they are implicitly unpinned, meaning that
54885650
** they can be safely discarded.
54895651
**
54905652
** ^The xDestroy() method is used to delete a cache allocated by xCreate().
54915653
** All resources associated with the specified cache should be freed. ^After
@@ -5959,5 +6121,61 @@
59596121
#ifdef __cplusplus
59606122
} /* End of the 'extern "C"' block */
59616123
#endif
59626124
#endif
59636125
6126
+/*
6127
+** 2010 August 30
6128
+**
6129
+** The author disclaims copyright to this source code. In place of
6130
+** a legal notice, here is a blessing:
6131
+**
6132
+** May you do good and not evil.
6133
+** May you find forgiveness for yourself and forgive others.
6134
+** May you share freely, never taking more than you give.
6135
+**
6136
+*************************************************************************
6137
+*/
6138
+
6139
+#ifndef _SQLITE3RTREE_H_
6140
+#define _SQLITE3RTREE_H_
6141
+
6142
+
6143
+#ifdef __cplusplus
6144
+extern "C" {
6145
+#endif
6146
+
6147
+typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6148
+
6149
+/*
6150
+** Register a geometry callback named zGeom that can be used as part of an
6151
+** R-Tree geometry query as follows:
6152
+**
6153
+** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6154
+*/
6155
+SQLITE_API int sqlite3_rtree_geometry_callback(
6156
+ sqlite3 *db,
6157
+ const char *zGeom,
6158
+ int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6159
+ void *pContext
6160
+);
6161
+
6162
+
6163
+/*
6164
+** A pointer to a structure of the following type is passed as the first
6165
+** argument to callbacks registered using rtree_geometry_callback().
6166
+*/
6167
+struct sqlite3_rtree_geometry {
6168
+ void *pContext; /* Copy of pContext passed to s_r_g_c() */
6169
+ int nParam; /* Size of array aParam[] */
6170
+ double *aParam; /* Parameters passed to SQL geom function */
6171
+ void *pUser; /* Callback implementation user data */
6172
+ void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
6173
+};
6174
+
6175
+
6176
+#ifdef __cplusplus
6177
+} /* end of the 'extern "C"' block */
6178
+#endif
6179
+
6180
+#endif /* ifndef _SQLITE3RTREE_H_ */
6181
+
59646182
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -105,13 +105,13 @@
105 **
106 ** See also: [sqlite3_libversion()],
107 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108 ** [sqlite_version()] and [sqlite_source_id()].
109 */
110 #define SQLITE_VERSION "3.7.2"
111 #define SQLITE_VERSION_NUMBER 3007002
112 #define SQLITE_SOURCE_ID "2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3"
113
114 /*
115 ** CAPI3REF: Run-Time Library Version Numbers
116 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
117 **
@@ -755,19 +755,23 @@
755 ** object once the object has been registered.
756 **
757 ** The zName field holds the name of the VFS module. The name must
758 ** be unique across all VFS modules.
759 **
760 ** SQLite will guarantee that the zFilename parameter to xOpen
761 ** is either a NULL pointer or string obtained
762 ** from xFullPathname(). SQLite further guarantees that
 
 
 
 
763 ** the string will be valid and unchanged until xClose() is
764 ** called. Because of the previous sentence,
765 ** the [sqlite3_file] can safely store a pointer to the
766 ** filename if it needs to remember the filename for some reason.
767 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
768 ** must invent its own temporary name for the file. Whenever the
769 ** xFilename parameter is NULL it will also be the case that the
770 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
771 **
772 ** The flags argument to xOpen() includes all bits set in
773 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -774,11 +778,11 @@
774 ** or [sqlite3_open16()] is used, then flags includes at least
775 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
776 ** If xOpen() opens a file read-only then it sets *pOutFlags to
777 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
778 **
779 ** SQLite will also add one of the following flags to the xOpen()
780 ** call, depending on the object being opened:
781 **
782 ** <ul>
783 ** <li> [SQLITE_OPEN_MAIN_DB]
784 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -785,11 +789,12 @@
785 ** <li> [SQLITE_OPEN_TEMP_DB]
786 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
787 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
788 ** <li> [SQLITE_OPEN_SUBJOURNAL]
789 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
790 ** </ul>
 
791 **
792 ** The file I/O implementation can use the object type flags to
793 ** change the way it deals with files. For example, an application
794 ** that does not care about crash recovery or rollback might make
795 ** the open of a journal file a no-op. Writes to this journal would
@@ -804,39 +809,40 @@
804 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
805 ** <li> [SQLITE_OPEN_EXCLUSIVE]
806 ** </ul>
807 **
808 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
809 ** deleted when it is closed. The [SQLITE_OPEN_DELETEONCLOSE]
810 ** will be set for TEMP databases, journals and for subjournals.
 
811 **
812 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
813 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
814 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
815 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
816 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
817 ** be created, and that it is an error if it already exists.
818 ** It is <i>not</i> used to indicate the file should be opened
819 ** for exclusive access.
820 **
821 ** At least szOsFile bytes of memory are allocated by SQLite
822 ** to hold the [sqlite3_file] structure passed as the third
823 ** argument to xOpen. The xOpen method does not have to
824 ** allocate the structure; it should just fill it in. Note that
825 ** the xOpen method must set the sqlite3_file.pMethods to either
826 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
827 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
828 ** element will be valid after xOpen returns regardless of the success
829 ** or failure of the xOpen call.
830 **
831 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
832 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
833 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
834 ** to test whether a file is at least readable. The file can be a
835 ** directory.
836 **
837 ** SQLite will always allocate at least mxPathname+1 bytes for the
838 ** output buffer xFullPathname. The exact size of the output buffer
839 ** is also passed as a parameter to both methods. If the output buffer
840 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
841 ** handled as a fatal error by SQLite, vfs implementations should endeavor
842 ** to prevent this by setting mxPathname to a sufficiently large value.
@@ -846,14 +852,14 @@
846 ** included in the VFS structure for completeness.
847 ** The xRandomness() function attempts to return nBytes bytes
848 ** of good-quality randomness into zOut. The return value is
849 ** the actual number of bytes of randomness obtained.
850 ** The xSleep() method causes the calling thread to sleep for at
851 ** least the number of microseconds given. The xCurrentTime()
852 ** method returns a Julian Day Number for the current date and time as
853 ** a floating point value.
854 ** The xCurrentTimeInt64() method returns, as an integer, the Julian
855 ** Day Number multipled by 86400000 (the number of milliseconds in
856 ** a 24-hour day).
857 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
858 ** date and time if that method is available (if iVersion is 2 or
859 ** greater and the function pointer is not NULL) and will fall back
@@ -1246,11 +1252,11 @@
1246 ** statistics. ^(When memory allocation statistics are disabled, the
1247 ** following SQLite interfaces become non-operational:
1248 ** <ul>
1249 ** <li> [sqlite3_memory_used()]
1250 ** <li> [sqlite3_memory_highwater()]
1251 ** <li> [sqlite3_soft_heap_limit()]
1252 ** <li> [sqlite3_status()]
1253 ** </ul>)^
1254 ** ^Memory allocation statistics are enabled by default unless SQLite is
1255 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1256 ** allocation statistics are disabled by default.
@@ -1260,19 +1266,18 @@
1260 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1261 ** scratch memory. There are three arguments: A pointer an 8-byte
1262 ** aligned memory buffer from which the scrach allocations will be
1263 ** drawn, the size of each scratch allocation (sz),
1264 ** and the maximum number of scratch allocations (N). The sz
1265 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1266 ** larger than the actual scratch space required due to internal overhead.
1267 ** The first argument must be a pointer to an 8-byte aligned buffer
1268 ** of at least sz*N bytes of memory.
1269 ** ^SQLite will use no more than one scratch buffer per thread. So
1270 ** N should be set to the expected maximum number of threads. ^SQLite will
1271 ** never require a scratch buffer that is more than 6 times the database
1272 ** page size. ^If SQLite needs needs additional scratch memory beyond
1273 ** what is provided by this configuration option, then
1274 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1275 **
1276 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1277 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1278 ** the database page cache with the default page cache implemenation.
@@ -1288,12 +1293,11 @@
1288 ** argument should point to an allocation of at least sz*N bytes of memory.
1289 ** ^SQLite will use the memory provided by the first argument to satisfy its
1290 ** memory needs for the first N pages that it adds to cache. ^If additional
1291 ** page cache memory is needed beyond what is provided by this option, then
1292 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1293 ** ^The implementation might use one or more of the N buffers to hold
1294 ** memory accounting information. The pointer in the first argument must
1295 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1296 ** will be undefined.</dd>
1297 **
1298 ** <dt>SQLITE_CONFIG_HEAP</dt>
1299 ** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1418,12 +1422,18 @@
1418 ** size of each lookaside buffer slot. ^The third argument is the number of
1419 ** slots. The size of the buffer in the first argument must be greater than
1420 ** or equal to the product of the second and third arguments. The buffer
1421 ** must be aligned to an 8-byte boundary. ^If the second argument to
1422 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1423 ** rounded down to the next smaller
1424 ** multiple of 8. See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
 
 
 
 
 
 
1425 **
1426 ** </dl>
1427 */
1428 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1429
@@ -1723,10 +1733,13 @@
1723 */
1724 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
1725
1726 /*
1727 ** CAPI3REF: Convenience Routines For Running Queries
 
 
 
1728 **
1729 ** Definition: A <b>result table</b> is memory data structure created by the
1730 ** [sqlite3_get_table()] interface. A result table records the
1731 ** complete query results from one or more queries.
1732 **
@@ -1744,11 +1757,11 @@
1744 **
1745 ** A result table might consist of one or more memory allocations.
1746 ** It is not safe to pass a result table directly to [sqlite3_free()].
1747 ** A result table should be deallocated using [sqlite3_free_table()].
1748 **
1749 ** As an example of the result table format, suppose a query result
1750 ** is as follows:
1751 **
1752 ** <blockquote><pre>
1753 ** Name | Age
1754 ** -----------------------
@@ -1768,31 +1781,31 @@
1768 ** azResult&#91;3] = "43";
1769 ** azResult&#91;4] = "Bob";
1770 ** azResult&#91;5] = "28";
1771 ** azResult&#91;6] = "Cindy";
1772 ** azResult&#91;7] = "21";
1773 ** </pre></blockquote>
1774 **
1775 ** ^The sqlite3_get_table() function evaluates one or more
1776 ** semicolon-separated SQL statements in the zero-terminated UTF-8
1777 ** string of its 2nd parameter and returns a result table to the
1778 ** pointer given in its 3rd parameter.
1779 **
1780 ** After the application has finished with the result from sqlite3_get_table(),
1781 ** it should pass the result table pointer to sqlite3_free_table() in order to
1782 ** release the memory that was malloced. Because of the way the
1783 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
1784 ** function must not try to call [sqlite3_free()] directly. Only
1785 ** [sqlite3_free_table()] is able to release the memory properly and safely.
1786 **
1787 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
1788 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
1789 ** to any internal data structures of SQLite. It uses only the public
1790 ** interface defined here. As a consequence, errors that occur in the
1791 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
1792 ** reflected in subsequent calls to [sqlite3_errcode()] or
1793 ** [sqlite3_errmsg()].)^
1794 */
1795 SQLITE_API int sqlite3_get_table(
1796 sqlite3 *db, /* An open database */
1797 const char *zSql, /* SQL to be evaluated */
1798 char ***pazResult, /* Results of the query */
@@ -1940,11 +1953,13 @@
1940 ** by sqlite3_realloc() and the prior allocation is freed.
1941 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
1942 ** is not freed.
1943 **
1944 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
1945 ** is always aligned to at least an 8 byte boundary.
 
 
1946 **
1947 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
1948 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
1949 ** implementation of these routines to be omitted. That capability
1950 ** is no longer provided. Only built-in memory allocators can be used.
@@ -2198,21 +2213,32 @@
2198 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2199
2200 /*
2201 ** CAPI3REF: Query Progress Callbacks
2202 **
2203 ** ^This routine configures a callback function - the
2204 ** progress callback - that is invoked periodically during long
2205 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2206 ** [sqlite3_get_table()]. An example use for this
2207 ** interface is to keep a GUI updated during a large query.
 
 
 
 
 
 
 
 
 
 
 
2208 **
2209 ** ^If the progress callback returns non-zero, the operation is
2210 ** interrupted. This feature can be used to implement a
2211 ** "Cancel" button on a GUI progress dialog box.
2212 **
2213 ** The progress handler must not do anything that will modify
2214 ** the database connection that invoked the progress handler.
2215 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2216 ** database connections for the meaning of "modify" in this paragraph.
2217 **
2218 */
@@ -2267,11 +2293,11 @@
2267 ** </dl>
2268 **
2269 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2270 ** combinations shown above or one of the combinations shown above combined
2271 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2272 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2273 ** then the behavior is undefined.
2274 **
2275 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2276 ** opens in the multi-thread [threading mode] as long as the single-thread
2277 ** mode has not been set at compile-time or start-time. ^If the
@@ -2392,21 +2418,26 @@
2392 ** ^(This interface allows the size of various constructs to be limited
2393 ** on a connection by connection basis. The first parameter is the
2394 ** [database connection] whose limit is to be set or queried. The
2395 ** second parameter is one of the [limit categories] that define a
2396 ** class of constructs to be size limited. The third parameter is the
2397 ** new limit for that construct. The function returns the old limit.)^
2398 **
2399 ** ^If the new limit is a negative number, the limit is unchanged.
2400 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2401 ** [limits | hard upper bound]
2402 ** set by a compile-time C preprocessor macro named
2403 ** [limits | SQLITE_MAX_XYZ].
2404 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2405 ** ^Attempts to increase a limit above its hard upper bound are
2406 ** silently truncated to the hard upper bound.
2407 **
 
 
 
 
 
2408 ** Run-time limits are intended for use in applications that manage
2409 ** both their own internal database and also databases that are controlled
2410 ** by untrusted external sources. An example application might be a
2411 ** web browser that has its own databases for storing history and
2412 ** separate databases controlled by JavaScript applications downloaded
@@ -2431,11 +2462,11 @@
2431 ** The synopsis of the meanings of the various limits is shown below.
2432 ** Additional information is available at [limits | Limits in SQLite].
2433 **
2434 ** <dl>
2435 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2436 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2437 **
2438 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2439 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2440 **
2441 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2449,11 +2480,13 @@
2449 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2450 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2451 **
2452 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2453 ** <dd>The maximum number of instructions in a virtual machine program
2454 ** used to implement an SQL statement.</dd>)^
 
 
2455 **
2456 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2457 ** <dd>The maximum number of arguments on a function.</dd>)^
2458 **
2459 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2462,12 +2495,11 @@
2462 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2463 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2464 ** [GLOB] operators.</dd>)^
2465 **
2466 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2467 ** <dd>The maximum number of variables in an SQL statement that can
2468 ** be bound.</dd>)^
2469 **
2470 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2471 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2472 ** </dl>
2473 */
@@ -2535,16 +2567,11 @@
2535 **
2536 ** <ol>
2537 ** <li>
2538 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2539 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2540 ** statement and try to run it again. ^If the schema has changed in
2541 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2542 ** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is
2543 ** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the
2544 ** error go away. Note: use [sqlite3_errmsg()] to find the text
2545 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
2546 ** </li>
2547 **
2548 ** <li>
2549 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2550 ** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -2553,15 +2580,20 @@
2553 ** in order to find the underlying cause of the problem. With the "v2" prepare
2554 ** interfaces, the underlying reason for the error is returned immediately.
2555 ** </li>
2556 **
2557 ** <li>
2558 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
2559 ** change the query plan for a statement, then the statement may be
2560 ** automatically recompiled (as if there had been a schema change) on the first
2561 ** [sqlite3_step()] call following any change to the
2562 ** [sqlite3_bind_text | bindings] of the [parameter].
 
 
 
 
 
2563 ** </li>
2564 ** </ol>
2565 */
2566 SQLITE_API int sqlite3_prepare(
2567 sqlite3 *db, /* Database handle */
@@ -2624,11 +2656,11 @@
2624 ** or if SQLite is run in one of reduced mutex modes
2625 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
2626 ** then there is no distinction between protected and unprotected
2627 ** sqlite3_value objects and they can be used interchangeably. However,
2628 ** for maximum code portability it is recommended that applications
2629 ** still make the distinction between between protected and unprotected
2630 ** sqlite3_value objects even when not strictly required.
2631 **
2632 ** ^The sqlite3_value objects that are passed as parameters into the
2633 ** implementation of [application-defined SQL functions] are protected.
2634 ** ^The sqlite3_value object returned by
@@ -2819,10 +2851,12 @@
2819 ** CAPI3REF: Number Of Columns In A Result Set
2820 **
2821 ** ^Return the number of columns in the result set returned by the
2822 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
2823 ** statement that does not return data (for example an [UPDATE]).
 
 
2824 */
2825 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
2826
2827 /*
2828 ** CAPI3REF: Column Names In A Result Set
@@ -3009,12 +3043,18 @@
3009 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3010
3011 /*
3012 ** CAPI3REF: Number of columns in a result set
3013 **
3014 ** ^The sqlite3_data_count(P) the number of columns in the
3015 ** of the result set of [prepared statement] P.
 
 
 
 
 
 
3016 */
3017 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3018
3019 /*
3020 ** CAPI3REF: Fundamental Datatypes
@@ -3090,22 +3130,30 @@
3090 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3091 ** the string to UTF-8 and then returns the number of bytes.
3092 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3093 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3094 ** the number of bytes in that string.
3095 ** ^The value returned does not include the zero terminator at the end
3096 ** of the string. ^For clarity: the value returned is the number of
 
 
 
 
 
 
 
 
 
 
 
 
 
3097 ** bytes in the string, not the number of characters.
3098 **
3099 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3100 ** even empty strings, are always zero terminated. ^The return
3101 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3102 ** pointer, possibly even a NULL pointer.
3103 **
3104 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3105 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3106 ** ^The zero terminator is not included in this count.
3107 **
3108 ** ^The object returned by [sqlite3_column_value()] is an
3109 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3110 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3111 ** If the [unprotected sqlite3_value] object returned by
@@ -3146,14 +3194,14 @@
3146 ** and atof(). SQLite does not really use these functions. It has its
3147 ** own equivalent internal routines. The atoi() and atof() names are
3148 ** used in the table for brevity and because they are familiar to most
3149 ** C programmers.
3150 **
3151 ** ^Note that when type conversions occur, pointers returned by prior
3152 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3153 ** sqlite3_column_text16() may be invalidated.
3154 ** ^(Type conversions and pointer invalidations might occur
3155 ** in the following cases:
3156 **
3157 ** <ul>
3158 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3159 ** sqlite3_column_text16() is called. A zero-terminator might
@@ -3162,26 +3210,26 @@
3162 ** sqlite3_column_text16() is called. The content must be converted
3163 ** to UTF-16.</li>
3164 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3165 ** sqlite3_column_text() is called. The content must be converted
3166 ** to UTF-8.</li>
3167 ** </ul>)^
3168 **
3169 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3170 ** not invalidate a prior pointer, though of course the content of the buffer
3171 ** that the prior pointer points to will have been modified. Other kinds
3172 ** of conversion are done in place when it is possible, but sometimes they
3173 ** are not possible and in those cases prior pointers are invalidated.
3174 **
3175 ** ^(The safest and easiest to remember policy is to invoke these routines
3176 ** in one of the following ways:
3177 **
3178 ** <ul>
3179 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3180 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3181 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3182 ** </ul>)^
3183 **
3184 ** In other words, you should call sqlite3_column_text(),
3185 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3186 ** into the desired format, then invoke sqlite3_column_bytes() or
3187 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3215,21 +3263,30 @@
3215
3216 /*
3217 ** CAPI3REF: Destroy A Prepared Statement Object
3218 **
3219 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3220 ** ^If the statement was executed successfully or not executed at all, then
3221 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3222 ** [error code] or [extended error code] is returned.
 
 
3223 **
3224 ** ^This routine can be called at any point during the execution of the
3225 ** [prepared statement]. ^If the virtual machine has not
3226 ** completed execution when this routine is called, that is like
3227 ** encountering an error or an [sqlite3_interrupt | interrupt].
3228 ** ^Incomplete updates may be rolled back and transactions canceled,
3229 ** depending on the circumstances, and the
3230 ** [error code] returned will be [SQLITE_ABORT].
 
 
 
 
 
 
 
3231 */
3232 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3233
3234 /*
3235 ** CAPI3REF: Reset A Prepared Statement Object
@@ -3261,40 +3318,42 @@
3261 ** CAPI3REF: Create Or Redefine SQL Functions
3262 ** KEYWORDS: {function creation routines}
3263 ** KEYWORDS: {application-defined SQL function}
3264 ** KEYWORDS: {application-defined SQL functions}
3265 **
3266 ** ^These two functions (collectively known as "function creation routines")
3267 ** are used to add SQL functions or aggregates or to redefine the behavior
3268 ** of existing SQL functions or aggregates. The only difference between the
3269 ** two is that the second parameter, the name of the (scalar) function or
3270 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3271 ** for sqlite3_create_function16().
 
3272 **
3273 ** ^The first parameter is the [database connection] to which the SQL
3274 ** function is to be added. ^If an application uses more than one database
3275 ** connection then application-defined SQL functions must be added
3276 ** to each database connection separately.
3277 **
3278 ** The second parameter is the name of the SQL function to be created or
3279 ** redefined. ^The length of the name is limited to 255 bytes, exclusive of
3280 ** the zero-terminator. Note that the name length limit is in bytes, not
3281 ** characters. ^Any attempt to create a function with a longer name
3282 ** will result in [SQLITE_ERROR] being returned.
 
3283 **
3284 ** ^The third parameter (nArg)
3285 ** is the number of arguments that the SQL function or
3286 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3287 ** aggregate may take any number of arguments between 0 and the limit
3288 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
3289 ** parameter is less than -1 or greater than 127 then the behavior is
3290 ** undefined.
3291 **
3292 ** The fourth parameter, eTextRep, specifies what
3293 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3294 ** its parameters. Any SQL function implementation should be able to work
3295 ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3296 ** more efficient with one encoding than another. ^An application may
3297 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3298 ** times with the same function but with different values of eTextRep.
3299 ** ^When multiple implementations of the same function are available, SQLite
3300 ** will pick the one that involves the least amount of data conversion.
@@ -3302,17 +3361,25 @@
3302 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3303 **
3304 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
3305 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3306 **
3307 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3308 ** pointers to C-language functions that implement the SQL function or
3309 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3310 ** callback only; NULL pointers should be passed as the xStep and xFinal
3311 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3312 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3313 ** SQL function or aggregate, pass NULL for all three function callbacks.
 
 
 
 
 
 
 
 
3314 **
3315 ** ^It is permitted to register multiple implementations of the same
3316 ** functions with the same name but with either differing numbers of
3317 ** arguments or differing preferred text encodings. ^SQLite will use
3318 ** the implementation that most closely matches the way in which the
@@ -3324,15 +3391,10 @@
3324 ** ^A function where the encoding difference is between UTF16le and UTF16be
3325 ** is a closer match than a function where the encoding difference is
3326 ** between UTF8 and UTF16.
3327 **
3328 ** ^Built-in functions may be overloaded by new application-defined functions.
3329 ** ^The first application-defined function with a given name overrides all
3330 ** built-in functions in the same [database connection] with the same name.
3331 ** ^Subsequent application-defined functions of the same name only override
3332 ** prior application-defined functions that are an exact match for the
3333 ** number of parameters and preferred encoding.
3334 **
3335 ** ^An application-defined function is permitted to call other
3336 ** SQLite interfaces. However, such calls must not
3337 ** close the database connection nor finalize or reset the prepared
3338 ** statement in which the function is running.
@@ -3354,10 +3416,21 @@
3354 int eTextRep,
3355 void *pApp,
3356 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3357 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3358 void (*xFinal)(sqlite3_context*)
 
 
 
 
 
 
 
 
 
 
 
3359 );
3360
3361 /*
3362 ** CAPI3REF: Text Encodings
3363 **
@@ -3701,73 +3774,97 @@
3701 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
3702
3703 /*
3704 ** CAPI3REF: Define New Collating Sequences
3705 **
3706 ** These functions are used to add new collation sequences to the
3707 ** [database connection] specified as the first argument.
3708 **
3709 ** ^The name of the new collation sequence is specified as a UTF-8 string
3710 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3711 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
3712 ** the name is passed as the second function argument.
3713 **
3714 ** ^The third argument may be one of the constants [SQLITE_UTF8],
3715 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
3716 ** routine expects to be passed pointers to strings encoded using UTF-8,
3717 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
3718 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
3719 ** expects pointers to be UTF-16 strings in the native byte order, or the
3720 ** argument can be [SQLITE_UTF16_ALIGNED] if the
3721 ** the routine expects pointers to 16-bit word aligned strings
3722 ** of UTF-16 in the native byte order.
3723 **
3724 ** A pointer to the user supplied routine must be passed as the fifth
3725 ** argument. ^If it is NULL, this is the same as deleting the collation
3726 ** sequence (so that SQLite cannot call it any more).
3727 ** ^Each time the application supplied function is invoked, it is passed
3728 ** as its first parameter a copy of the void* passed as the fourth argument
3729 ** to sqlite3_create_collation() or sqlite3_create_collation16().
3730 **
3731 ** ^The remaining arguments to the application-supplied routine are two strings,
3732 ** each represented by a (length, data) pair and encoded in the encoding
3733 ** that was passed as the third argument when the collation sequence was
3734 ** registered. The application defined collation routine should
3735 ** return negative, zero or positive if the first string is less than,
3736 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3737 **
3738 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
3739 ** except that it takes an extra argument which is a destructor for
3740 ** the collation. ^The destructor is called when the collation is
3741 ** destroyed and is passed a copy of the fourth parameter void* pointer
3742 ** of the sqlite3_create_collation_v2().
3743 ** ^Collations are destroyed when they are overridden by later calls to the
3744 ** collation creation functions or when the [database connection] is closed
3745 ** using [sqlite3_close()].
3746 **
3747 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
3748 */
3749 SQLITE_API int sqlite3_create_collation(
3750 sqlite3*,
3751 const char *zName,
3752 int eTextRep,
3753 void*,
3754 int(*xCompare)(void*,int,const void*,int,const void*)
3755 );
3756 SQLITE_API int sqlite3_create_collation_v2(
3757 sqlite3*,
3758 const char *zName,
3759 int eTextRep,
3760 void*,
3761 int(*xCompare)(void*,int,const void*,int,const void*),
3762 void(*xDestroy)(void*)
3763 );
3764 SQLITE_API int sqlite3_create_collation16(
3765 sqlite3*,
3766 const void *zName,
3767 int eTextRep,
3768 void*,
3769 int(*xCompare)(void*,int,const void*,int,const void*)
3770 );
3771
3772 /*
3773 ** CAPI3REF: Collation Needed Callbacks
@@ -3852,20 +3949,23 @@
3852 #endif
3853
3854 /*
3855 ** CAPI3REF: Suspend Execution For A Short Time
3856 **
3857 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
3858 ** for at least a number of milliseconds specified in its parameter.
3859 **
3860 ** ^If the operating system does not support sleep requests with
3861 ** millisecond time resolution, then the time will be rounded up to
3862 ** the nearest second. ^The number of milliseconds of sleep actually
3863 ** requested from the operating system is returned.
3864 **
3865 ** ^SQLite implements this interface by calling the xSleep()
3866 ** method of the default [sqlite3_vfs] object.
 
 
 
3867 */
3868 SQLITE_API int sqlite3_sleep(int);
3869
3870 /*
3871 ** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4083,44 +4183,77 @@
4083 ** of heap memory by deallocating non-essential memory allocations
4084 ** held by the database library. Memory used to cache database
4085 ** pages to improve performance is an example of non-essential memory.
4086 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4087 ** which might be more or less than the amount requested.
 
 
4088 */
4089 SQLITE_API int sqlite3_release_memory(int);
4090
4091 /*
4092 ** CAPI3REF: Impose A Limit On Heap Size
4093 **
4094 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4095 ** on the amount of heap memory that may be allocated by SQLite.
4096 ** ^If an internal allocation is requested that would exceed the
4097 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4098 ** more times to free up some space before the allocation is performed.
4099 **
4100 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4101 ** cannot free sufficient memory to prevent the limit from being exceeded,
4102 ** the memory is allocated anyway and the current operation proceeds.
4103 **
4104 ** ^A negative or zero value for N means that there is no soft heap limit and
4105 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4106 ** ^The default value for the soft heap limit is zero.
4107 **
4108 ** ^(SQLite makes a best effort to honor the soft heap limit.
4109 ** But if the soft heap limit cannot be honored, execution will
4110 ** continue without error or notification.)^ This is why the limit is
4111 ** called a "soft" limit. It is advisory only.
4112 **
4113 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4114 ** allocated by a single thread - the same thread in which this routine
4115 ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is
4116 ** applied to all threads. The value specified for the soft heap limit
4117 ** is an upper bound on the total memory allocation for all threads. In
4118 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4119 ** individual threads.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4120 */
4121 SQLITE_API void sqlite3_soft_heap_limit(int);
 
4122
4123 /*
4124 ** CAPI3REF: Extract Metadata About A Column Of A Table
4125 **
4126 ** ^This routine returns metadata about a specific column of a specific
@@ -4240,38 +4373,51 @@
4240 ** it back off again.
4241 */
4242 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4243
4244 /*
4245 ** CAPI3REF: Automatically Load An Extensions
4246 **
4247 ** ^This API can be invoked at program startup in order to register
4248 ** one or more statically linked extensions that will be available
4249 ** to all new [database connections].
4250 **
4251 ** ^(This routine stores a pointer to the extension entry point
4252 ** in an array that is obtained from [sqlite3_malloc()]. That memory
4253 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4254 **
4255 ** ^This function registers an extension entry point that is
4256 ** automatically invoked whenever a new [database connection]
4257 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4258 ** or [sqlite3_open_v2()].
4259 ** ^Duplicate extensions are detected so calling this routine
4260 ** multiple times with the same extension is harmless.
4261 ** ^Automatic extensions apply across all threads.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4262 */
4263 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4264
4265 /*
4266 ** CAPI3REF: Reset Automatic Extension Loading
4267 **
4268 ** ^(This function disables all previously registered automatic
4269 ** extensions. It undoes the effect of all prior
4270 ** [sqlite3_auto_extension()] calls.)^
4271 **
4272 ** ^This function disables automatic extensions in all threads.
4273 */
4274 SQLITE_API void sqlite3_reset_auto_extension(void);
4275
4276 /*
4277 ** The interface to the virtual-table mechanism is currently considered
@@ -4906,11 +5052,11 @@
4906 ** output variable when querying the system for the current mutex
4907 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
4908 **
4909 ** ^The xMutexInit method defined by this structure is invoked as
4910 ** part of system initialization by the sqlite3_initialize() function.
4911 ** ^The xMutexInit routine is calle by SQLite exactly once for each
4912 ** effective call to [sqlite3_initialize()].
4913 **
4914 ** ^The xMutexEnd method defined by this structure is invoked as
4915 ** part of system shutdown by the sqlite3_shutdown() function. The
4916 ** implementation of this method is expected to release all outstanding
@@ -5103,11 +5249,12 @@
5103 #define SQLITE_TESTCTRL_ALWAYS 13
5104 #define SQLITE_TESTCTRL_RESERVE 14
5105 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
5106 #define SQLITE_TESTCTRL_ISKEYWORD 16
5107 #define SQLITE_TESTCTRL_PGHDRSZ 17
5108 #define SQLITE_TESTCTRL_LAST 17
 
5109
5110 /*
5111 ** CAPI3REF: SQLite Runtime Status
5112 **
5113 ** ^This interface is used to retrieve runtime status information
@@ -5122,11 +5269,11 @@
5122 ** value. For those parameters
5123 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5124 ** ^(Other parameters record only the highwater mark and not the current
5125 ** value. For these latter parameters nothing is written into *pCurrent.)^
5126 **
5127 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5128 ** non-zero [error code] on failure.
5129 **
5130 ** This routine is threadsafe but is not atomic. This routine can be
5131 ** called while other threads are running the same or different SQLite
5132 ** interfaces. However the values returned in *pCurrent and
@@ -5172,11 +5319,11 @@
5172 ** [SQLITE_CONFIG_PAGECACHE]. The
5173 ** value returned is in pages, not in bytes.</dd>)^
5174 **
5175 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5176 ** <dd>This parameter returns the number of bytes of page cache
5177 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5178 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
5179 ** returned value includes allocations that overflowed because they
5180 ** where too large (they were larger than the "sz" parameter to
5181 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5182 ** no space was left in the page cache.</dd>)^
@@ -5195,11 +5342,11 @@
5195 ** outstanding at time, this parameter also reports the number of threads
5196 ** using scratch memory at the same time.</dd>)^
5197 **
5198 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5199 ** <dd>This parameter returns the number of bytes of scratch memory
5200 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5201 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
5202 ** returned include overflows because the requested allocation was too
5203 ** larger (that is, because the requested allocation was larger than the
5204 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5205 ** slots were available.
@@ -5243,10 +5390,13 @@
5243 **
5244 ** ^The current value of the requested parameter is written into *pCur
5245 ** and the highest instantaneous value is written into *pHiwtr. ^If
5246 ** the resetFlg is true, then the highest instantaneous value is
5247 ** reset back down to the current value.
 
 
 
5248 **
5249 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5250 */
5251 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5252
@@ -5370,122 +5520,134 @@
5370 ** CAPI3REF: Application Defined Page Cache.
5371 ** KEYWORDS: {page cache}
5372 **
5373 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5374 ** register an alternative page cache implementation by passing in an
5375 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5376 ** heap memory used by SQLite is used by the page cache to cache data read
5377 ** from, or ready to be written to, the database file. By implementing a
5378 ** custom page cache using this API, an application can control more
5379 ** precisely the amount of memory consumed by SQLite, the way in which
 
5380 ** that memory is allocated and released, and the policies used to
5381 ** determine exactly which parts of a database file are cached and for
5382 ** how long.
5383 **
 
 
 
 
5384 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5385 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
5386 ** the application may discard the parameter after the call to
5387 ** [sqlite3_config()] returns.)^
5388 **
5389 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
 
5390 ** (usually only once during the lifetime of the process). ^(The xInit()
5391 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5392 ** ^The xInit() method can set up up global structures and/or any mutexes
5393 ** required by the custom page cache implementation.
 
 
 
5394 **
5395 ** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5396 ** if the application invokes this API. It can be used to clean up
5397 ** any outstanding resources before process shutdown, if required.
 
5398 **
5399 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5400 ** the xInit method, so the xInit method need not be threadsafe. ^The
5401 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5402 ** not need to be threadsafe either. All other methods must be threadsafe
5403 ** in multithreaded applications.
5404 **
5405 ** ^SQLite will never invoke xInit() more than once without an intervening
5406 ** call to xShutdown().
5407 **
5408 ** ^The xCreate() method is used to construct a new cache instance. SQLite
5409 ** will typically create one cache instance for each open database file,
5410 ** though this is not guaranteed. ^The
5411 ** first parameter, szPage, is the size in bytes of the pages that must
5412 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
5413 ** will the page size of the database file that is to be cached plus an
5414 ** increment (here called "R") of about 100 or 200. ^SQLite will use the
5415 ** extra R bytes on each page to store metadata about the underlying
5416 ** database page on disk. The value of R depends
5417 ** on the SQLite version, the target platform, and how SQLite was compiled.
5418 ** ^R is constant for a particular build of SQLite. ^The second argument to
5419 ** xCreate(), bPurgeable, is true if the cache being created will
5420 ** be used to cache database pages of a file stored on disk, or
5421 ** false if it is used for an in-memory database. ^The cache implementation
5422 ** does not have to do anything special based with the value of bPurgeable;
5423 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
5424 ** never invoke xUnpin() except to deliberately delete a page.
5425 ** ^In other words, a cache created with bPurgeable set to false will
 
 
5426 ** never contain any unpinned pages.
5427 **
5428 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5429 ** suggested maximum cache-size (number of pages stored by) the cache
5430 ** instance passed as the first argument. This is the value configured using
5431 ** the SQLite "[PRAGMA cache_size]" command.)^ ^As with the bPurgeable
5432 ** parameter, the implementation is not required to do anything with this
5433 ** value; it is advisory only.
5434 **
5435 ** ^The xPagecount() method should return the number of pages currently
5436 ** stored in the cache.
5437 **
5438 ** ^The xFetch() method is used to fetch a page and return a pointer to it.
5439 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5440 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5441 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
 
5442 ** is considered to be "pinned".
5443 **
5444 ** ^If the requested page is already in the page cache, then the page cache
5445 ** implementation must return a pointer to the page buffer with its content
5446 ** intact. ^(If the requested page is not already in the cache, then the
5447 ** behavior of the cache implementation is determined by the value of the
5448 ** createFlag parameter passed to xFetch, according to the following table:
5449 **
5450 ** <table border=1 width=85% align=center>
5451 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5452 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
5453 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5454 ** Otherwise return NULL.
5455 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
5456 ** NULL if allocating a new page is effectively impossible.
5457 ** </table>)^
5458 **
5459 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1. If
5460 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
 
5461 ** attempt to unpin one or more cache pages by spilling the content of
5462 ** pinned pages to disk and synching the operating system disk cache. After
5463 ** attempting to unpin pages, the xFetch() method will be invoked again with
5464 ** a createFlag of 2.
5465 **
5466 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5467 ** as its second argument. ^(If the third parameter, discard, is non-zero,
5468 ** then the page should be evicted from the cache. In this case SQLite
5469 ** assumes that the next time the page is retrieved from the cache using
5470 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5471 ** zero, then the page is considered to be unpinned. ^The cache implementation
5472 ** may choose to evict unpinned pages at any time.
5473 **
5474 ** ^(The cache is not required to perform any reference counting. A single
5475 ** call to xUnpin() unpins the page regardless of the number of prior calls
5476 ** to xFetch().)^
5477 **
5478 ** ^The xRekey() method is used to change the key value associated with the
5479 ** page passed as the second argument from oldKey to newKey. ^If the cache
5480 ** previously contains an entry associated with newKey, it should be
5481 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5482 ** to be pinned.
5483 **
5484 ** ^When SQLite calls the xTruncate() method, the cache must discard all
5485 ** existing cache entries with page numbers (keys) greater than or equal
5486 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
5487 ** of these pages are pinned, they are implicitly unpinned, meaning that
5488 ** they can be safely discarded.
5489 **
5490 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5491 ** All resources associated with the specified cache should be freed. ^After
@@ -5959,5 +6121,61 @@
5959 #ifdef __cplusplus
5960 } /* End of the 'extern "C"' block */
5961 #endif
5962 #endif
5963
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5964
--- src/sqlite3.h
+++ src/sqlite3.h
@@ -105,13 +105,13 @@
105 **
106 ** See also: [sqlite3_libversion()],
107 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
108 ** [sqlite_version()] and [sqlite_source_id()].
109 */
110 #define SQLITE_VERSION "3.7.3"
111 #define SQLITE_VERSION_NUMBER 3007003
112 #define SQLITE_SOURCE_ID "2010-09-29 23:09:23 1ef0dc9328f47506cb2dcd142150e96cb4755216"
113
114 /*
115 ** CAPI3REF: Run-Time Library Version Numbers
116 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
117 **
@@ -755,19 +755,23 @@
755 ** object once the object has been registered.
756 **
757 ** The zName field holds the name of the VFS module. The name must
758 ** be unique across all VFS modules.
759 **
760 ** ^SQLite guarantees that the zFilename parameter to xOpen
761 ** is either a NULL pointer or string obtained
762 ** from xFullPathname() with an optional suffix added.
763 ** ^If a suffix is added to the zFilename parameter, it will
764 ** consist of a single "-" character followed by no more than
765 ** 10 alphanumeric and/or "-" characters.
766 ** ^SQLite further guarantees that
767 ** the string will be valid and unchanged until xClose() is
768 ** called. Because of the previous sentence,
769 ** the [sqlite3_file] can safely store a pointer to the
770 ** filename if it needs to remember the filename for some reason.
771 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
772 ** must invent its own temporary name for the file. ^Whenever the
773 ** xFilename parameter is NULL it will also be the case that the
774 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
775 **
776 ** The flags argument to xOpen() includes all bits set in
777 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
@@ -774,11 +778,11 @@
778 ** or [sqlite3_open16()] is used, then flags includes at least
779 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
780 ** If xOpen() opens a file read-only then it sets *pOutFlags to
781 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
782 **
783 ** ^(SQLite will also add one of the following flags to the xOpen()
784 ** call, depending on the object being opened:
785 **
786 ** <ul>
787 ** <li> [SQLITE_OPEN_MAIN_DB]
788 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
@@ -785,11 +789,12 @@
789 ** <li> [SQLITE_OPEN_TEMP_DB]
790 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
791 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
792 ** <li> [SQLITE_OPEN_SUBJOURNAL]
793 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
794 ** <li> [SQLITE_OPEN_WAL]
795 ** </ul>)^
796 **
797 ** The file I/O implementation can use the object type flags to
798 ** change the way it deals with files. For example, an application
799 ** that does not care about crash recovery or rollback might make
800 ** the open of a journal file a no-op. Writes to this journal would
@@ -804,39 +809,40 @@
809 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
810 ** <li> [SQLITE_OPEN_EXCLUSIVE]
811 ** </ul>
812 **
813 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
814 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
815 ** will be set for TEMP databases and their journals, transient
816 ** databases, and subjournals.
817 **
818 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
819 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
820 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
821 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
822 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
823 ** be created, and that it is an error if it already exists.
824 ** It is <i>not</i> used to indicate the file should be opened
825 ** for exclusive access.
826 **
827 ** ^At least szOsFile bytes of memory are allocated by SQLite
828 ** to hold the [sqlite3_file] structure passed as the third
829 ** argument to xOpen. The xOpen method does not have to
830 ** allocate the structure; it should just fill it in. Note that
831 ** the xOpen method must set the sqlite3_file.pMethods to either
832 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
833 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
834 ** element will be valid after xOpen returns regardless of the success
835 ** or failure of the xOpen call.
836 **
837 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
838 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
839 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
840 ** to test whether a file is at least readable. The file can be a
841 ** directory.
842 **
843 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
844 ** output buffer xFullPathname. The exact size of the output buffer
845 ** is also passed as a parameter to both methods. If the output buffer
846 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
847 ** handled as a fatal error by SQLite, vfs implementations should endeavor
848 ** to prevent this by setting mxPathname to a sufficiently large value.
@@ -846,14 +852,14 @@
852 ** included in the VFS structure for completeness.
853 ** The xRandomness() function attempts to return nBytes bytes
854 ** of good-quality randomness into zOut. The return value is
855 ** the actual number of bytes of randomness obtained.
856 ** The xSleep() method causes the calling thread to sleep for at
857 ** least the number of microseconds given. ^The xCurrentTime()
858 ** method returns a Julian Day Number for the current date and time as
859 ** a floating point value.
860 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
861 ** Day Number multipled by 86400000 (the number of milliseconds in
862 ** a 24-hour day).
863 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
864 ** date and time if that method is available (if iVersion is 2 or
865 ** greater and the function pointer is not NULL) and will fall back
@@ -1246,11 +1252,11 @@
1252 ** statistics. ^(When memory allocation statistics are disabled, the
1253 ** following SQLite interfaces become non-operational:
1254 ** <ul>
1255 ** <li> [sqlite3_memory_used()]
1256 ** <li> [sqlite3_memory_highwater()]
1257 ** <li> [sqlite3_soft_heap_limit64()]
1258 ** <li> [sqlite3_status()]
1259 ** </ul>)^
1260 ** ^Memory allocation statistics are enabled by default unless SQLite is
1261 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1262 ** allocation statistics are disabled by default.
@@ -1260,19 +1266,18 @@
1266 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1267 ** scratch memory. There are three arguments: A pointer an 8-byte
1268 ** aligned memory buffer from which the scrach allocations will be
1269 ** drawn, the size of each scratch allocation (sz),
1270 ** and the maximum number of scratch allocations (N). The sz
1271 ** argument must be a multiple of 16.
 
1272 ** The first argument must be a pointer to an 8-byte aligned buffer
1273 ** of at least sz*N bytes of memory.
1274 ** ^SQLite will use no more than two scratch buffers per thread. So
1275 ** N should be set to twice the expected maximum number of threads.
1276 ** ^SQLite will never require a scratch buffer that is more than 6
1277 ** times the database page size. ^If SQLite needs needs additional
1278 ** scratch memory beyond what is provided by this configuration option, then
1279 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1280 **
1281 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1282 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1283 ** the database page cache with the default page cache implemenation.
@@ -1288,12 +1293,11 @@
1293 ** argument should point to an allocation of at least sz*N bytes of memory.
1294 ** ^SQLite will use the memory provided by the first argument to satisfy its
1295 ** memory needs for the first N pages that it adds to cache. ^If additional
1296 ** page cache memory is needed beyond what is provided by this option, then
1297 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1298 ** The pointer in the first argument must
 
1299 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1300 ** will be undefined.</dd>
1301 **
1302 ** <dt>SQLITE_CONFIG_HEAP</dt>
1303 ** <dd> ^This option specifies a static memory buffer that SQLite will use
@@ -1418,12 +1422,18 @@
1422 ** size of each lookaside buffer slot. ^The third argument is the number of
1423 ** slots. The size of the buffer in the first argument must be greater than
1424 ** or equal to the product of the second and third arguments. The buffer
1425 ** must be aligned to an 8-byte boundary. ^If the second argument to
1426 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1427 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1428 ** configuration for a database connection can only be changed when that
1429 ** connection is not currently using lookaside memory, or in other words
1430 ** when the "current value" returned by
1431 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1432 ** Any attempt to change the lookaside memory configuration when lookaside
1433 ** memory is in use leaves the configuration unchanged and returns
1434 ** [SQLITE_BUSY].)^</dd>
1435 **
1436 ** </dl>
1437 */
1438 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1439
@@ -1723,10 +1733,13 @@
1733 */
1734 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
1735
1736 /*
1737 ** CAPI3REF: Convenience Routines For Running Queries
1738 **
1739 ** This is a legacy interface that is preserved for backwards compatibility.
1740 ** Use of this interface is not recommended.
1741 **
1742 ** Definition: A <b>result table</b> is memory data structure created by the
1743 ** [sqlite3_get_table()] interface. A result table records the
1744 ** complete query results from one or more queries.
1745 **
@@ -1744,11 +1757,11 @@
1757 **
1758 ** A result table might consist of one or more memory allocations.
1759 ** It is not safe to pass a result table directly to [sqlite3_free()].
1760 ** A result table should be deallocated using [sqlite3_free_table()].
1761 **
1762 ** ^(As an example of the result table format, suppose a query result
1763 ** is as follows:
1764 **
1765 ** <blockquote><pre>
1766 ** Name | Age
1767 ** -----------------------
@@ -1768,31 +1781,31 @@
1781 ** azResult&#91;3] = "43";
1782 ** azResult&#91;4] = "Bob";
1783 ** azResult&#91;5] = "28";
1784 ** azResult&#91;6] = "Cindy";
1785 ** azResult&#91;7] = "21";
1786 ** </pre></blockquote>)^
1787 **
1788 ** ^The sqlite3_get_table() function evaluates one or more
1789 ** semicolon-separated SQL statements in the zero-terminated UTF-8
1790 ** string of its 2nd parameter and returns a result table to the
1791 ** pointer given in its 3rd parameter.
1792 **
1793 ** After the application has finished with the result from sqlite3_get_table(),
1794 ** it must pass the result table pointer to sqlite3_free_table() in order to
1795 ** release the memory that was malloced. Because of the way the
1796 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
1797 ** function must not try to call [sqlite3_free()] directly. Only
1798 ** [sqlite3_free_table()] is able to release the memory properly and safely.
1799 **
1800 ** The sqlite3_get_table() interface is implemented as a wrapper around
1801 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
1802 ** to any internal data structures of SQLite. It uses only the public
1803 ** interface defined here. As a consequence, errors that occur in the
1804 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
1805 ** reflected in subsequent calls to [sqlite3_errcode()] or
1806 ** [sqlite3_errmsg()].
1807 */
1808 SQLITE_API int sqlite3_get_table(
1809 sqlite3 *db, /* An open database */
1810 const char *zSql, /* SQL to be evaluated */
1811 char ***pazResult, /* Results of the query */
@@ -1940,11 +1953,13 @@
1953 ** by sqlite3_realloc() and the prior allocation is freed.
1954 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
1955 ** is not freed.
1956 **
1957 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
1958 ** is always aligned to at least an 8 byte boundary, or to a
1959 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
1960 ** option is used.
1961 **
1962 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
1963 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
1964 ** implementation of these routines to be omitted. That capability
1965 ** is no longer provided. Only built-in memory allocators can be used.
@@ -2198,21 +2213,32 @@
2213 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2214
2215 /*
2216 ** CAPI3REF: Query Progress Callbacks
2217 **
2218 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2219 ** function X to be invoked periodically during long running calls to
2220 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2221 ** database connection D. An example use for this
2222 ** interface is to keep a GUI updated during a large query.
2223 **
2224 ** ^The parameter P is passed through as the only parameter to the
2225 ** callback function X. ^The parameter N is the number of
2226 ** [virtual machine instructions] that are evaluated between successive
2227 ** invocations of the callback X.
2228 **
2229 ** ^Only a single progress handler may be defined at one time per
2230 ** [database connection]; setting a new progress handler cancels the
2231 ** old one. ^Setting parameter X to NULL disables the progress handler.
2232 ** ^The progress handler is also disabled by setting N to a value less
2233 ** than 1.
2234 **
2235 ** ^If the progress callback returns non-zero, the operation is
2236 ** interrupted. This feature can be used to implement a
2237 ** "Cancel" button on a GUI progress dialog box.
2238 **
2239 ** The progress handler callback must not do anything that will modify
2240 ** the database connection that invoked the progress handler.
2241 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2242 ** database connections for the meaning of "modify" in this paragraph.
2243 **
2244 */
@@ -2267,11 +2293,11 @@
2293 ** </dl>
2294 **
2295 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2296 ** combinations shown above or one of the combinations shown above combined
2297 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2298 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2299 ** then the behavior is undefined.
2300 **
2301 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2302 ** opens in the multi-thread [threading mode] as long as the single-thread
2303 ** mode has not been set at compile-time or start-time. ^If the
@@ -2392,21 +2418,26 @@
2418 ** ^(This interface allows the size of various constructs to be limited
2419 ** on a connection by connection basis. The first parameter is the
2420 ** [database connection] whose limit is to be set or queried. The
2421 ** second parameter is one of the [limit categories] that define a
2422 ** class of constructs to be size limited. The third parameter is the
2423 ** new limit for that construct.)^
2424 **
2425 ** ^If the new limit is a negative number, the limit is unchanged.
2426 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
2427 ** [limits | hard upper bound]
2428 ** set at compile-time by a C preprocessor macro called
2429 ** [limits | SQLITE_MAX_<i>NAME</i>].
2430 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2431 ** ^Attempts to increase a limit above its hard upper bound are
2432 ** silently truncated to the hard upper bound.
2433 **
2434 ** ^Regardless of whether or not the limit was changed, the
2435 ** [sqlite3_limit()] interface returns the prior value of the limit.
2436 ** ^Hence, to find the current value of a limit without changing it,
2437 ** simply invoke this interface with the third parameter set to -1.
2438 **
2439 ** Run-time limits are intended for use in applications that manage
2440 ** both their own internal database and also databases that are controlled
2441 ** by untrusted external sources. An example application might be a
2442 ** web browser that has its own databases for storing history and
2443 ** separate databases controlled by JavaScript applications downloaded
@@ -2431,11 +2462,11 @@
2462 ** The synopsis of the meanings of the various limits is shown below.
2463 ** Additional information is available at [limits | Limits in SQLite].
2464 **
2465 ** <dl>
2466 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2467 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
2468 **
2469 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2470 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2471 **
2472 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
@@ -2449,11 +2480,13 @@
2480 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2481 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2482 **
2483 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2484 ** <dd>The maximum number of instructions in a virtual machine program
2485 ** used to implement an SQL statement. This limit is not currently
2486 ** enforced, though that might be added in some future release of
2487 ** SQLite.</dd>)^
2488 **
2489 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2490 ** <dd>The maximum number of arguments on a function.</dd>)^
2491 **
2492 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
@@ -2462,12 +2495,11 @@
2495 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2496 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2497 ** [GLOB] operators.</dd>)^
2498 **
2499 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2500 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
 
2501 **
2502 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2503 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2504 ** </dl>
2505 */
@@ -2535,16 +2567,11 @@
2567 **
2568 ** <ol>
2569 ** <li>
2570 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2571 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2572 ** statement and try to run it again.
 
 
 
 
 
2573 ** </li>
2574 **
2575 ** <li>
2576 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2577 ** [error codes] or [extended error codes]. ^The legacy behavior was that
@@ -2553,15 +2580,20 @@
2580 ** in order to find the underlying cause of the problem. With the "v2" prepare
2581 ** interfaces, the underlying reason for the error is returned immediately.
2582 ** </li>
2583 **
2584 ** <li>
2585 ** ^If the specific value bound to [parameter | host parameter] in the
2586 ** WHERE clause might influence the choice of query plan for a statement,
2587 ** then the statement will be automatically recompiled, as if there had been
2588 ** a schema change, on the first [sqlite3_step()] call following any change
2589 ** to the [sqlite3_bind_text | bindings] of that [parameter].
2590 ** ^The specific value of WHERE-clause [parameter] might influence the
2591 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
2592 ** or [GLOB] operator or if the parameter is compared to an indexed column
2593 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
2594 ** the
2595 ** </li>
2596 ** </ol>
2597 */
2598 SQLITE_API int sqlite3_prepare(
2599 sqlite3 *db, /* Database handle */
@@ -2624,11 +2656,11 @@
2656 ** or if SQLite is run in one of reduced mutex modes
2657 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
2658 ** then there is no distinction between protected and unprotected
2659 ** sqlite3_value objects and they can be used interchangeably. However,
2660 ** for maximum code portability it is recommended that applications
2661 ** still make the distinction between protected and unprotected
2662 ** sqlite3_value objects even when not strictly required.
2663 **
2664 ** ^The sqlite3_value objects that are passed as parameters into the
2665 ** implementation of [application-defined SQL functions] are protected.
2666 ** ^The sqlite3_value object returned by
@@ -2819,10 +2851,12 @@
2851 ** CAPI3REF: Number Of Columns In A Result Set
2852 **
2853 ** ^Return the number of columns in the result set returned by the
2854 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
2855 ** statement that does not return data (for example an [UPDATE]).
2856 **
2857 ** See also: [sqlite3_data_count()]
2858 */
2859 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
2860
2861 /*
2862 ** CAPI3REF: Column Names In A Result Set
@@ -3009,12 +3043,18 @@
3043 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3044
3045 /*
3046 ** CAPI3REF: Number of columns in a result set
3047 **
3048 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3049 ** current row of the result set of [prepared statement] P.
3050 ** ^If prepared statement P does not have results ready to return
3051 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3052 ** interfaces) then sqlite3_data_count(P) returns 0.
3053 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3054 **
3055 ** See also: [sqlite3_column_count()]
3056 */
3057 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3058
3059 /*
3060 ** CAPI3REF: Fundamental Datatypes
@@ -3090,22 +3130,30 @@
3130 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3131 ** the string to UTF-8 and then returns the number of bytes.
3132 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3133 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3134 ** the number of bytes in that string.
3135 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3136 **
3137 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3138 ** routine returns the number of bytes in that BLOB or string.
3139 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3140 ** the string to UTF-16 and then returns the number of bytes.
3141 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3142 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3143 ** the number of bytes in that string.
3144 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3145 **
3146 ** ^The values returned by [sqlite3_column_bytes()] and
3147 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3148 ** of the string. ^For clarity: the values returned by
3149 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3150 ** bytes in the string, not the number of characters.
3151 **
3152 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3153 ** even empty strings, are always zero terminated. ^The return
3154 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
 
 
 
 
 
3155 **
3156 ** ^The object returned by [sqlite3_column_value()] is an
3157 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3158 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3159 ** If the [unprotected sqlite3_value] object returned by
@@ -3146,14 +3194,14 @@
3194 ** and atof(). SQLite does not really use these functions. It has its
3195 ** own equivalent internal routines. The atoi() and atof() names are
3196 ** used in the table for brevity and because they are familiar to most
3197 ** C programmers.
3198 **
3199 ** Note that when type conversions occur, pointers returned by prior
3200 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3201 ** sqlite3_column_text16() may be invalidated.
3202 ** Type conversions and pointer invalidations might occur
3203 ** in the following cases:
3204 **
3205 ** <ul>
3206 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3207 ** sqlite3_column_text16() is called. A zero-terminator might
@@ -3162,26 +3210,26 @@
3210 ** sqlite3_column_text16() is called. The content must be converted
3211 ** to UTF-16.</li>
3212 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3213 ** sqlite3_column_text() is called. The content must be converted
3214 ** to UTF-8.</li>
3215 ** </ul>
3216 **
3217 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3218 ** not invalidate a prior pointer, though of course the content of the buffer
3219 ** that the prior pointer references will have been modified. Other kinds
3220 ** of conversion are done in place when it is possible, but sometimes they
3221 ** are not possible and in those cases prior pointers are invalidated.
3222 **
3223 ** The safest and easiest to remember policy is to invoke these routines
3224 ** in one of the following ways:
3225 **
3226 ** <ul>
3227 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3228 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3229 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3230 ** </ul>
3231 **
3232 ** In other words, you should call sqlite3_column_text(),
3233 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3234 ** into the desired format, then invoke sqlite3_column_bytes() or
3235 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
@@ -3215,21 +3263,30 @@
3263
3264 /*
3265 ** CAPI3REF: Destroy A Prepared Statement Object
3266 **
3267 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3268 ** ^If the most recent evaluation of the statement encountered no errors or
3269 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3270 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3271 ** sqlite3_finalize(S) returns the appropriate [error code] or
3272 ** [extended error code].
3273 **
3274 ** ^The sqlite3_finalize(S) routine can be called at any point during
3275 ** the life cycle of [prepared statement] S:
3276 ** before statement S is ever evaluated, after
3277 ** one or more calls to [sqlite3_reset()], or after any call
3278 ** to [sqlite3_step()] regardless of whether or not the statement has
3279 ** completed execution.
3280 **
3281 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3282 **
3283 ** The application must finalize every [prepared statement] in order to avoid
3284 ** resource leaks. It is a grievous error for the application to try to use
3285 ** a prepared statement after it has been finalized. Any use of a prepared
3286 ** statement after it has been finalized can result in undefined and
3287 ** undesirable behavior such as segfaults and heap corruption.
3288 */
3289 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3290
3291 /*
3292 ** CAPI3REF: Reset A Prepared Statement Object
@@ -3261,40 +3318,42 @@
3318 ** CAPI3REF: Create Or Redefine SQL Functions
3319 ** KEYWORDS: {function creation routines}
3320 ** KEYWORDS: {application-defined SQL function}
3321 ** KEYWORDS: {application-defined SQL functions}
3322 **
3323 ** ^These functions (collectively known as "function creation routines")
3324 ** are used to add SQL functions or aggregates or to redefine the behavior
3325 ** of existing SQL functions or aggregates. The only differences between
3326 ** these routines are the text encoding expected for
3327 ** the the second parameter (the name of the function being created)
3328 ** and the presence or absence of a destructor callback for
3329 ** the application data pointer.
3330 **
3331 ** ^The first parameter is the [database connection] to which the SQL
3332 ** function is to be added. ^If an application uses more than one database
3333 ** connection then application-defined SQL functions must be added
3334 ** to each database connection separately.
3335 **
3336 ** ^The second parameter is the name of the SQL function to be created or
3337 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
3338 ** representation, exclusive of the zero-terminator. ^Note that the name
3339 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
3340 ** ^Any attempt to create a function with a longer name
3341 ** will result in [SQLITE_MISUSE] being returned.
3342 **
3343 ** ^The third parameter (nArg)
3344 ** is the number of arguments that the SQL function or
3345 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3346 ** aggregate may take any number of arguments between 0 and the limit
3347 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
3348 ** parameter is less than -1 or greater than 127 then the behavior is
3349 ** undefined.
3350 **
3351 ** ^The fourth parameter, eTextRep, specifies what
3352 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3353 ** its parameters. Every SQL function implementation must be able to work
3354 ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
3355 ** more efficient with one encoding than another. ^An application may
3356 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3357 ** times with the same function but with different values of eTextRep.
3358 ** ^When multiple implementations of the same function are available, SQLite
3359 ** will pick the one that involves the least amount of data conversion.
@@ -3302,17 +3361,25 @@
3361 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3362 **
3363 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
3364 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3365 **
3366 ** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3367 ** pointers to C-language functions that implement the SQL function or
3368 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3369 ** callback only; NULL pointers must be passed as the xStep and xFinal
3370 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3371 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3372 ** SQL function or aggregate, pass NULL poiners for all three function
3373 ** callbacks.
3374 **
3375 ** ^If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3376 ** then it is invoked when the function is deleted, either by being
3377 ** overloaded or when the database connection closes.
3378 ** ^When the destructure callback of the tenth parameter is invoked, it
3379 ** is passed a single argument which is a copy of the pointer which was
3380 ** the fifth parameter to sqlite3_create_function_v2().
3381 **
3382 ** ^It is permitted to register multiple implementations of the same
3383 ** functions with the same name but with either differing numbers of
3384 ** arguments or differing preferred text encodings. ^SQLite will use
3385 ** the implementation that most closely matches the way in which the
@@ -3324,15 +3391,10 @@
3391 ** ^A function where the encoding difference is between UTF16le and UTF16be
3392 ** is a closer match than a function where the encoding difference is
3393 ** between UTF8 and UTF16.
3394 **
3395 ** ^Built-in functions may be overloaded by new application-defined functions.
 
 
 
 
 
3396 **
3397 ** ^An application-defined function is permitted to call other
3398 ** SQLite interfaces. However, such calls must not
3399 ** close the database connection nor finalize or reset the prepared
3400 ** statement in which the function is running.
@@ -3354,10 +3416,21 @@
3416 int eTextRep,
3417 void *pApp,
3418 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3419 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3420 void (*xFinal)(sqlite3_context*)
3421 );
3422 SQLITE_API int sqlite3_create_function_v2(
3423 sqlite3 *db,
3424 const char *zFunctionName,
3425 int nArg,
3426 int eTextRep,
3427 void *pApp,
3428 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3429 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3430 void (*xFinal)(sqlite3_context*),
3431 void(*xDestroy)(void*)
3432 );
3433
3434 /*
3435 ** CAPI3REF: Text Encodings
3436 **
@@ -3701,73 +3774,97 @@
3774 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
3775
3776 /*
3777 ** CAPI3REF: Define New Collating Sequences
3778 **
3779 ** ^These functions add, remove, or modify a [collation] associated
3780 ** with the [database connection] specified as the first argument.
3781 **
3782 ** ^The name of the collation is a UTF-8 string
3783 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
3784 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
3785 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
3786 ** considered to be the same name.
3787 **
3788 ** ^(The third argument (eTextRep) must be one of the constants:
3789 ** <ul>
3790 ** <li> [SQLITE_UTF8],
3791 ** <li> [SQLITE_UTF16LE],
3792 ** <li> [SQLITE_UTF16BE],
3793 ** <li> [SQLITE_UTF16], or
3794 ** <li> [SQLITE_UTF16_ALIGNED].
3795 ** </ul>)^
3796 ** ^The eTextRep argument determines the encoding of strings passed
3797 ** to the collating function callback, xCallback.
3798 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
3799 ** force strings to be UTF16 with native byte order.
3800 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
3801 ** on an even byte address.
3802 **
3803 ** ^The fourth argument, pArg, is a application data pointer that is passed
3804 ** through as the first argument to the collating function callback.
3805 **
3806 ** ^The fifth argument, xCallback, is a pointer to the collating function.
3807 ** ^Multiple collating functions can be registered using the same name but
3808 ** with different eTextRep parameters and SQLite will use whichever
3809 ** function requires the least amount of data transformation.
3810 ** ^If the xCallback argument is NULL then the collating function is
3811 ** deleted. ^When all collating functions having the same name are deleted,
3812 ** that collation is no longer usable.
3813 **
3814 ** ^The collating function callback is invoked with a copy of the pArg
3815 ** application data pointer and with two strings in the encoding specified
3816 ** by the eTextRep argument. The collating function must return an
3817 ** integer that is negative, zero, or positive
3818 ** if the first string is less than, equal to, or greater than the second,
3819 ** respectively. A collating function must alway return the same answer
3820 ** given the same inputs. If two or more collating functions are registered
3821 ** to the same collation name (using different eTextRep values) then all
3822 ** must give an equivalent answer when invoked with equivalent strings.
3823 ** The collating function must obey the following properties for all
3824 ** strings A, B, and C:
3825 **
3826 ** <ol>
3827 ** <li> If A==B then B==A.
3828 ** <li> If A==B and B==C then A==C.
3829 ** <li> If A&lt;B THEN B&gt;A.
3830 ** <li> If A&lt;B and B&lt;C then A&lt;C.
3831 ** </ol>
3832 **
3833 ** If a collating function fails any of the above constraints and that
3834 ** collating function is registered and used, then the behavior of SQLite
3835 ** is undefined.
3836 **
3837 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
3838 ** with the addition that the xDestroy callback is invoked on pArg when
3839 ** the collating function is deleted.
3840 ** ^Collating functions are deleted when they are overridden by later
3841 ** calls to the collation creation functions or when the
3842 ** [database connection] is closed using [sqlite3_close()].
 
 
3843 **
3844 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
3845 */
3846 SQLITE_API int sqlite3_create_collation(
3847 sqlite3*,
3848 const char *zName,
3849 int eTextRep,
3850 void *pArg,
3851 int(*xCompare)(void*,int,const void*,int,const void*)
3852 );
3853 SQLITE_API int sqlite3_create_collation_v2(
3854 sqlite3*,
3855 const char *zName,
3856 int eTextRep,
3857 void *pArg,
3858 int(*xCompare)(void*,int,const void*,int,const void*),
3859 void(*xDestroy)(void*)
3860 );
3861 SQLITE_API int sqlite3_create_collation16(
3862 sqlite3*,
3863 const void *zName,
3864 int eTextRep,
3865 void *pArg,
3866 int(*xCompare)(void*,int,const void*,int,const void*)
3867 );
3868
3869 /*
3870 ** CAPI3REF: Collation Needed Callbacks
@@ -3852,20 +3949,23 @@
3949 #endif
3950
3951 /*
3952 ** CAPI3REF: Suspend Execution For A Short Time
3953 **
3954 ** The sqlite3_sleep() function causes the current thread to suspend execution
3955 ** for at least a number of milliseconds specified in its parameter.
3956 **
3957 ** If the operating system does not support sleep requests with
3958 ** millisecond time resolution, then the time will be rounded up to
3959 ** the nearest second. The number of milliseconds of sleep actually
3960 ** requested from the operating system is returned.
3961 **
3962 ** ^SQLite implements this interface by calling the xSleep()
3963 ** method of the default [sqlite3_vfs] object. If the xSleep() method
3964 ** of the default VFS is not implemented correctly, or not implemented at
3965 ** all, then the behavior of sqlite3_sleep() may deviate from the description
3966 ** in the previous paragraphs.
3967 */
3968 SQLITE_API int sqlite3_sleep(int);
3969
3970 /*
3971 ** CAPI3REF: Name Of The Folder Holding Temporary Files
@@ -4083,44 +4183,77 @@
4183 ** of heap memory by deallocating non-essential memory allocations
4184 ** held by the database library. Memory used to cache database
4185 ** pages to improve performance is an example of non-essential memory.
4186 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4187 ** which might be more or less than the amount requested.
4188 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4189 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4190 */
4191 SQLITE_API int sqlite3_release_memory(int);
4192
4193 /*
4194 ** CAPI3REF: Impose A Limit On Heap Size
4195 **
4196 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4197 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4198 ** ^SQLite strives to keep heap memory utilization below the soft heap
4199 ** limit by reducing the number of pages held in the page cache
4200 ** as heap memory usages approaches the limit.
4201 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4202 ** below the limit, it will exceed the limit rather than generate
4203 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
4204 ** is advisory only.
4205 **
4206 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4207 ** the soft heap limit prior to the call. ^If the argument N is negative
4208 ** then no change is made to the soft heap limit. Hence, the current
4209 ** size of the soft heap limit can be determined by invoking
4210 ** sqlite3_soft_heap_limit64() with a negative argument.
4211 **
4212 ** ^If the argument N is zero then the soft heap limit is disabled.
4213 **
4214 ** ^(The soft heap limit is not enforced in the current implementation
4215 ** if one or more of following conditions are true:
4216 **
4217 ** <ul>
4218 ** <li> The soft heap limit is set to zero.
4219 ** <li> Memory accounting is disabled using a combination of the
4220 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4221 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4222 ** <li> An alternative page cache implementation is specifed using
4223 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4224 ** <li> The page cache allocates from its own memory pool supplied
4225 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4226 ** from the heap.
4227 ** </ul>)^
4228 **
4229 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4230 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4231 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4232 ** the soft heap limit is enforced on every memory allocation. Without
4233 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4234 ** when memory is allocated by the page cache. Testing suggests that because
4235 ** the page cache is the predominate memory user in SQLite, most
4236 ** applications will achieve adequate soft heap limit enforcement without
4237 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4238 **
4239 ** The circumstances under which SQLite will enforce the soft heap limit may
4240 ** changes in future releases of SQLite.
4241 */
4242 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4243
4244 /*
4245 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4246 ** DEPRECATED
4247 **
4248 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4249 ** interface. This routine is provided for historical compatibility
4250 ** only. All new applications should use the
4251 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4252 */
4253 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4254
4255
4256 /*
4257 ** CAPI3REF: Extract Metadata About A Column Of A Table
4258 **
4259 ** ^This routine returns metadata about a specific column of a specific
@@ -4240,38 +4373,51 @@
4373 ** it back off again.
4374 */
4375 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4376
4377 /*
4378 ** CAPI3REF: Automatically Load Statically Linked Extensions
4379 **
4380 ** ^This interface causes the xEntryPoint() function to be invoked for
4381 ** each new [database connection] that is created. The idea here is that
4382 ** xEntryPoint() is the entry point for a statically linked SQLite extension
4383 ** that is to be automatically loaded into all new database connections.
4384 **
4385 ** ^(Even though the function prototype shows that xEntryPoint() takes
4386 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
4387 ** arguments and expects and integer result as if the signature of the
4388 ** entry point where as follows:
4389 **
4390 ** <blockquote><pre>
4391 ** &nbsp; int xEntryPoint(
4392 ** &nbsp; sqlite3 *db,
4393 ** &nbsp; const char **pzErrMsg,
4394 ** &nbsp; const struct sqlite3_api_routines *pThunk
4395 ** &nbsp; );
4396 ** </pre></blockquote>)^
4397 **
4398 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4399 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4400 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
4401 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
4402 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
4403 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4404 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4405 **
4406 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4407 ** on the list of automatic extensions is a harmless no-op. ^No entry point
4408 ** will be called more than once for each database connection that is opened.
4409 **
4410 ** See also: [sqlite3_reset_auto_extension()].
4411 */
4412 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4413
4414 /*
4415 ** CAPI3REF: Reset Automatic Extension Loading
4416 **
4417 ** ^This interface disables all automatic extensions previously
4418 ** registered using [sqlite3_auto_extension()].
 
 
 
4419 */
4420 SQLITE_API void sqlite3_reset_auto_extension(void);
4421
4422 /*
4423 ** The interface to the virtual-table mechanism is currently considered
@@ -4906,11 +5052,11 @@
5052 ** output variable when querying the system for the current mutex
5053 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5054 **
5055 ** ^The xMutexInit method defined by this structure is invoked as
5056 ** part of system initialization by the sqlite3_initialize() function.
5057 ** ^The xMutexInit routine is called by SQLite exactly once for each
5058 ** effective call to [sqlite3_initialize()].
5059 **
5060 ** ^The xMutexEnd method defined by this structure is invoked as
5061 ** part of system shutdown by the sqlite3_shutdown() function. The
5062 ** implementation of this method is expected to release all outstanding
@@ -5103,11 +5249,12 @@
5249 #define SQLITE_TESTCTRL_ALWAYS 13
5250 #define SQLITE_TESTCTRL_RESERVE 14
5251 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
5252 #define SQLITE_TESTCTRL_ISKEYWORD 16
5253 #define SQLITE_TESTCTRL_PGHDRSZ 17
5254 #define SQLITE_TESTCTRL_SCRATCHMALLOC 18
5255 #define SQLITE_TESTCTRL_LAST 18
5256
5257 /*
5258 ** CAPI3REF: SQLite Runtime Status
5259 **
5260 ** ^This interface is used to retrieve runtime status information
@@ -5122,11 +5269,11 @@
5269 ** value. For those parameters
5270 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5271 ** ^(Other parameters record only the highwater mark and not the current
5272 ** value. For these latter parameters nothing is written into *pCurrent.)^
5273 **
5274 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5275 ** non-zero [error code] on failure.
5276 **
5277 ** This routine is threadsafe but is not atomic. This routine can be
5278 ** called while other threads are running the same or different SQLite
5279 ** interfaces. However the values returned in *pCurrent and
@@ -5172,11 +5319,11 @@
5319 ** [SQLITE_CONFIG_PAGECACHE]. The
5320 ** value returned is in pages, not in bytes.</dd>)^
5321 **
5322 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5323 ** <dd>This parameter returns the number of bytes of page cache
5324 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
5325 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
5326 ** returned value includes allocations that overflowed because they
5327 ** where too large (they were larger than the "sz" parameter to
5328 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5329 ** no space was left in the page cache.</dd>)^
@@ -5195,11 +5342,11 @@
5342 ** outstanding at time, this parameter also reports the number of threads
5343 ** using scratch memory at the same time.</dd>)^
5344 **
5345 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5346 ** <dd>This parameter returns the number of bytes of scratch memory
5347 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
5348 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
5349 ** returned include overflows because the requested allocation was too
5350 ** larger (that is, because the requested allocation was larger than the
5351 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5352 ** slots were available.
@@ -5243,10 +5390,13 @@
5390 **
5391 ** ^The current value of the requested parameter is written into *pCur
5392 ** and the highest instantaneous value is written into *pHiwtr. ^If
5393 ** the resetFlg is true, then the highest instantaneous value is
5394 ** reset back down to the current value.
5395 **
5396 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5397 ** non-zero [error code] on failure.
5398 **
5399 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5400 */
5401 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5402
@@ -5370,122 +5520,134 @@
5520 ** CAPI3REF: Application Defined Page Cache.
5521 ** KEYWORDS: {page cache}
5522 **
5523 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5524 ** register an alternative page cache implementation by passing in an
5525 ** instance of the sqlite3_pcache_methods structure.)^
5526 ** In many applications, most of the heap memory allocated by
5527 ** SQLite is used for the page cache.
5528 ** By implementing a
5529 ** custom page cache using this API, an application can better control
5530 ** the amount of memory consumed by SQLite, the way in which
5531 ** that memory is allocated and released, and the policies used to
5532 ** determine exactly which parts of a database file are cached and for
5533 ** how long.
5534 **
5535 ** The alternative page cache mechanism is an
5536 ** extreme measure that is only needed by the most demanding applications.
5537 ** The built-in page cache is recommended for most uses.
5538 **
5539 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5540 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
5541 ** the application may discard the parameter after the call to
5542 ** [sqlite3_config()] returns.)^
5543 **
5544 ** ^(The xInit() method is called once for each effective
5545 ** call to [sqlite3_initialize()])^
5546 ** (usually only once during the lifetime of the process). ^(The xInit()
5547 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5548 ** The intent of the xInit() method is to set up global data structures
5549 ** required by the custom page cache implementation.
5550 ** ^(If the xInit() method is NULL, then the
5551 ** built-in default page cache is used instead of the application defined
5552 ** page cache.)^
5553 **
5554 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
5555 ** It can be used to clean up
5556 ** any outstanding resources before process shutdown, if required.
5557 ** ^The xShutdown() method may be NULL.
5558 **
5559 ** ^SQLite automatically serializes calls to the xInit method,
5560 ** so the xInit method need not be threadsafe. ^The
5561 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5562 ** not need to be threadsafe either. All other methods must be threadsafe
5563 ** in multithreaded applications.
5564 **
5565 ** ^SQLite will never invoke xInit() more than once without an intervening
5566 ** call to xShutdown().
5567 **
5568 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
5569 ** SQLite will typically create one cache instance for each open database file,
5570 ** though this is not guaranteed. ^The
5571 ** first parameter, szPage, is the size in bytes of the pages that must
5572 ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
5573 ** will the page size of the database file that is to be cached plus an
5574 ** increment (here called "R") of about 100 or 200. SQLite will use the
5575 ** extra R bytes on each page to store metadata about the underlying
5576 ** database page on disk. The value of R depends
5577 ** on the SQLite version, the target platform, and how SQLite was compiled.
5578 ** ^R is constant for a particular build of SQLite. ^The second argument to
5579 ** xCreate(), bPurgeable, is true if the cache being created will
5580 ** be used to cache database pages of a file stored on disk, or
5581 ** false if it is used for an in-memory database. The cache implementation
5582 ** does not have to do anything special based with the value of bPurgeable;
5583 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
5584 ** never invoke xUnpin() except to deliberately delete a page.
5585 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
5586 ** false will always have the "discard" flag set to true.
5587 ** ^Hence, a cache created with bPurgeable false will
5588 ** never contain any unpinned pages.
5589 **
5590 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5591 ** suggested maximum cache-size (number of pages stored by) the cache
5592 ** instance passed as the first argument. This is the value configured using
5593 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
5594 ** parameter, the implementation is not required to do anything with this
5595 ** value; it is advisory only.
5596 **
5597 ** The xPagecount() method must return the number of pages currently
5598 ** stored in the cache, both pinned and unpinned.
5599 **
5600 ** The xFetch() method locates a page in the cache and returns a pointer to
5601 ** the page, or a NULL pointer.
5602 ** A "page", in this context, means a buffer of szPage bytes aligned at an
5603 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
5604 ** mimimum key value is 1. After it has been retrieved using xFetch, the page
5605 ** is considered to be "pinned".
5606 **
5607 ** If the requested page is already in the page cache, then the page cache
5608 ** implementation must return a pointer to the page buffer with its content
5609 ** intact. If the requested page is not already in the cache, then the
5610 ** behavior of the cache implementation should use the value of the createFlag
5611 ** parameter to help it determined what action to take:
5612 **
5613 ** <table border=1 width=85% align=center>
5614 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5615 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
5616 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5617 ** Otherwise return NULL.
5618 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
5619 ** NULL if allocating a new page is effectively impossible.
5620 ** </table>
5621 **
5622 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
5623 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
5624 ** failed.)^ In between the to xFetch() calls, SQLite may
5625 ** attempt to unpin one or more cache pages by spilling the content of
5626 ** pinned pages to disk and synching the operating system disk cache.
 
 
5627 **
5628 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5629 ** as its second argument. If the third parameter, discard, is non-zero,
5630 ** then the page must be evicted from the cache.
5631 ** ^If the discard parameter is
5632 ** zero, then the page may be discarded or retained at the discretion of
5633 ** page cache implementation. ^The page cache implementation
5634 ** may choose to evict unpinned pages at any time.
5635 **
5636 ** The cache must not perform any reference counting. A single
5637 ** call to xUnpin() unpins the page regardless of the number of prior calls
5638 ** to xFetch().
5639 **
5640 ** The xRekey() method is used to change the key value associated with the
5641 ** page passed as the second argument. If the cache
5642 ** previously contains an entry associated with newKey, it must be
5643 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5644 ** to be pinned.
5645 **
5646 ** When SQLite calls the xTruncate() method, the cache must discard all
5647 ** existing cache entries with page numbers (keys) greater than or equal
5648 ** to the value of the iLimit parameter passed to xTruncate(). If any
5649 ** of these pages are pinned, they are implicitly unpinned, meaning that
5650 ** they can be safely discarded.
5651 **
5652 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5653 ** All resources associated with the specified cache should be freed. ^After
@@ -5959,5 +6121,61 @@
6121 #ifdef __cplusplus
6122 } /* End of the 'extern "C"' block */
6123 #endif
6124 #endif
6125
6126 /*
6127 ** 2010 August 30
6128 **
6129 ** The author disclaims copyright to this source code. In place of
6130 ** a legal notice, here is a blessing:
6131 **
6132 ** May you do good and not evil.
6133 ** May you find forgiveness for yourself and forgive others.
6134 ** May you share freely, never taking more than you give.
6135 **
6136 *************************************************************************
6137 */
6138
6139 #ifndef _SQLITE3RTREE_H_
6140 #define _SQLITE3RTREE_H_
6141
6142
6143 #ifdef __cplusplus
6144 extern "C" {
6145 #endif
6146
6147 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6148
6149 /*
6150 ** Register a geometry callback named zGeom that can be used as part of an
6151 ** R-Tree geometry query as follows:
6152 **
6153 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6154 */
6155 SQLITE_API int sqlite3_rtree_geometry_callback(
6156 sqlite3 *db,
6157 const char *zGeom,
6158 int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6159 void *pContext
6160 );
6161
6162
6163 /*
6164 ** A pointer to a structure of the following type is passed as the first
6165 ** argument to callbacks registered using rtree_geometry_callback().
6166 */
6167 struct sqlite3_rtree_geometry {
6168 void *pContext; /* Copy of pContext passed to s_r_g_c() */
6169 int nParam; /* Size of array aParam[] */
6170 double *aParam; /* Parameters passed to SQL geom function */
6171 void *pUser; /* Callback implementation user data */
6172 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
6173 };
6174
6175
6176 #ifdef __cplusplus
6177 } /* end of the 'extern "C"' block */
6178 #endif
6179
6180 #endif /* ifndef _SQLITE3RTREE_H_ */
6181
6182

Keyboard Shortcuts

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